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