blob: 131762060d1aa4e667f2ba23b8c252a539f0c18d [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.
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001961 enqueueDispatchEntry(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001963 enqueueDispatchEntry(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001965 enqueueDispatchEntry(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001967 enqueueDispatchEntry(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 InputTarget::FLAG_DISPATCH_AS_IS);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001969 enqueueDispatchEntry(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001971 enqueueDispatchEntry(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
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001980void InputDispatcher::enqueueDispatchEntry(
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 }
2057 break;
2058 }
2059 }
2060
2061 // Remember that we are waiting for this dispatch to complete.
2062 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002063 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 }
2065
2066 // Enqueue the dispatch entry.
2067 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002068 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069}
2070
2071void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2072 const sp<Connection>& connection) {
2073#if DEBUG_DISPATCH_CYCLE
2074 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002075 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076#endif
2077
2078 while (connection->status == Connection::STATUS_NORMAL
2079 && !connection->outboundQueue.isEmpty()) {
2080 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2081 dispatchEntry->deliveryTime = currentTime;
2082
2083 // Publish the event.
2084 status_t status;
2085 EventEntry* eventEntry = dispatchEntry->eventEntry;
2086 switch (eventEntry->type) {
2087 case EventEntry::TYPE_KEY: {
2088 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2089
2090 // Publish the key event.
2091 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002092 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2094 keyEntry->keyCode, keyEntry->scanCode,
2095 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2096 keyEntry->eventTime);
2097 break;
2098 }
2099
2100 case EventEntry::TYPE_MOTION: {
2101 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2102
2103 PointerCoords scaledCoords[MAX_POINTERS];
2104 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2105
2106 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002107 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2109 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002110 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2111 float wxs = dispatchEntry->windowXScale;
2112 float wys = dispatchEntry->windowYScale;
2113 xOffset = dispatchEntry->xOffset * wxs;
2114 yOffset = dispatchEntry->yOffset * wys;
2115 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002116 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002118 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119 }
2120 usingCoords = scaledCoords;
2121 }
2122 } else {
2123 xOffset = 0.0f;
2124 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125
2126 // We don't want the dispatch target to know.
2127 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002128 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 scaledCoords[i].clear();
2130 }
2131 usingCoords = scaledCoords;
2132 }
2133 }
2134
2135 // Publish the motion event.
2136 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002137 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002138 dispatchEntry->resolvedAction, motionEntry->actionButton,
2139 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002140 motionEntry->metaState, motionEntry->buttonState, motionEntry->classification,
Michael Wright7b159c92015-05-14 14:48:03 +01002141 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 motionEntry->downTime, motionEntry->eventTime,
2143 motionEntry->pointerCount, motionEntry->pointerProperties,
2144 usingCoords);
2145 break;
2146 }
2147
2148 default:
2149 ALOG_ASSERT(false);
2150 return;
2151 }
2152
2153 // Check the result.
2154 if (status) {
2155 if (status == WOULD_BLOCK) {
2156 if (connection->waitQueue.isEmpty()) {
2157 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2158 "This is unexpected because the wait queue is empty, so the pipe "
2159 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002160 "event to it, status=%d", connection->getInputChannelName().c_str(),
2161 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2163 } else {
2164 // Pipe is full and we are waiting for the app to finish process some events
2165 // before sending more events to it.
2166#if DEBUG_DISPATCH_CYCLE
2167 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2168 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002169 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170#endif
2171 connection->inputPublisherBlocked = true;
2172 }
2173 } else {
2174 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002175 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2177 }
2178 return;
2179 }
2180
2181 // Re-enqueue the event on the wait queue.
2182 connection->outboundQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002183 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184 connection->waitQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002185 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 }
2187}
2188
2189void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2190 const sp<Connection>& connection, uint32_t seq, bool handled) {
2191#if DEBUG_DISPATCH_CYCLE
2192 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002193 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194#endif
2195
2196 connection->inputPublisherBlocked = false;
2197
2198 if (connection->status == Connection::STATUS_BROKEN
2199 || connection->status == Connection::STATUS_ZOMBIE) {
2200 return;
2201 }
2202
2203 // Notify other system components and prepare to start the next dispatch cycle.
2204 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2205}
2206
2207void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2208 const sp<Connection>& connection, bool notify) {
2209#if DEBUG_DISPATCH_CYCLE
2210 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002211 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212#endif
2213
2214 // Clear the dispatch queues.
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002215 drainDispatchQueue(&connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002216 traceOutboundQueueLength(connection);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002217 drainDispatchQueue(&connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002218 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219
2220 // The connection appears to be unrecoverably broken.
2221 // Ignore already broken or zombie connections.
2222 if (connection->status == Connection::STATUS_NORMAL) {
2223 connection->status = Connection::STATUS_BROKEN;
2224
2225 if (notify) {
2226 // Notify other system components.
2227 onDispatchCycleBrokenLocked(currentTime, connection);
2228 }
2229 }
2230}
2231
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002232void InputDispatcher::drainDispatchQueue(Queue<DispatchEntry>* queue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 while (!queue->isEmpty()) {
2234 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002235 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 }
2237}
2238
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002239void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002241 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 }
2243 delete dispatchEntry;
2244}
2245
2246int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2247 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2248
2249 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002250 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251
2252 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2253 if (connectionIndex < 0) {
2254 ALOGE("Received spurious receive callback for unknown input channel. "
2255 "fd=%d, events=0x%x", fd, events);
2256 return 0; // remove the callback
2257 }
2258
2259 bool notify;
2260 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2261 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2262 if (!(events & ALOOPER_EVENT_INPUT)) {
2263 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002264 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 return 1;
2266 }
2267
2268 nsecs_t currentTime = now();
2269 bool gotOne = false;
2270 status_t status;
2271 for (;;) {
2272 uint32_t seq;
2273 bool handled;
2274 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2275 if (status) {
2276 break;
2277 }
2278 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2279 gotOne = true;
2280 }
2281 if (gotOne) {
2282 d->runCommandsLockedInterruptible();
2283 if (status == WOULD_BLOCK) {
2284 return 1;
2285 }
2286 }
2287
2288 notify = status != DEAD_OBJECT || !connection->monitor;
2289 if (notify) {
2290 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002291 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 }
2293 } else {
2294 // Monitor channels are never explicitly unregistered.
2295 // We do it automatically when the remote endpoint is closed so don't warn
2296 // about them.
2297 notify = !connection->monitor;
2298 if (notify) {
2299 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002300 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
2302 }
2303
2304 // Unregister the channel.
2305 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2306 return 0; // remove the callback
2307 } // release lock
2308}
2309
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002310void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked (
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 const CancelationOptions& options) {
2312 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2313 synthesizeCancelationEventsForConnectionLocked(
2314 mConnectionsByFd.valueAt(i), options);
2315 }
2316}
2317
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002318void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked (
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002319 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002320 for (auto& it : mMonitoringChannelsByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002321 const std::vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002322 const size_t numChannels = monitoringChannels.size();
2323 for (size_t i = 0; i < numChannels; i++) {
2324 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2325 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002326 }
2327}
2328
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2330 const sp<InputChannel>& channel, const CancelationOptions& options) {
2331 ssize_t index = getConnectionIndexLocked(channel);
2332 if (index >= 0) {
2333 synthesizeCancelationEventsForConnectionLocked(
2334 mConnectionsByFd.valueAt(index), options);
2335 }
2336}
2337
2338void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2339 const sp<Connection>& connection, const CancelationOptions& options) {
2340 if (connection->status == Connection::STATUS_BROKEN) {
2341 return;
2342 }
2343
2344 nsecs_t currentTime = now();
2345
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002346 std::vector<EventEntry*> cancelationEvents;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347 connection->inputState.synthesizeCancelationEvents(currentTime,
2348 cancelationEvents, options);
2349
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002350 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002352 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002354 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 options.reason, options.mode);
2356#endif
2357 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002358 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 switch (cancelationEventEntry->type) {
2360 case EventEntry::TYPE_KEY:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002361 logOutboundKeyDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 static_cast<KeyEntry*>(cancelationEventEntry));
2363 break;
2364 case EventEntry::TYPE_MOTION:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002365 logOutboundMotionDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 static_cast<MotionEntry*>(cancelationEventEntry));
2367 break;
2368 }
2369
2370 InputTarget target;
chaviwfbe5d9c2018-12-26 12:23:37 -08002371 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(
2372 connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002373 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2375 target.xOffset = -windowInfo->frameLeft;
2376 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002377 target.globalScaleFactor = windowInfo->globalScaleFactor;
2378 target.windowXScale = windowInfo->windowXScale;
2379 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 } else {
2381 target.xOffset = 0;
2382 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002383 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384 }
2385 target.inputChannel = connection->inputChannel;
2386 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2387
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002388 enqueueDispatchEntry(connection, cancelationEventEntry, // increments ref
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2390
2391 cancelationEventEntry->release();
2392 }
2393
2394 startDispatchCycleLocked(currentTime, connection);
2395 }
2396}
2397
2398InputDispatcher::MotionEntry*
2399InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2400 ALOG_ASSERT(pointerIds.value != 0);
2401
2402 uint32_t splitPointerIndexMap[MAX_POINTERS];
2403 PointerProperties splitPointerProperties[MAX_POINTERS];
2404 PointerCoords splitPointerCoords[MAX_POINTERS];
2405
2406 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2407 uint32_t splitPointerCount = 0;
2408
2409 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2410 originalPointerIndex++) {
2411 const PointerProperties& pointerProperties =
2412 originalMotionEntry->pointerProperties[originalPointerIndex];
2413 uint32_t pointerId = uint32_t(pointerProperties.id);
2414 if (pointerIds.hasBit(pointerId)) {
2415 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2416 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2417 splitPointerCoords[splitPointerCount].copyFrom(
2418 originalMotionEntry->pointerCoords[originalPointerIndex]);
2419 splitPointerCount += 1;
2420 }
2421 }
2422
2423 if (splitPointerCount != pointerIds.count()) {
2424 // This is bad. We are missing some of the pointers that we expected to deliver.
2425 // Most likely this indicates that we received an ACTION_MOVE events that has
2426 // different pointer ids than we expected based on the previous ACTION_DOWN
2427 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2428 // in this way.
2429 ALOGW("Dropping split motion event because the pointer count is %d but "
2430 "we expected there to be %d pointers. This probably means we received "
2431 "a broken sequence of pointer ids from the input device.",
2432 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002433 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434 }
2435
2436 int32_t action = originalMotionEntry->action;
2437 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2438 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2439 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2440 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2441 const PointerProperties& pointerProperties =
2442 originalMotionEntry->pointerProperties[originalPointerIndex];
2443 uint32_t pointerId = uint32_t(pointerProperties.id);
2444 if (pointerIds.hasBit(pointerId)) {
2445 if (pointerIds.count() == 1) {
2446 // The first/last pointer went down/up.
2447 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2448 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2449 } else {
2450 // A secondary pointer went down/up.
2451 uint32_t splitPointerIndex = 0;
2452 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2453 splitPointerIndex += 1;
2454 }
2455 action = maskedAction | (splitPointerIndex
2456 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2457 }
2458 } else {
2459 // An unrelated pointer changed.
2460 action = AMOTION_EVENT_ACTION_MOVE;
2461 }
2462 }
2463
2464 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002465 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 originalMotionEntry->eventTime,
2467 originalMotionEntry->deviceId,
2468 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002469 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 originalMotionEntry->policyFlags,
2471 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002472 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473 originalMotionEntry->flags,
2474 originalMotionEntry->metaState,
2475 originalMotionEntry->buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002476 originalMotionEntry->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477 originalMotionEntry->edgeFlags,
2478 originalMotionEntry->xPrecision,
2479 originalMotionEntry->yPrecision,
2480 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002481 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482
2483 if (originalMotionEntry->injectionState) {
2484 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2485 splitMotionEntry->injectionState->refCount += 1;
2486 }
2487
2488 return splitMotionEntry;
2489}
2490
2491void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2492#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002493 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494#endif
2495
2496 bool needWake;
2497 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002498 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499
Prabir Pradhan42611e02018-11-27 14:04:02 -08002500 ConfigurationChangedEntry* newEntry =
2501 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502 needWake = enqueueInboundEventLocked(newEntry);
2503 } // release lock
2504
2505 if (needWake) {
2506 mLooper->wake();
2507 }
2508}
2509
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002510/**
2511 * If one of the meta shortcuts is detected, process them here:
2512 * Meta + Backspace -> generate BACK
2513 * Meta + Enter -> generate HOME
2514 * This will potentially overwrite keyCode and metaState.
2515 */
2516void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2517 int32_t& keyCode, int32_t& metaState) {
2518 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2519 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2520 if (keyCode == AKEYCODE_DEL) {
2521 newKeyCode = AKEYCODE_BACK;
2522 } else if (keyCode == AKEYCODE_ENTER) {
2523 newKeyCode = AKEYCODE_HOME;
2524 }
2525 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002526 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002527 struct KeyReplacement replacement = {keyCode, deviceId};
2528 mReplacedKeys.add(replacement, newKeyCode);
2529 keyCode = newKeyCode;
2530 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2531 }
2532 } else if (action == AKEY_EVENT_ACTION_UP) {
2533 // In order to maintain a consistent stream of up and down events, check to see if the key
2534 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2535 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002536 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002537 struct KeyReplacement replacement = {keyCode, deviceId};
2538 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2539 if (index >= 0) {
2540 keyCode = mReplacedKeys.valueAt(index);
2541 mReplacedKeys.removeItemsAt(index);
2542 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2543 }
2544 }
2545}
2546
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2548#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002549 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002550 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002551 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002552 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002554 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555#endif
2556 if (!validateKeyEvent(args->action)) {
2557 return;
2558 }
2559
2560 uint32_t policyFlags = args->policyFlags;
2561 int32_t flags = args->flags;
2562 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002563 // InputDispatcher tracks and generates key repeats on behalf of
2564 // whatever notifies it, so repeatCount should always be set to 0
2565 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2567 policyFlags |= POLICY_FLAG_VIRTUAL;
2568 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2569 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 if (policyFlags & POLICY_FLAG_FUNCTION) {
2571 metaState |= AMETA_FUNCTION_ON;
2572 }
2573
2574 policyFlags |= POLICY_FLAG_TRUSTED;
2575
Michael Wright78f24442014-08-06 15:55:28 -07002576 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002577 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002578
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002580 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002581 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 args->downTime, args->eventTime);
2583
Michael Wright2b3c3302018-03-02 17:19:13 +00002584 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002586 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2587 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2588 std::to_string(t.duration().count()).c_str());
2589 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002590
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591 bool needWake;
2592 { // acquire lock
2593 mLock.lock();
2594
2595 if (shouldSendKeyToInputFilterLocked(args)) {
2596 mLock.unlock();
2597
2598 policyFlags |= POLICY_FLAG_FILTERED;
2599 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2600 return; // event was consumed by the filter
2601 }
2602
2603 mLock.lock();
2604 }
2605
Prabir Pradhan42611e02018-11-27 14:04:02 -08002606 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002607 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002608 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 metaState, repeatCount, args->downTime);
2610
2611 needWake = enqueueInboundEventLocked(newEntry);
2612 mLock.unlock();
2613 } // release lock
2614
2615 if (needWake) {
2616 mLooper->wake();
2617 }
2618}
2619
2620bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2621 return mInputFilterEnabled;
2622}
2623
2624void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2625#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002626 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2627 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002628 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002629 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2630 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002631 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002632 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002633 for (uint32_t i = 0; i < args->pointerCount; i++) {
2634 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2635 "x=%f, y=%f, pressure=%f, size=%f, "
2636 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2637 "orientation=%f",
2638 i, args->pointerProperties[i].id,
2639 args->pointerProperties[i].toolType,
2640 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2641 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2642 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2643 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2644 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2645 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2646 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2647 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2648 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2649 }
2650#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002651 if (!validateMotionEvent(args->action, args->actionButton,
2652 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 return;
2654 }
2655
2656 uint32_t policyFlags = args->policyFlags;
2657 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002658
2659 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002660 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002661 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2662 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2663 std::to_string(t.duration().count()).c_str());
2664 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665
2666 bool needWake;
2667 { // acquire lock
2668 mLock.lock();
2669
2670 if (shouldSendMotionToInputFilterLocked(args)) {
2671 mLock.unlock();
2672
2673 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002674 event.initialize(args->deviceId, args->source, args->displayId,
2675 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002676 args->flags, args->edgeFlags, args->metaState, args->buttonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002677 args->classification, 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678 args->downTime, args->eventTime,
2679 args->pointerCount, args->pointerProperties, args->pointerCoords);
2680
2681 policyFlags |= POLICY_FLAG_FILTERED;
2682 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2683 return; // event was consumed by the filter
2684 }
2685
2686 mLock.lock();
2687 }
2688
2689 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002690 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002691 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002692 args->action, args->actionButton, args->flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002693 args->metaState, args->buttonState, args->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002695 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696
2697 needWake = enqueueInboundEventLocked(newEntry);
2698 mLock.unlock();
2699 } // release lock
2700
2701 if (needWake) {
2702 mLooper->wake();
2703 }
2704}
2705
2706bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002707 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708}
2709
2710void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2711#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002712 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2713 "switchMask=0x%08x",
2714 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715#endif
2716
2717 uint32_t policyFlags = args->policyFlags;
2718 policyFlags |= POLICY_FLAG_TRUSTED;
2719 mPolicy->notifySwitch(args->eventTime,
2720 args->switchValues, args->switchMask, policyFlags);
2721}
2722
2723void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2724#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002725 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726 args->eventTime, args->deviceId);
2727#endif
2728
2729 bool needWake;
2730 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002731 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732
Prabir Pradhan42611e02018-11-27 14:04:02 -08002733 DeviceResetEntry* newEntry =
2734 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735 needWake = enqueueInboundEventLocked(newEntry);
2736 } // release lock
2737
2738 if (needWake) {
2739 mLooper->wake();
2740 }
2741}
2742
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002743int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2745 uint32_t policyFlags) {
2746#if DEBUG_INBOUND_EVENT_DETAILS
2747 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002748 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2749 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750#endif
2751
2752 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2753
2754 policyFlags |= POLICY_FLAG_INJECTED;
2755 if (hasInjectionPermission(injectorPid, injectorUid)) {
2756 policyFlags |= POLICY_FLAG_TRUSTED;
2757 }
2758
2759 EventEntry* firstInjectedEntry;
2760 EventEntry* lastInjectedEntry;
2761 switch (event->getType()) {
2762 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002763 KeyEvent keyEvent;
2764 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2765 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766 if (! validateKeyEvent(action)) {
2767 return INPUT_EVENT_INJECTION_FAILED;
2768 }
2769
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002770 int32_t flags = keyEvent.getFlags();
2771 int32_t keyCode = keyEvent.getKeyCode();
2772 int32_t metaState = keyEvent.getMetaState();
2773 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2774 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002775 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002776 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002777 keyEvent.getDownTime(), keyEvent.getEventTime());
2778
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2780 policyFlags |= POLICY_FLAG_VIRTUAL;
2781 }
2782
2783 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002784 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002785 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002786 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2787 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2788 std::to_string(t.duration().count()).c_str());
2789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790 }
2791
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002793 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002794 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002796 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2797 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002798 lastInjectedEntry = firstInjectedEntry;
2799 break;
2800 }
2801
2802 case AINPUT_EVENT_TYPE_MOTION: {
2803 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002804 int32_t action = motionEvent->getAction();
2805 size_t pointerCount = motionEvent->getPointerCount();
2806 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002807 int32_t actionButton = motionEvent->getActionButton();
Charles Chen3611f1f2019-01-29 17:26:18 +08002808 int32_t displayId = motionEvent->getDisplayId();
Michael Wright7b159c92015-05-14 14:48:03 +01002809 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 return INPUT_EVENT_INJECTION_FAILED;
2811 }
2812
2813 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2814 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002815 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002816 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002817 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2818 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2819 std::to_string(t.duration().count()).c_str());
2820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 }
2822
2823 mLock.lock();
2824 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2825 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002826 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002827 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2828 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002829 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002831 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002833 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002834 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2835 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836 lastInjectedEntry = firstInjectedEntry;
2837 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2838 sampleEventTimes += 1;
2839 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002840 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2841 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002842 motionEvent->getDeviceId(), motionEvent->getSource(),
2843 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002844 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002846 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002848 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002849 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2850 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 lastInjectedEntry->next = nextInjectedEntry;
2852 lastInjectedEntry = nextInjectedEntry;
2853 }
2854 break;
2855 }
2856
2857 default:
2858 ALOGW("Cannot inject event of type %d", event->getType());
2859 return INPUT_EVENT_INJECTION_FAILED;
2860 }
2861
2862 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2863 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2864 injectionState->injectionIsAsync = true;
2865 }
2866
2867 injectionState->refCount += 1;
2868 lastInjectedEntry->injectionState = injectionState;
2869
2870 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002871 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872 EventEntry* nextEntry = entry->next;
2873 needWake |= enqueueInboundEventLocked(entry);
2874 entry = nextEntry;
2875 }
2876
2877 mLock.unlock();
2878
2879 if (needWake) {
2880 mLooper->wake();
2881 }
2882
2883 int32_t injectionResult;
2884 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002885 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886
2887 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2888 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2889 } else {
2890 for (;;) {
2891 injectionResult = injectionState->injectionResult;
2892 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2893 break;
2894 }
2895
2896 nsecs_t remainingTimeout = endTime - now();
2897 if (remainingTimeout <= 0) {
2898#if DEBUG_INJECTION
2899 ALOGD("injectInputEvent - Timed out waiting for injection result "
2900 "to become available.");
2901#endif
2902 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2903 break;
2904 }
2905
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002906 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907 }
2908
2909 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2910 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2911 while (injectionState->pendingForegroundDispatches != 0) {
2912#if DEBUG_INJECTION
2913 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2914 injectionState->pendingForegroundDispatches);
2915#endif
2916 nsecs_t remainingTimeout = endTime - now();
2917 if (remainingTimeout <= 0) {
2918#if DEBUG_INJECTION
2919 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2920 "dispatches to finish.");
2921#endif
2922 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2923 break;
2924 }
2925
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002926 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927 }
2928 }
2929 }
2930
2931 injectionState->release();
2932 } // release lock
2933
2934#if DEBUG_INJECTION
2935 ALOGD("injectInputEvent - Finished with result %d. "
2936 "injectorPid=%d, injectorUid=%d",
2937 injectionResult, injectorPid, injectorUid);
2938#endif
2939
2940 return injectionResult;
2941}
2942
2943bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2944 return injectorUid == 0
2945 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2946}
2947
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002948void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949 InjectionState* injectionState = entry->injectionState;
2950 if (injectionState) {
2951#if DEBUG_INJECTION
2952 ALOGD("Setting input event injection result to %d. "
2953 "injectorPid=%d, injectorUid=%d",
2954 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2955#endif
2956
2957 if (injectionState->injectionIsAsync
2958 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2959 // Log the outcome since the injector did not wait for the injection result.
2960 switch (injectionResult) {
2961 case INPUT_EVENT_INJECTION_SUCCEEDED:
2962 ALOGV("Asynchronous input event injection succeeded.");
2963 break;
2964 case INPUT_EVENT_INJECTION_FAILED:
2965 ALOGW("Asynchronous input event injection failed.");
2966 break;
2967 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2968 ALOGW("Asynchronous input event injection permission denied.");
2969 break;
2970 case INPUT_EVENT_INJECTION_TIMED_OUT:
2971 ALOGW("Asynchronous input event injection timed out.");
2972 break;
2973 }
2974 }
2975
2976 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002977 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002978 }
2979}
2980
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002981void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002982 InjectionState* injectionState = entry->injectionState;
2983 if (injectionState) {
2984 injectionState->pendingForegroundDispatches += 1;
2985 }
2986}
2987
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002988void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002989 InjectionState* injectionState = entry->injectionState;
2990 if (injectionState) {
2991 injectionState->pendingForegroundDispatches -= 1;
2992
2993 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002994 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002995 }
2996 }
2997}
2998
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002999std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3000 int32_t displayId) const {
3001 std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>::const_iterator it =
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003002 mWindowHandlesByDisplay.find(displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003003 if(it != mWindowHandlesByDisplay.end()) {
3004 return it->second;
3005 }
3006
3007 // Return an empty one if nothing found.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003008 return std::vector<sp<InputWindowHandle>>();
Arthur Hungb92218b2018-08-14 12:00:21 +08003009}
3010
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003012 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003013 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003014 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3015 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003016 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003017 return windowHandle;
3018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019 }
3020 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003021 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003022}
3023
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003024bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003025 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003026 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3027 for (const sp<InputWindowHandle>& handle : windowHandles) {
3028 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003029 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003030 ALOGE("Found window %s in display %" PRId32
3031 ", but it should belong to display %" PRId32,
3032 windowHandle->getName().c_str(), it.first,
3033 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003034 }
3035 return true;
3036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037 }
3038 }
3039 return false;
3040}
3041
Robert Carr5c8a0262018-10-03 16:30:44 -07003042sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3043 size_t count = mInputChannelsByToken.count(token);
3044 if (count == 0) {
3045 return nullptr;
3046 }
3047 return mInputChannelsByToken.at(token);
3048}
3049
Arthur Hungb92218b2018-08-14 12:00:21 +08003050/**
3051 * Called from InputManagerService, update window handle list by displayId that can receive input.
3052 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3053 * If set an empty list, remove all handles from the specific display.
3054 * For focused handle, check if need to change and send a cancel event to previous one.
3055 * For removed handle, check if need to send a cancel event if already in touch.
3056 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003057void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
chaviw291d88a2019-02-14 10:33:58 -08003058 int32_t displayId, const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003060 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003061#endif
3062 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003063 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064
Arthur Hungb92218b2018-08-14 12:00:21 +08003065 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003066 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3067 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068
Tiger Huang721e26f2018-07-24 22:26:19 +08003069 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003071
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003072 if (inputWindowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003073 // Remove all handles on a display if there are no windows left.
3074 mWindowHandlesByDisplay.erase(displayId);
3075 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003076 // Since we compare the pointer of input window handles across window updates, we need
3077 // to make sure the handle object for the same window stays unchanged across updates.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003078 const std::vector<sp<InputWindowHandle>>& oldHandles =
3079 mWindowHandlesByDisplay[displayId];
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003080 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003081 for (const sp<InputWindowHandle>& handle : oldHandles) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003082 oldHandlesByTokens[handle->getToken()] = handle;
3083 }
3084
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003085 std::vector<sp<InputWindowHandle>> newHandles;
3086 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003087 if (!handle->updateInfo() || (getInputChannelLocked(handle->getToken()) == nullptr
3088 && handle->getInfo()->portalToDisplayId == ADISPLAY_ID_NONE)) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003089 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003090 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003091 continue;
3092 }
3093
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003094 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003095 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003096 handle->getName().c_str(), displayId,
3097 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003098 continue;
3099 }
3100
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003101 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3102 const sp<InputWindowHandle> oldHandle =
3103 oldHandlesByTokens.at(handle->getToken());
3104 oldHandle->updateFrom(handle);
3105 newHandles.push_back(oldHandle);
3106 } else {
3107 newHandles.push_back(handle);
3108 }
3109 }
3110
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003111 for (const sp<InputWindowHandle>& windowHandle : newHandles) {
Arthur Hung7ab76b12019-01-09 19:17:20 +08003112 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3113 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus
3114 && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003115 newFocusedWindowHandle = windowHandle;
3116 }
3117 if (windowHandle == mLastHoverWindowHandle) {
3118 foundHoveredWindow = true;
3119 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003120 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003121
3122 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003123 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124 }
3125
3126 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003127 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128 }
3129
Tiger Huang721e26f2018-07-24 22:26:19 +08003130 sp<InputWindowHandle> oldFocusedWindowHandle =
3131 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3132
3133 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3134 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003136 ALOGD("Focus left window: %s in display %" PRId32,
3137 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003139 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3140 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003141 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3143 "focus left window");
3144 synthesizeCancelationEventsForInputChannelLocked(
3145 focusedInputChannel, options);
3146 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003147 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003149 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003151 ALOGD("Focus entered window: %s in display %" PRId32,
3152 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003154 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155 }
Robert Carrf759f162018-11-13 12:57:11 -08003156
3157 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003158 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003159 }
3160
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 }
3162
Arthur Hungb92218b2018-08-14 12:00:21 +08003163 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3164 if (stateIndex >= 0) {
3165 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003166 for (size_t i = 0; i < state.windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003167 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003168 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003170 ALOGD("Touched window was removed: %s in display %" PRId32,
3171 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003173 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003174 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003175 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003176 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3177 "touched window was removed");
3178 synthesizeCancelationEventsForInputChannelLocked(
3179 touchedInputChannel, options);
3180 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003181 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003182 } else {
3183 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 }
3186 }
3187
3188 // Release information for windows that are no longer present.
3189 // This ensures that unused input channels are released promptly.
3190 // Otherwise, they might stick around until the window handle is destroyed
3191 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003192 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003193 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003195 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003197 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 }
3199 }
3200 } // release lock
3201
3202 // Wake up poll loop since it may need to make new input dispatching choices.
3203 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003204
3205 if (setInputWindowsListener) {
3206 setInputWindowsListener->onSetInputWindowsFinished();
3207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003208}
3209
3210void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003211 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003213 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214#endif
3215 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003216 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217
Tiger Huang721e26f2018-07-24 22:26:19 +08003218 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3219 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003220 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003221 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3222 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003224 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003226 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003228 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003230 oldFocusedApplicationHandle->releaseInfo();
3231 oldFocusedApplicationHandle.clear();
3232 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233 }
3234
3235#if DEBUG_FOCUS
3236 //logDispatchStateLocked();
3237#endif
3238 } // release lock
3239
3240 // Wake up poll loop since it may need to make new input dispatching choices.
3241 mLooper->wake();
3242}
3243
Tiger Huang721e26f2018-07-24 22:26:19 +08003244/**
3245 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3246 * the display not specified.
3247 *
3248 * We track any unreleased events for each window. If a window loses the ability to receive the
3249 * released event, we will send a cancel event to it. So when the focused display is changed, we
3250 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3251 * display. The display-specified events won't be affected.
3252 */
3253void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3254#if DEBUG_FOCUS
3255 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3256#endif
3257 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003258 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003259
3260 if (mFocusedDisplayId != displayId) {
3261 sp<InputWindowHandle> oldFocusedWindowHandle =
3262 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3263 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003264 sp<InputChannel> inputChannel =
3265 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003266 if (inputChannel != nullptr) {
3267 CancelationOptions options(
3268 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3269 "The display which contains this window no longer has focus.");
3270 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3271 }
3272 }
3273 mFocusedDisplayId = displayId;
3274
3275 // Sanity check
3276 sp<InputWindowHandle> newFocusedWindowHandle =
3277 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003278 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003279
Tiger Huang721e26f2018-07-24 22:26:19 +08003280 if (newFocusedWindowHandle == nullptr) {
3281 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3282 if (!mFocusedWindowHandlesByDisplay.empty()) {
3283 ALOGE("But another display has a focused window:");
3284 for (auto& it : mFocusedWindowHandlesByDisplay) {
3285 const int32_t displayId = it.first;
3286 const sp<InputWindowHandle>& windowHandle = it.second;
3287 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3288 displayId, windowHandle->getName().c_str());
3289 }
3290 }
3291 }
3292 }
3293
3294#if DEBUG_FOCUS
3295 logDispatchStateLocked();
3296#endif
3297 } // release lock
3298
3299 // Wake up poll loop since it may need to make new input dispatching choices.
3300 mLooper->wake();
3301}
3302
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3304#if DEBUG_FOCUS
3305 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3306#endif
3307
3308 bool changed;
3309 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003310 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311
3312 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3313 if (mDispatchFrozen && !frozen) {
3314 resetANRTimeoutsLocked();
3315 }
3316
3317 if (mDispatchEnabled && !enabled) {
3318 resetAndDropEverythingLocked("dispatcher is being disabled");
3319 }
3320
3321 mDispatchEnabled = enabled;
3322 mDispatchFrozen = frozen;
3323 changed = true;
3324 } else {
3325 changed = false;
3326 }
3327
3328#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003329 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330#endif
3331 } // release lock
3332
3333 if (changed) {
3334 // Wake up poll loop since it may need to make new input dispatching choices.
3335 mLooper->wake();
3336 }
3337}
3338
3339void InputDispatcher::setInputFilterEnabled(bool enabled) {
3340#if DEBUG_FOCUS
3341 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3342#endif
3343
3344 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003345 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346
3347 if (mInputFilterEnabled == enabled) {
3348 return;
3349 }
3350
3351 mInputFilterEnabled = enabled;
3352 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3353 } // release lock
3354
3355 // Wake up poll loop since there might be work to do to drop everything.
3356 mLooper->wake();
3357}
3358
chaviwfbe5d9c2018-12-26 12:23:37 -08003359bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3360 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003362 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003364 return true;
3365 }
3366
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003368 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369
chaviwfbe5d9c2018-12-26 12:23:37 -08003370 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3371 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003372 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003373 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 return false;
3375 }
chaviw4f2dd402018-12-26 15:30:27 -08003376#if DEBUG_FOCUS
3377 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3378 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3379#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3381#if DEBUG_FOCUS
3382 ALOGD("Cannot transfer focus because windows are on different displays.");
3383#endif
3384 return false;
3385 }
3386
3387 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003388 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3389 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3390 for (size_t i = 0; i < state.windows.size(); i++) {
3391 const TouchedWindow& touchedWindow = state.windows[i];
3392 if (touchedWindow.windowHandle == fromWindowHandle) {
3393 int32_t oldTargetFlags = touchedWindow.targetFlags;
3394 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003396 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397
Jeff Brownf086ddb2014-02-11 14:28:48 -08003398 int32_t newTargetFlags = oldTargetFlags
3399 & (InputTarget::FLAG_FOREGROUND
3400 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3401 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402
Jeff Brownf086ddb2014-02-11 14:28:48 -08003403 found = true;
3404 goto Found;
3405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 }
3407 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003408Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409
3410 if (! found) {
3411#if DEBUG_FOCUS
3412 ALOGD("Focus transfer failed because from window did not have focus.");
3413#endif
3414 return false;
3415 }
3416
chaviwfbe5d9c2018-12-26 12:23:37 -08003417
3418 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3419 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3421 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3422 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3423 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3424 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3425
3426 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3427 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3428 "transferring touch focus from this window to another window");
3429 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3430 }
3431
3432#if DEBUG_FOCUS
3433 logDispatchStateLocked();
3434#endif
3435 } // release lock
3436
3437 // Wake up poll loop since it may need to make new input dispatching choices.
3438 mLooper->wake();
3439 return true;
3440}
3441
3442void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3443#if DEBUG_FOCUS
3444 ALOGD("Resetting and dropping all events (%s).", reason);
3445#endif
3446
3447 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3448 synthesizeCancelationEventsForAllConnectionsLocked(options);
3449
3450 resetKeyRepeatLocked();
3451 releasePendingEventLocked();
3452 drainInboundQueueLocked();
3453 resetANRTimeoutsLocked();
3454
Jeff Brownf086ddb2014-02-11 14:28:48 -08003455 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003457 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458}
3459
3460void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003461 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462 dumpDispatchStateLocked(dump);
3463
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003464 std::istringstream stream(dump);
3465 std::string line;
3466
3467 while (std::getline(stream, line, '\n')) {
3468 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469 }
3470}
3471
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003472void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3473 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3474 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003475 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476
Tiger Huang721e26f2018-07-24 22:26:19 +08003477 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3478 dump += StringPrintf(INDENT "FocusedApplications:\n");
3479 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3480 const int32_t displayId = it.first;
3481 const sp<InputApplicationHandle>& applicationHandle = it.second;
3482 dump += StringPrintf(
3483 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3484 displayId,
3485 applicationHandle->getName().c_str(),
3486 applicationHandle->getDispatchingTimeout(
3487 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3488 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003490 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003492
3493 if (!mFocusedWindowHandlesByDisplay.empty()) {
3494 dump += StringPrintf(INDENT "FocusedWindows:\n");
3495 for (auto& it : mFocusedWindowHandlesByDisplay) {
3496 const int32_t displayId = it.first;
3497 const sp<InputWindowHandle>& windowHandle = it.second;
3498 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3499 displayId, windowHandle->getName().c_str());
3500 }
3501 } else {
3502 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504
Jeff Brownf086ddb2014-02-11 14:28:48 -08003505 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003506 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003507 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3508 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003509 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003510 state.displayId, toString(state.down), toString(state.split),
3511 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003512 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003513 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003514 for (size_t i = 0; i < state.windows.size(); i++) {
3515 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003516 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3517 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003518 touchedWindow.pointerIds.value,
3519 touchedWindow.targetFlags);
3520 }
3521 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003522 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003523 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003524 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003525 dump += INDENT3 "Portal windows:\n";
3526 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003527 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003528 dump += StringPrintf(INDENT4 "%zu: name='%s'\n",
3529 i, portalWindowHandle->getName().c_str());
3530 }
3531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 }
3533 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003534 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 }
3536
Arthur Hungb92218b2018-08-14 12:00:21 +08003537 if (!mWindowHandlesByDisplay.empty()) {
3538 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003539 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003540 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003541 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003542 dump += INDENT2 "Windows:\n";
3543 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003544 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003545 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546
Arthur Hungb92218b2018-08-14 12:00:21 +08003547 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003548 "portalToDisplayId=%d, paused=%s, hasFocus=%s, hasWallpaper=%s, "
Arthur Hungb92218b2018-08-14 12:00:21 +08003549 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003550 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003551 "touchableRegion=",
3552 i, windowInfo->name.c_str(), windowInfo->displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003553 windowInfo->portalToDisplayId,
Arthur Hungb92218b2018-08-14 12:00:21 +08003554 toString(windowInfo->paused),
3555 toString(windowInfo->hasFocus),
3556 toString(windowInfo->hasWallpaper),
3557 toString(windowInfo->visible),
3558 toString(windowInfo->canReceiveKeys),
3559 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3560 windowInfo->layer,
3561 windowInfo->frameLeft, windowInfo->frameTop,
3562 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003563 windowInfo->globalScaleFactor,
3564 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003565 dumpRegion(dump, windowInfo->touchableRegion);
3566 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3567 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3568 windowInfo->ownerPid, windowInfo->ownerUid,
3569 windowInfo->dispatchingTimeout / 1000000.0);
3570 }
3571 } else {
3572 dump += INDENT2 "Windows: <none>\n";
3573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574 }
3575 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003576 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577 }
3578
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003579 if (!mMonitoringChannelsByDisplay.empty()) {
3580 for (auto& it : mMonitoringChannelsByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003581 const std::vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003582 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003583 const size_t numChannels = monitoringChannels.size();
3584 for (size_t i = 0; i < numChannels; i++) {
3585 const sp<InputChannel>& channel = monitoringChannels[i];
3586 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3587 }
3588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003590 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 }
3592
3593 nsecs_t currentTime = now();
3594
3595 // Dump recently dispatched or dropped events from oldest to newest.
3596 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003597 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003599 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003601 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 (currentTime - entry->eventTime) * 0.000001f);
3603 }
3604 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003605 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 }
3607
3608 // Dump event currently being dispatched.
3609 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003610 dump += INDENT "PendingEvent:\n";
3611 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003613 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3615 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003616 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
3618
3619 // Dump inbound events from oldest to newest.
3620 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003621 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003623 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003625 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 (currentTime - entry->eventTime) * 0.000001f);
3627 }
3628 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003629 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 }
3631
Michael Wright78f24442014-08-06 15:55:28 -07003632 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003633 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003634 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3635 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3636 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003637 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003638 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3639 }
3640 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003641 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003642 }
3643
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003645 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3647 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003648 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003650 i, connection->getInputChannelName().c_str(),
3651 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 connection->getStatusLabel(), toString(connection->monitor),
3653 toString(connection->inputPublisherBlocked));
3654
3655 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003656 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 connection->outboundQueue.count());
3658 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3659 entry = entry->next) {
3660 dump.append(INDENT4);
3661 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003662 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 entry->targetFlags, entry->resolvedAction,
3664 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3665 }
3666 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003667 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 }
3669
3670 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003671 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 connection->waitQueue.count());
3673 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3674 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003675 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003677 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 "age=%0.1fms, wait=%0.1fms\n",
3679 entry->targetFlags, entry->resolvedAction,
3680 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3681 (currentTime - entry->deliveryTime) * 0.000001f);
3682 }
3683 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003684 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 }
3686 }
3687 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003688 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 }
3690
3691 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003692 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 (mAppSwitchDueTime - now()) / 1000000.0);
3694 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003695 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 }
3697
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003698 dump += INDENT "Configuration:\n";
3699 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003701 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702 mConfig.keyRepeatTimeout * 0.000001f);
3703}
3704
Robert Carr803535b2018-08-02 16:38:15 -07003705status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003707 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3708 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709#endif
3710
3711 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003712 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713
Robert Carr4e670e52018-08-15 13:26:12 -07003714 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3715 // treat inputChannel as monitor channel for displayId.
3716 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3717 if (monitor) {
3718 inputChannel->setToken(new BBinder());
3719 }
3720
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721 if (getConnectionIndexLocked(inputChannel) >= 0) {
3722 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003723 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 return BAD_VALUE;
3725 }
3726
Robert Carr803535b2018-08-02 16:38:15 -07003727 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728
3729 int fd = inputChannel->getFd();
3730 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003731 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003733 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 if (monitor) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003735 std::vector<sp<InputChannel>>& monitoringChannels =
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003736 mMonitoringChannelsByDisplay[displayId];
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003737 monitoringChannels.push_back(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738 }
3739
3740 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3741 } // release lock
3742
3743 // Wake the looper because some connections have changed.
3744 mLooper->wake();
3745 return OK;
3746}
3747
3748status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3749#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003750 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751#endif
3752
3753 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003754 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755
3756 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3757 if (status) {
3758 return status;
3759 }
3760 } // release lock
3761
3762 // Wake the poll loop because removing the connection may have changed the current
3763 // synchronization state.
3764 mLooper->wake();
3765 return OK;
3766}
3767
3768status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3769 bool notify) {
3770 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3771 if (connectionIndex < 0) {
3772 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003773 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 return BAD_VALUE;
3775 }
3776
3777 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3778 mConnectionsByFd.removeItemsAt(connectionIndex);
3779
Robert Carr5c8a0262018-10-03 16:30:44 -07003780 mInputChannelsByToken.erase(inputChannel->getToken());
3781
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 if (connection->monitor) {
3783 removeMonitorChannelLocked(inputChannel);
3784 }
3785
3786 mLooper->removeFd(inputChannel->getFd());
3787
3788 nsecs_t currentTime = now();
3789 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3790
3791 connection->status = Connection::STATUS_ZOMBIE;
3792 return OK;
3793}
3794
3795void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003796 for (auto it = mMonitoringChannelsByDisplay.begin();
3797 it != mMonitoringChannelsByDisplay.end(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003798 std::vector<sp<InputChannel>>& monitoringChannels = it->second;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003799 const size_t numChannels = monitoringChannels.size();
3800 for (size_t i = 0; i < numChannels; i++) {
3801 if (monitoringChannels[i] == inputChannel) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003802 monitoringChannels.erase(monitoringChannels.begin() + i);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003803 break;
3804 }
3805 }
3806 if (monitoringChannels.empty()) {
3807 it = mMonitoringChannelsByDisplay.erase(it);
3808 } else {
3809 ++it;
3810 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 }
3812}
3813
3814ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003815 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003816 return -1;
3817 }
3818
Robert Carr4e670e52018-08-15 13:26:12 -07003819 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3820 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3821 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3822 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 }
3824 }
Robert Carr4e670e52018-08-15 13:26:12 -07003825
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826 return -1;
3827}
3828
3829void InputDispatcher::onDispatchCycleFinishedLocked(
3830 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3831 CommandEntry* commandEntry = postCommandLocked(
3832 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3833 commandEntry->connection = connection;
3834 commandEntry->eventTime = currentTime;
3835 commandEntry->seq = seq;
3836 commandEntry->handled = handled;
3837}
3838
3839void InputDispatcher::onDispatchCycleBrokenLocked(
3840 nsecs_t currentTime, const sp<Connection>& connection) {
3841 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003842 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843
3844 CommandEntry* commandEntry = postCommandLocked(
3845 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3846 commandEntry->connection = connection;
3847}
3848
chaviw0c06c6e2019-01-09 13:27:07 -08003849void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
3850 const sp<InputWindowHandle>& newFocus) {
3851 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
3852 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08003853 CommandEntry* commandEntry = postCommandLocked(
3854 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08003855 commandEntry->oldToken = oldToken;
3856 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003857}
3858
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859void InputDispatcher::onANRLocked(
3860 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3861 const sp<InputWindowHandle>& windowHandle,
3862 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3863 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3864 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3865 ALOGI("Application is not responding: %s. "
3866 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003867 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868 dispatchLatency, waitDuration, reason);
3869
3870 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003871 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 struct tm tm;
3873 localtime_r(&t, &tm);
3874 char timestr[64];
3875 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3876 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003877 mLastANRState += INDENT "ANR:\n";
3878 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3879 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003880 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003881 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3882 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3883 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884 dumpDispatchStateLocked(mLastANRState);
3885
3886 CommandEntry* commandEntry = postCommandLocked(
3887 & InputDispatcher::doNotifyANRLockedInterruptible);
3888 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003889 commandEntry->inputChannel = windowHandle != nullptr ?
3890 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891 commandEntry->reason = reason;
3892}
3893
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003894void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible (
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895 CommandEntry* commandEntry) {
3896 mLock.unlock();
3897
3898 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3899
3900 mLock.lock();
3901}
3902
3903void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3904 CommandEntry* commandEntry) {
3905 sp<Connection> connection = commandEntry->connection;
3906
3907 if (connection->status != Connection::STATUS_ZOMBIE) {
3908 mLock.unlock();
3909
Robert Carr803535b2018-08-02 16:38:15 -07003910 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911
3912 mLock.lock();
3913 }
3914}
3915
Robert Carrf759f162018-11-13 12:57:11 -08003916void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3917 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08003918 sp<IBinder> oldToken = commandEntry->oldToken;
3919 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003920 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08003921 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08003922 mLock.lock();
3923}
3924
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925void InputDispatcher::doNotifyANRLockedInterruptible(
3926 CommandEntry* commandEntry) {
3927 mLock.unlock();
3928
3929 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003930 commandEntry->inputApplicationHandle,
3931 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932 commandEntry->reason);
3933
3934 mLock.lock();
3935
3936 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003937 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938}
3939
3940void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3941 CommandEntry* commandEntry) {
3942 KeyEntry* entry = commandEntry->keyEntry;
3943
3944 KeyEvent event;
3945 initializeKeyEvent(&event, entry);
3946
3947 mLock.unlock();
3948
Michael Wright2b3c3302018-03-02 17:19:13 +00003949 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003950 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3951 commandEntry->inputChannel->getToken() : nullptr;
3952 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003954 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3955 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3956 std::to_string(t.duration().count()).c_str());
3957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958
3959 mLock.lock();
3960
3961 if (delay < 0) {
3962 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3963 } else if (!delay) {
3964 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3965 } else {
3966 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3967 entry->interceptKeyWakeupTime = now() + delay;
3968 }
3969 entry->release();
3970}
3971
3972void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3973 CommandEntry* commandEntry) {
3974 sp<Connection> connection = commandEntry->connection;
3975 nsecs_t finishTime = commandEntry->eventTime;
3976 uint32_t seq = commandEntry->seq;
3977 bool handled = commandEntry->handled;
3978
3979 // Handle post-event policy actions.
3980 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3981 if (dispatchEntry) {
3982 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3983 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003984 std::string msg =
3985 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003986 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003988 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 }
3990
3991 bool restartEvent;
3992 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3993 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3994 restartEvent = afterKeyEventLockedInterruptible(connection,
3995 dispatchEntry, keyEntry, handled);
3996 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3997 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3998 restartEvent = afterMotionEventLockedInterruptible(connection,
3999 dispatchEntry, motionEntry, handled);
4000 } else {
4001 restartEvent = false;
4002 }
4003
4004 // Dequeue the event and start the next cycle.
4005 // Note that because the lock might have been released, it is possible that the
4006 // contents of the wait queue to have been drained, so we need to double-check
4007 // a few things.
4008 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4009 connection->waitQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004010 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4012 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004013 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014 } else {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08004015 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016 }
4017 }
4018
4019 // Start the next dispatch cycle for this connection.
4020 startDispatchCycleLocked(now(), connection);
4021 }
4022}
4023
4024bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4025 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004026 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004027 if (!handled) {
4028 // Report the key as unhandled, since the fallback was not handled.
4029 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4030 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004031 return false;
4032 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004034 // Get the fallback key state.
4035 // Clear it out after dispatching the UP.
4036 int32_t originalKeyCode = keyEntry->keyCode;
4037 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4038 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4039 connection->inputState.removeFallbackKey(originalKeyCode);
4040 }
4041
4042 if (handled || !dispatchEntry->hasForegroundTarget()) {
4043 // If the application handles the original key for which we previously
4044 // generated a fallback or if the window is not a foreground window,
4045 // then cancel the associated fallback key, if any.
4046 if (fallbackKeyCode != -1) {
4047 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004049 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4051 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4052 keyEntry->policyFlags);
4053#endif
4054 KeyEvent event;
4055 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004056 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057
4058 mLock.unlock();
4059
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004060 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4061 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062
4063 mLock.lock();
4064
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004065 // Cancel the fallback key.
4066 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004068 "application handled the original non-fallback key "
4069 "or is no longer a foreground target, "
4070 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 options.keyCode = fallbackKeyCode;
4072 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004074 connection->inputState.removeFallbackKey(originalKeyCode);
4075 }
4076 } else {
4077 // If the application did not handle a non-fallback key, first check
4078 // that we are in a good state to perform unhandled key event processing
4079 // Then ask the policy what to do with it.
4080 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4081 && keyEntry->repeatCount == 0;
4082 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004084 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4085 "since this is not an initial down. "
4086 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4087 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4088 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004090 return false;
4091 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004093 // Dispatch the unhandled key to the policy.
4094#if DEBUG_OUTBOUND_EVENT_DETAILS
4095 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4096 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4097 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4098 keyEntry->policyFlags);
4099#endif
4100 KeyEvent event;
4101 initializeKeyEvent(&event, keyEntry);
4102
4103 mLock.unlock();
4104
4105 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4106 &event, keyEntry->policyFlags, &event);
4107
4108 mLock.lock();
4109
4110 if (connection->status != Connection::STATUS_NORMAL) {
4111 connection->inputState.removeFallbackKey(originalKeyCode);
4112 return false;
4113 }
4114
4115 // Latch the fallback keycode for this key on an initial down.
4116 // The fallback keycode cannot change at any other point in the lifecycle.
4117 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004119 fallbackKeyCode = event.getKeyCode();
4120 } else {
4121 fallbackKeyCode = AKEYCODE_UNKNOWN;
4122 }
4123 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4124 }
4125
4126 ALOG_ASSERT(fallbackKeyCode != -1);
4127
4128 // Cancel the fallback key if the policy decides not to send it anymore.
4129 // We will continue to dispatch the key to the policy but we will no
4130 // longer dispatch a fallback key to the application.
4131 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4132 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4133#if DEBUG_OUTBOUND_EVENT_DETAILS
4134 if (fallback) {
4135 ALOGD("Unhandled key event: Policy requested to send key %d"
4136 "as a fallback for %d, but on the DOWN it had requested "
4137 "to send %d instead. Fallback canceled.",
4138 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4139 } else {
4140 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4141 "but on the DOWN it had requested to send %d. "
4142 "Fallback canceled.",
4143 originalKeyCode, fallbackKeyCode);
4144 }
4145#endif
4146
4147 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4148 "canceling fallback, policy no longer desires it");
4149 options.keyCode = fallbackKeyCode;
4150 synthesizeCancelationEventsForConnectionLocked(connection, options);
4151
4152 fallback = false;
4153 fallbackKeyCode = AKEYCODE_UNKNOWN;
4154 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4155 connection->inputState.setFallbackKey(originalKeyCode,
4156 fallbackKeyCode);
4157 }
4158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159
4160#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004161 {
4162 std::string msg;
4163 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4164 connection->inputState.getFallbackKeys();
4165 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4166 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4167 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004169 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4170 fallbackKeys.size(), msg.c_str());
4171 }
4172#endif
4173
4174 if (fallback) {
4175 // Restart the dispatch cycle using the fallback key.
4176 keyEntry->eventTime = event.getEventTime();
4177 keyEntry->deviceId = event.getDeviceId();
4178 keyEntry->source = event.getSource();
4179 keyEntry->displayId = event.getDisplayId();
4180 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4181 keyEntry->keyCode = fallbackKeyCode;
4182 keyEntry->scanCode = event.getScanCode();
4183 keyEntry->metaState = event.getMetaState();
4184 keyEntry->repeatCount = event.getRepeatCount();
4185 keyEntry->downTime = event.getDownTime();
4186 keyEntry->syntheticRepeat = false;
4187
4188#if DEBUG_OUTBOUND_EVENT_DETAILS
4189 ALOGD("Unhandled key event: Dispatching fallback key. "
4190 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4191 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4192#endif
4193 return true; // restart the event
4194 } else {
4195#if DEBUG_OUTBOUND_EVENT_DETAILS
4196 ALOGD("Unhandled key event: No fallback key.");
4197#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004198
4199 // Report the key as unhandled, since there is no fallback key.
4200 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201 }
4202 }
4203 return false;
4204}
4205
4206bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4207 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4208 return false;
4209}
4210
4211void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4212 mLock.unlock();
4213
4214 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4215
4216 mLock.lock();
4217}
4218
4219void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004220 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4222 entry->downTime, entry->eventTime);
4223}
4224
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004225void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4227 // TODO Write some statistics about how long we spend waiting.
4228}
4229
4230void InputDispatcher::traceInboundQueueLengthLocked() {
4231 if (ATRACE_ENABLED()) {
4232 ATRACE_INT("iq", mInboundQueue.count());
4233 }
4234}
4235
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004236void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 if (ATRACE_ENABLED()) {
4238 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004239 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 ATRACE_INT(counterName, connection->outboundQueue.count());
4241 }
4242}
4243
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004244void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 if (ATRACE_ENABLED()) {
4246 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004247 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 ATRACE_INT(counterName, connection->waitQueue.count());
4249 }
4250}
4251
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004252void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004253 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004255 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 dumpDispatchStateLocked(dump);
4257
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004258 if (!mLastANRState.empty()) {
4259 dump += "\nInput Dispatcher State at time of last ANR:\n";
4260 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 }
4262}
4263
4264void InputDispatcher::monitor() {
4265 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004266 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004268 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269}
4270
4271
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272// --- InputDispatcher::InjectionState ---
4273
4274InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4275 refCount(1),
4276 injectorPid(injectorPid), injectorUid(injectorUid),
4277 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4278 pendingForegroundDispatches(0) {
4279}
4280
4281InputDispatcher::InjectionState::~InjectionState() {
4282}
4283
4284void InputDispatcher::InjectionState::release() {
4285 refCount -= 1;
4286 if (refCount == 0) {
4287 delete this;
4288 } else {
4289 ALOG_ASSERT(refCount > 0);
4290 }
4291}
4292
4293
4294// --- InputDispatcher::EventEntry ---
4295
Prabir Pradhan42611e02018-11-27 14:04:02 -08004296InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4297 nsecs_t eventTime, uint32_t policyFlags) :
4298 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4299 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300}
4301
4302InputDispatcher::EventEntry::~EventEntry() {
4303 releaseInjectionState();
4304}
4305
4306void InputDispatcher::EventEntry::release() {
4307 refCount -= 1;
4308 if (refCount == 0) {
4309 delete this;
4310 } else {
4311 ALOG_ASSERT(refCount > 0);
4312 }
4313}
4314
4315void InputDispatcher::EventEntry::releaseInjectionState() {
4316 if (injectionState) {
4317 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004318 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 }
4320}
4321
4322
4323// --- InputDispatcher::ConfigurationChangedEntry ---
4324
Prabir Pradhan42611e02018-11-27 14:04:02 -08004325InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4326 uint32_t sequenceNum, nsecs_t eventTime) :
4327 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328}
4329
4330InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4331}
4332
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004333void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4334 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335}
4336
4337
4338// --- InputDispatcher::DeviceResetEntry ---
4339
Prabir Pradhan42611e02018-11-27 14:04:02 -08004340InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4341 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4342 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 deviceId(deviceId) {
4344}
4345
4346InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4347}
4348
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004349void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4350 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 deviceId, policyFlags);
4352}
4353
4354
4355// --- InputDispatcher::KeyEntry ---
4356
Prabir Pradhan42611e02018-11-27 14:04:02 -08004357InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004358 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4360 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004361 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004362 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4364 repeatCount(repeatCount), downTime(downTime),
4365 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4366 interceptKeyWakeupTime(0) {
4367}
4368
4369InputDispatcher::KeyEntry::~KeyEntry() {
4370}
4371
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004372void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004373 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4375 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004376 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004377 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378}
4379
4380void InputDispatcher::KeyEntry::recycle() {
4381 releaseInjectionState();
4382
4383 dispatchInProgress = false;
4384 syntheticRepeat = false;
4385 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4386 interceptKeyWakeupTime = 0;
4387}
4388
4389
4390// --- InputDispatcher::MotionEntry ---
4391
Prabir Pradhan42611e02018-11-27 14:04:02 -08004392InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004393 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4394 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004395 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4396 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004397 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004398 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4399 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004400 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004402 deviceId(deviceId), source(source), displayId(displayId), action(action),
4403 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004404 classification(classification), edgeFlags(edgeFlags),
4405 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004406 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 for (uint32_t i = 0; i < pointerCount; i++) {
4408 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4409 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004410 if (xOffset || yOffset) {
4411 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 }
4414}
4415
4416InputDispatcher::MotionEntry::~MotionEntry() {
4417}
4418
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004419void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004420 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004421 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004422 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004423 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004424 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4425 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004426
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 for (uint32_t i = 0; i < pointerCount; i++) {
4428 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004429 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004431 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432 pointerCoords[i].getX(), pointerCoords[i].getY());
4433 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004434 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435}
4436
4437
4438// --- InputDispatcher::DispatchEntry ---
4439
4440volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4441
4442InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004443 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4444 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 seq(nextSeq()),
4446 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004447 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4448 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4450 eventEntry->refCount += 1;
4451}
4452
4453InputDispatcher::DispatchEntry::~DispatchEntry() {
4454 eventEntry->release();
4455}
4456
4457uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4458 // Sequence number 0 is reserved and will never be returned.
4459 uint32_t seq;
4460 do {
4461 seq = android_atomic_inc(&sNextSeqAtomic);
4462 } while (!seq);
4463 return seq;
4464}
4465
4466
4467// --- InputDispatcher::InputState ---
4468
4469InputDispatcher::InputState::InputState() {
4470}
4471
4472InputDispatcher::InputState::~InputState() {
4473}
4474
4475bool InputDispatcher::InputState::isNeutral() const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004476 return mKeyMementos.empty() && mMotionMementos.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477}
4478
4479bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4480 int32_t displayId) const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004481 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 if (memento.deviceId == deviceId
4483 && memento.source == source
4484 && memento.displayId == displayId
4485 && memento.hovering) {
4486 return true;
4487 }
4488 }
4489 return false;
4490}
4491
4492bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4493 int32_t action, int32_t flags) {
4494 switch (action) {
4495 case AKEY_EVENT_ACTION_UP: {
4496 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4497 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4498 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4499 mFallbackKeys.removeItemsAt(i);
4500 } else {
4501 i += 1;
4502 }
4503 }
4504 }
4505 ssize_t index = findKeyMemento(entry);
4506 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004507 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508 return true;
4509 }
4510 /* FIXME: We can't just drop the key up event because that prevents creating
4511 * popup windows that are automatically shown when a key is held and then
4512 * dismissed when the key is released. The problem is that the popup will
4513 * not have received the original key down, so the key up will be considered
4514 * to be inconsistent with its observed state. We could perhaps handle this
4515 * by synthesizing a key down but that will cause other problems.
4516 *
4517 * So for now, allow inconsistent key up events to be dispatched.
4518 *
4519#if DEBUG_OUTBOUND_EVENT_DETAILS
4520 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4521 "keyCode=%d, scanCode=%d",
4522 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4523#endif
4524 return false;
4525 */
4526 return true;
4527 }
4528
4529 case AKEY_EVENT_ACTION_DOWN: {
4530 ssize_t index = findKeyMemento(entry);
4531 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004532 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533 }
4534 addKeyMemento(entry, flags);
4535 return true;
4536 }
4537
4538 default:
4539 return true;
4540 }
4541}
4542
4543bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4544 int32_t action, int32_t flags) {
4545 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4546 switch (actionMasked) {
4547 case AMOTION_EVENT_ACTION_UP:
4548 case AMOTION_EVENT_ACTION_CANCEL: {
4549 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4550 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004551 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552 return true;
4553 }
4554#if DEBUG_OUTBOUND_EVENT_DETAILS
4555 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004556 "displayId=%" PRId32 ", actionMasked=%d",
4557 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558#endif
4559 return false;
4560 }
4561
4562 case AMOTION_EVENT_ACTION_DOWN: {
4563 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4564 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004565 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566 }
4567 addMotionMemento(entry, flags, false /*hovering*/);
4568 return true;
4569 }
4570
4571 case AMOTION_EVENT_ACTION_POINTER_UP:
4572 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4573 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004574 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4575 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4576 // generate cancellation events for these since they're based in relative rather than
4577 // absolute units.
4578 return true;
4579 }
4580
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004582
4583 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4584 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4585 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4586 // other value and we need to track the motion so we can send cancellation events for
4587 // anything generating fallback events (e.g. DPad keys for joystick movements).
4588 if (index >= 0) {
4589 if (entry->pointerCoords[0].isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004590 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wright38dcdff2014-03-19 12:06:10 -07004591 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004592 MotionMemento& memento = mMotionMementos[index];
Michael Wright38dcdff2014-03-19 12:06:10 -07004593 memento.setPointers(entry);
4594 }
4595 } else if (!entry->pointerCoords[0].isEmpty()) {
4596 addMotionMemento(entry, flags, false /*hovering*/);
4597 }
4598
4599 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4600 return true;
4601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004603 MotionMemento& memento = mMotionMementos[index];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604 memento.setPointers(entry);
4605 return true;
4606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607#if DEBUG_OUTBOUND_EVENT_DETAILS
4608 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004609 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4610 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611#endif
4612 return false;
4613 }
4614
4615 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4616 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4617 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004618 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619 return true;
4620 }
4621#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004622 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4623 "displayId=%" PRId32,
4624 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625#endif
4626 return false;
4627 }
4628
4629 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4630 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4631 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4632 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004633 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 }
4635 addMotionMemento(entry, flags, true /*hovering*/);
4636 return true;
4637 }
4638
4639 default:
4640 return true;
4641 }
4642}
4643
4644ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4645 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004646 const KeyMemento& memento = mKeyMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647 if (memento.deviceId == entry->deviceId
4648 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004649 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 && memento.keyCode == entry->keyCode
4651 && memento.scanCode == entry->scanCode) {
4652 return i;
4653 }
4654 }
4655 return -1;
4656}
4657
4658ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4659 bool hovering) const {
4660 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004661 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662 if (memento.deviceId == entry->deviceId
4663 && memento.source == entry->source
4664 && memento.displayId == entry->displayId
4665 && memento.hovering == hovering) {
4666 return i;
4667 }
4668 }
4669 return -1;
4670}
4671
4672void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004673 KeyMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674 memento.deviceId = entry->deviceId;
4675 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004676 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004677 memento.keyCode = entry->keyCode;
4678 memento.scanCode = entry->scanCode;
4679 memento.metaState = entry->metaState;
4680 memento.flags = flags;
4681 memento.downTime = entry->downTime;
4682 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004683 mKeyMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684}
4685
4686void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4687 int32_t flags, bool hovering) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004688 MotionMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 memento.deviceId = entry->deviceId;
4690 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004691 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692 memento.flags = flags;
4693 memento.xPrecision = entry->xPrecision;
4694 memento.yPrecision = entry->yPrecision;
4695 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 memento.setPointers(entry);
4697 memento.hovering = hovering;
4698 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004699 mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700}
4701
4702void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4703 pointerCount = entry->pointerCount;
4704 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4705 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4706 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4707 }
4708}
4709
4710void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004711 std::vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4712 for (KeyMemento& memento : mKeyMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 if (shouldCancelKey(memento, options)) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004714 outEvents.push_back(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004715 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4717 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4718 }
4719 }
4720
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004721 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004723 const int32_t action = memento.hovering ?
4724 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004725 outEvents.push_back(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004726 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004727 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4728 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004730 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004731 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732 }
4733 }
4734}
4735
4736void InputDispatcher::InputState::clear() {
4737 mKeyMementos.clear();
4738 mMotionMementos.clear();
4739 mFallbackKeys.clear();
4740}
4741
4742void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4743 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004744 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4746 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004747 const MotionMemento& otherMemento = other.mMotionMementos[j];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 if (memento.deviceId == otherMemento.deviceId
4749 && memento.source == otherMemento.source
4750 && memento.displayId == otherMemento.displayId) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004751 other.mMotionMementos.erase(other.mMotionMementos.begin() + j);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 } else {
4753 j += 1;
4754 }
4755 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004756 other.mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757 }
4758 }
4759}
4760
4761int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4762 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4763 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4764}
4765
4766void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4767 int32_t fallbackKeyCode) {
4768 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4769 if (index >= 0) {
4770 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4771 } else {
4772 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4773 }
4774}
4775
4776void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4777 mFallbackKeys.removeItem(originalKeyCode);
4778}
4779
4780bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4781 const CancelationOptions& options) {
4782 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4783 return false;
4784 }
4785
4786 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4787 return false;
4788 }
4789
4790 switch (options.mode) {
4791 case CancelationOptions::CANCEL_ALL_EVENTS:
4792 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4793 return true;
4794 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4795 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004796 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4797 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798 default:
4799 return false;
4800 }
4801}
4802
4803bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4804 const CancelationOptions& options) {
4805 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4806 return false;
4807 }
4808
4809 switch (options.mode) {
4810 case CancelationOptions::CANCEL_ALL_EVENTS:
4811 return true;
4812 case CancelationOptions::CANCEL_POINTER_EVENTS:
4813 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4814 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4815 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004816 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4817 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 default:
4819 return false;
4820 }
4821}
4822
4823
4824// --- InputDispatcher::Connection ---
4825
Robert Carr803535b2018-08-02 16:38:15 -07004826InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4827 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828 monitor(monitor),
4829 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4830}
4831
4832InputDispatcher::Connection::~Connection() {
4833}
4834
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004835const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004836 if (inputChannel != nullptr) {
4837 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838 }
4839 if (monitor) {
4840 return "monitor";
4841 }
4842 return "?";
4843}
4844
4845const char* InputDispatcher::Connection::getStatusLabel() const {
4846 switch (status) {
4847 case STATUS_NORMAL:
4848 return "NORMAL";
4849
4850 case STATUS_BROKEN:
4851 return "BROKEN";
4852
4853 case STATUS_ZOMBIE:
4854 return "ZOMBIE";
4855
4856 default:
4857 return "UNKNOWN";
4858 }
4859}
4860
4861InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004862 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 if (entry->seq == seq) {
4864 return entry;
4865 }
4866 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004867 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868}
4869
4870
4871// --- InputDispatcher::CommandEntry ---
4872
4873InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004874 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 seq(0), handled(false) {
4876}
4877
4878InputDispatcher::CommandEntry::~CommandEntry() {
4879}
4880
4881
4882// --- InputDispatcher::TouchState ---
4883
4884InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004885 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886}
4887
4888InputDispatcher::TouchState::~TouchState() {
4889}
4890
4891void InputDispatcher::TouchState::reset() {
4892 down = false;
4893 split = false;
4894 deviceId = -1;
4895 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004896 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 windows.clear();
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004898 portalWindows.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899}
4900
4901void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4902 down = other.down;
4903 split = other.split;
4904 deviceId = other.deviceId;
4905 source = other.source;
4906 displayId = other.displayId;
4907 windows = other.windows;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004908 portalWindows = other.portalWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909}
4910
4911void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4912 int32_t targetFlags, BitSet32 pointerIds) {
4913 if (targetFlags & InputTarget::FLAG_SPLIT) {
4914 split = true;
4915 }
4916
4917 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004918 TouchedWindow& touchedWindow = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919 if (touchedWindow.windowHandle == windowHandle) {
4920 touchedWindow.targetFlags |= targetFlags;
4921 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4922 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4923 }
4924 touchedWindow.pointerIds.value |= pointerIds.value;
4925 return;
4926 }
4927 }
4928
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004929 TouchedWindow touchedWindow;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930 touchedWindow.windowHandle = windowHandle;
4931 touchedWindow.targetFlags = targetFlags;
4932 touchedWindow.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004933 windows.push_back(touchedWindow);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934}
4935
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004936void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) {
4937 size_t numWindows = portalWindows.size();
4938 for (size_t i = 0; i < numWindows; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004939 if (portalWindows[i] == windowHandle) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004940 return;
4941 }
4942 }
4943 portalWindows.push_back(windowHandle);
4944}
4945
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4947 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004948 if (windows[i].windowHandle == windowHandle) {
4949 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950 return;
4951 }
4952 }
4953}
4954
Robert Carr803535b2018-08-02 16:38:15 -07004955void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4956 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004957 if (windows[i].windowHandle->getToken() == token) {
4958 windows.erase(windows.begin() + i);
Robert Carr803535b2018-08-02 16:38:15 -07004959 return;
4960 }
4961 }
4962}
4963
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4965 for (size_t i = 0 ; i < windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004966 TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4968 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4969 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4970 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4971 i += 1;
4972 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004973 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974 }
4975 }
4976}
4977
4978sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4979 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004980 const TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004981 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4982 return window.windowHandle;
4983 }
4984 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004985 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986}
4987
4988bool InputDispatcher::TouchState::isSlippery() const {
4989 // Must have exactly one foreground window.
4990 bool haveSlipperyForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004991 for (const TouchedWindow& window : windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4993 if (haveSlipperyForegroundWindow
4994 || !(window.windowHandle->getInfo()->layoutParamsFlags
4995 & InputWindowInfo::FLAG_SLIPPERY)) {
4996 return false;
4997 }
4998 haveSlipperyForegroundWindow = true;
4999 }
5000 }
5001 return haveSlipperyForegroundWindow;
5002}
5003
5004
5005// --- InputDispatcherThread ---
5006
5007InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5008 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5009}
5010
5011InputDispatcherThread::~InputDispatcherThread() {
5012}
5013
5014bool InputDispatcherThread::threadLoop() {
5015 mDispatcher->dispatchOnce();
5016 return true;
5017}
5018
5019} // namespace android