blob: 381bfe80a2aea00ebc0eaeca68d54d4ba2f48927 [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 Hungb92218b2018-08-14 12:00:21 +0800527 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
528 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800530 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531 const InputWindowInfo* windowInfo = windowHandle->getInfo();
532 if (windowInfo->displayId == displayId) {
533 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534
535 if (windowInfo->visible) {
536 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
537 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
538 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
539 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800540 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
541 if (portalToDisplayId != ADISPLAY_ID_NONE
542 && portalToDisplayId != displayId) {
543 if (addPortalWindows) {
544 // For the monitoring channels of the display.
545 mTempTouchState.addPortalWindow(windowHandle);
546 }
547 return findTouchedWindowAtLocked(
548 portalToDisplayId, x, y, addOutsideTargets, addPortalWindows);
549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 // Found window.
551 return windowHandle;
552 }
553 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800554
555 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
556 mTempTouchState.addOrUpdateWindow(
557 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560 }
561 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700562 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563}
564
565void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
566 const char* reason;
567 switch (dropReason) {
568 case DROP_REASON_POLICY:
569#if DEBUG_INBOUND_EVENT_DETAILS
570 ALOGD("Dropped event because policy consumed it.");
571#endif
572 reason = "inbound event was dropped because the policy consumed it";
573 break;
574 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100575 if (mLastDropReason != DROP_REASON_DISABLED) {
576 ALOGI("Dropped event because input dispatch is disabled.");
577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800578 reason = "inbound event was dropped because input dispatch is disabled";
579 break;
580 case DROP_REASON_APP_SWITCH:
581 ALOGI("Dropped event because of pending overdue app switch.");
582 reason = "inbound event was dropped because of pending overdue app switch";
583 break;
584 case DROP_REASON_BLOCKED:
585 ALOGI("Dropped event because the current application is not responding and the user "
586 "has started interacting with a different application.");
587 reason = "inbound event was dropped because the current application is not responding "
588 "and the user has started interacting with a different application";
589 break;
590 case DROP_REASON_STALE:
591 ALOGI("Dropped event because it is stale.");
592 reason = "inbound event was dropped because it is stale";
593 break;
594 default:
595 ALOG_ASSERT(false);
596 return;
597 }
598
599 switch (entry->type) {
600 case EventEntry::TYPE_KEY: {
601 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
602 synthesizeCancelationEventsForAllConnectionsLocked(options);
603 break;
604 }
605 case EventEntry::TYPE_MOTION: {
606 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
607 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
608 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
609 synthesizeCancelationEventsForAllConnectionsLocked(options);
610 } else {
611 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
612 synthesizeCancelationEventsForAllConnectionsLocked(options);
613 }
614 break;
615 }
616 }
617}
618
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800619static bool isAppSwitchKeyCode(int32_t keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800620 return keyCode == AKEYCODE_HOME
621 || keyCode == AKEYCODE_ENDCALL
622 || keyCode == AKEYCODE_APP_SWITCH;
623}
624
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800625bool InputDispatcher::isAppSwitchKeyEvent(KeyEntry* keyEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
627 && isAppSwitchKeyCode(keyEntry->keyCode)
628 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
629 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
630}
631
632bool InputDispatcher::isAppSwitchPendingLocked() {
633 return mAppSwitchDueTime != LONG_LONG_MAX;
634}
635
636void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
637 mAppSwitchDueTime = LONG_LONG_MAX;
638
639#if DEBUG_APP_SWITCH
640 if (handled) {
641 ALOGD("App switch has arrived.");
642 } else {
643 ALOGD("App switch was abandoned.");
644 }
645#endif
646}
647
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800648bool InputDispatcher::isStaleEvent(nsecs_t currentTime, EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
650}
651
652bool InputDispatcher::haveCommandsLocked() const {
653 return !mCommandQueue.isEmpty();
654}
655
656bool InputDispatcher::runCommandsLockedInterruptible() {
657 if (mCommandQueue.isEmpty()) {
658 return false;
659 }
660
661 do {
662 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
663
664 Command command = commandEntry->command;
665 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
666
667 commandEntry->connection.clear();
668 delete commandEntry;
669 } while (! mCommandQueue.isEmpty());
670 return true;
671}
672
673InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
674 CommandEntry* commandEntry = new CommandEntry(command);
675 mCommandQueue.enqueueAtTail(commandEntry);
676 return commandEntry;
677}
678
679void InputDispatcher::drainInboundQueueLocked() {
680 while (! mInboundQueue.isEmpty()) {
681 EventEntry* entry = mInboundQueue.dequeueAtHead();
682 releaseInboundEventLocked(entry);
683 }
684 traceInboundQueueLengthLocked();
685}
686
687void InputDispatcher::releasePendingEventLocked() {
688 if (mPendingEvent) {
689 resetANRTimeoutsLocked();
690 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700691 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 }
693}
694
695void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
696 InjectionState* injectionState = entry->injectionState;
697 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
698#if DEBUG_DISPATCH_CYCLE
699 ALOGD("Injected inbound event was dropped.");
700#endif
701 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
702 }
703 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700704 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 }
706 addRecentEventLocked(entry);
707 entry->release();
708}
709
710void InputDispatcher::resetKeyRepeatLocked() {
711 if (mKeyRepeatState.lastKeyEntry) {
712 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700713 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 }
715}
716
717InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
718 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
719
720 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700721 uint32_t policyFlags = entry->policyFlags &
722 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723 if (entry->refCount == 1) {
724 entry->recycle();
725 entry->eventTime = currentTime;
726 entry->policyFlags = policyFlags;
727 entry->repeatCount += 1;
728 } else {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800729 KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100730 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731 entry->action, entry->flags, entry->keyCode, entry->scanCode,
732 entry->metaState, entry->repeatCount + 1, entry->downTime);
733
734 mKeyRepeatState.lastKeyEntry = newEntry;
735 entry->release();
736
737 entry = newEntry;
738 }
739 entry->syntheticRepeat = true;
740
741 // Increment reference count since we keep a reference to the event in
742 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
743 entry->refCount += 1;
744
745 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
746 return entry;
747}
748
749bool InputDispatcher::dispatchConfigurationChangedLocked(
750 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
751#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700752 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753#endif
754
755 // Reset key repeating in case a keyboard device was added or removed or something.
756 resetKeyRepeatLocked();
757
758 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
759 CommandEntry* commandEntry = postCommandLocked(
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800760 & InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800761 commandEntry->eventTime = entry->eventTime;
762 return true;
763}
764
765bool InputDispatcher::dispatchDeviceResetLocked(
766 nsecs_t currentTime, DeviceResetEntry* entry) {
767#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700768 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
769 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770#endif
771
772 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
773 "device was reset");
774 options.deviceId = entry->deviceId;
775 synthesizeCancelationEventsForAllConnectionsLocked(options);
776 return true;
777}
778
779bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
780 DropReason* dropReason, nsecs_t* nextWakeupTime) {
781 // Preprocessing.
782 if (! entry->dispatchInProgress) {
783 if (entry->repeatCount == 0
784 && entry->action == AKEY_EVENT_ACTION_DOWN
785 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
786 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
787 if (mKeyRepeatState.lastKeyEntry
788 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
789 // We have seen two identical key downs in a row which indicates that the device
790 // driver is automatically generating key repeats itself. We take note of the
791 // repeat here, but we disable our own next key repeat timer since it is clear that
792 // we will not need to synthesize key repeats ourselves.
793 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
794 resetKeyRepeatLocked();
795 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
796 } else {
797 // Not a repeat. Save key down state in case we do see a repeat later.
798 resetKeyRepeatLocked();
799 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
800 }
801 mKeyRepeatState.lastKeyEntry = entry;
802 entry->refCount += 1;
803 } else if (! entry->syntheticRepeat) {
804 resetKeyRepeatLocked();
805 }
806
807 if (entry->repeatCount == 1) {
808 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
809 } else {
810 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
811 }
812
813 entry->dispatchInProgress = true;
814
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800815 logOutboundKeyDetails("dispatchKey - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816 }
817
818 // Handle case where the policy asked us to try again later last time.
819 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
820 if (currentTime < entry->interceptKeyWakeupTime) {
821 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
822 *nextWakeupTime = entry->interceptKeyWakeupTime;
823 }
824 return false; // wait until next wakeup
825 }
826 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
827 entry->interceptKeyWakeupTime = 0;
828 }
829
830 // Give the policy a chance to intercept the key.
831 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
832 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
833 CommandEntry* commandEntry = postCommandLocked(
834 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800835 sp<InputWindowHandle> focusedWindowHandle =
836 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
837 if (focusedWindowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -0700838 commandEntry->inputChannel =
839 getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840 }
841 commandEntry->keyEntry = entry;
842 entry->refCount += 1;
843 return false; // wait for the command to run
844 } else {
845 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
846 }
847 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
848 if (*dropReason == DROP_REASON_NOT_DROPPED) {
849 *dropReason = DROP_REASON_POLICY;
850 }
851 }
852
853 // Clean up if dropping the event.
854 if (*dropReason != DROP_REASON_NOT_DROPPED) {
855 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
856 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800857 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 return true;
859 }
860
861 // Identify targets.
862 Vector<InputTarget> inputTargets;
863 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
864 entry, inputTargets, nextWakeupTime);
865 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
866 return false;
867 }
868
869 setInjectionResultLocked(entry, injectionResult);
870 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
871 return true;
872 }
873
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800874 // Add monitor channels from event's or focused display.
875 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876
877 // Dispatch the key.
878 dispatchEventLocked(currentTime, entry, inputTargets);
879 return true;
880}
881
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800882void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100884 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
885 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800886 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100888 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800890 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891#endif
892}
893
894bool InputDispatcher::dispatchMotionLocked(
895 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
896 // Preprocessing.
897 if (! entry->dispatchInProgress) {
898 entry->dispatchInProgress = true;
899
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800900 logOutboundMotionDetails("dispatchMotion - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 }
902
903 // Clean up if dropping the event.
904 if (*dropReason != DROP_REASON_NOT_DROPPED) {
905 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
906 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
907 return true;
908 }
909
910 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
911
912 // Identify targets.
913 Vector<InputTarget> inputTargets;
914
915 bool conflictingPointerActions = false;
916 int32_t injectionResult;
917 if (isPointerEvent) {
918 // Pointer event. (eg. touchscreen)
919 injectionResult = findTouchedWindowTargetsLocked(currentTime,
920 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
921 } else {
922 // Non touch event. (eg. trackball)
923 injectionResult = findFocusedWindowTargetsLocked(currentTime,
924 entry, inputTargets, nextWakeupTime);
925 }
926 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
927 return false;
928 }
929
930 setInjectionResultLocked(entry, injectionResult);
931 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100932 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
933 CancelationOptions::Mode mode(isPointerEvent ?
934 CancelationOptions::CANCEL_POINTER_EVENTS :
935 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
936 CancelationOptions options(mode, "input event injection failed");
937 synthesizeCancelationEventsForMonitorsLocked(options);
938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939 return true;
940 }
941
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800942 // Add monitor channels from event's or focused display.
943 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800945 if (isPointerEvent) {
946 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
947 if (stateIndex >= 0) {
948 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
949 if (!state.portalWindows.isEmpty()) {
950 // The event has gone through these portal windows, so we add monitoring targets of
951 // the corresponding displays as well.
952 for (size_t i = 0; i < state.portalWindows.size(); i++) {
953 const InputWindowInfo* windowInfo = state.portalWindows.itemAt(i)->getInfo();
954 addMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
955 -windowInfo->frameLeft, -windowInfo->frameTop);
956 }
957 }
958 }
959 }
960
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 // Dispatch the motion.
962 if (conflictingPointerActions) {
963 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
964 "conflicting pointer actions");
965 synthesizeCancelationEventsForAllConnectionsLocked(options);
966 }
967 dispatchEventLocked(currentTime, entry, inputTargets);
968 return true;
969}
970
971
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800972void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800974 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
975 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100976 "action=0x%x, actionButton=0x%x, flags=0x%x, "
977 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800978 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800980 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100981 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 entry->metaState, entry->buttonState,
983 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800984 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985
986 for (uint32_t i = 0; i < entry->pointerCount; i++) {
987 ALOGD(" Pointer %d: id=%d, toolType=%d, "
988 "x=%f, y=%f, pressure=%f, size=%f, "
989 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800990 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 i, entry->pointerProperties[i].id,
992 entry->pointerProperties[i].toolType,
993 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
994 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
995 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
996 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
997 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
998 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
999 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1000 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08001001 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 }
1003#endif
1004}
1005
1006void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1007 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
1008#if DEBUG_DISPATCH_CYCLE
1009 ALOGD("dispatchEventToCurrentInputTargets");
1010#endif
1011
1012 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1013
1014 pokeUserActivityLocked(eventEntry);
1015
1016 for (size_t i = 0; i < inputTargets.size(); i++) {
1017 const InputTarget& inputTarget = inputTargets.itemAt(i);
1018
1019 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
1020 if (connectionIndex >= 0) {
1021 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1022 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1023 } else {
1024#if DEBUG_FOCUS
1025 ALOGD("Dropping event delivery to target with channel '%s' because it "
1026 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001027 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028#endif
1029 }
1030 }
1031}
1032
1033int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1034 const EventEntry* entry,
1035 const sp<InputApplicationHandle>& applicationHandle,
1036 const sp<InputWindowHandle>& windowHandle,
1037 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001038 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1040#if DEBUG_FOCUS
1041 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1042#endif
1043 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1044 mInputTargetWaitStartTime = currentTime;
1045 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1046 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001047 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 }
1049 } else {
1050 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1051#if DEBUG_FOCUS
1052 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001053 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 reason);
1055#endif
1056 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001057 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001059 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 timeout = applicationHandle->getDispatchingTimeout(
1061 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1062 } else {
1063 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1064 }
1065
1066 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1067 mInputTargetWaitStartTime = currentTime;
1068 mInputTargetWaitTimeoutTime = currentTime + timeout;
1069 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001070 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071
Yi Kong9b14ac62018-07-17 13:48:38 -07001072 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001073 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 }
Robert Carr740167f2018-10-11 19:03:41 -07001075 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1076 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077 }
1078 }
1079 }
1080
1081 if (mInputTargetWaitTimeoutExpired) {
1082 return INPUT_EVENT_INJECTION_TIMED_OUT;
1083 }
1084
1085 if (currentTime >= mInputTargetWaitTimeoutTime) {
1086 onANRLocked(currentTime, applicationHandle, windowHandle,
1087 entry->eventTime, mInputTargetWaitStartTime, reason);
1088
1089 // Force poll loop to wake up immediately on next iteration once we get the
1090 // ANR response back from the policy.
1091 *nextWakeupTime = LONG_LONG_MIN;
1092 return INPUT_EVENT_INJECTION_PENDING;
1093 } else {
1094 // Force poll loop to wake up when timeout is due.
1095 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1096 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1097 }
1098 return INPUT_EVENT_INJECTION_PENDING;
1099 }
1100}
1101
Robert Carr803535b2018-08-02 16:38:15 -07001102void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1103 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1104 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1105 state.removeWindowByToken(token);
1106 }
1107}
1108
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1110 const sp<InputChannel>& inputChannel) {
1111 if (newTimeout > 0) {
1112 // Extend the timeout.
1113 mInputTargetWaitTimeoutTime = now() + newTimeout;
1114 } else {
1115 // Give up.
1116 mInputTargetWaitTimeoutExpired = true;
1117
1118 // Input state will not be realistic. Mark it out of sync.
1119 if (inputChannel.get()) {
1120 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1121 if (connectionIndex >= 0) {
1122 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001123 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124
Robert Carr803535b2018-08-02 16:38:15 -07001125 if (token != nullptr) {
1126 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 }
1128
1129 if (connection->status == Connection::STATUS_NORMAL) {
1130 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1131 "application not responding");
1132 synthesizeCancelationEventsForConnectionLocked(connection, options);
1133 }
1134 }
1135 }
1136 }
1137}
1138
1139nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1140 nsecs_t currentTime) {
1141 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1142 return currentTime - mInputTargetWaitStartTime;
1143 }
1144 return 0;
1145}
1146
1147void InputDispatcher::resetANRTimeoutsLocked() {
1148#if DEBUG_FOCUS
1149 ALOGD("Resetting ANR timeouts.");
1150#endif
1151
1152 // Reset input target wait timeout.
1153 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001154 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155}
1156
Tiger Huang721e26f2018-07-24 22:26:19 +08001157/**
1158 * Get the display id that the given event should go to. If this event specifies a valid display id,
1159 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1160 * Focused display is the display that the user most recently interacted with.
1161 */
1162int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1163 int32_t displayId;
1164 switch (entry->type) {
1165 case EventEntry::TYPE_KEY: {
1166 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1167 displayId = typedEntry->displayId;
1168 break;
1169 }
1170 case EventEntry::TYPE_MOTION: {
1171 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1172 displayId = typedEntry->displayId;
1173 break;
1174 }
1175 default: {
1176 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1177 return ADISPLAY_ID_NONE;
1178 }
1179 }
1180 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1181}
1182
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1184 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1185 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001186 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187
Tiger Huang721e26f2018-07-24 22:26:19 +08001188 int32_t displayId = getTargetDisplayId(entry);
1189 sp<InputWindowHandle> focusedWindowHandle =
1190 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1191 sp<InputApplicationHandle> focusedApplicationHandle =
1192 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1193
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 // If there is no currently focused window and no focused application
1195 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001196 if (focusedWindowHandle == nullptr) {
1197 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001199 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 "Waiting because no window has focus but there is a "
1201 "focused application that may eventually add a window "
1202 "when it finishes starting up.");
1203 goto Unresponsive;
1204 }
1205
Arthur Hung3b413f22018-10-26 18:05:34 +08001206 ALOGI("Dropping event because there is no focused window or focused application in display "
1207 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1209 goto Failed;
1210 }
1211
1212 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001213 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1215 goto Failed;
1216 }
1217
Jeff Brownffb49772014-10-10 19:01:34 -07001218 // Check whether the window is ready for more input.
1219 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001220 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001221 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001223 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 goto Unresponsive;
1225 }
1226
1227 // Success! Output targets.
1228 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001229 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1231 inputTargets);
1232
1233 // Done.
1234Failed:
1235Unresponsive:
1236 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001237 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238#if DEBUG_FOCUS
1239 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1240 "timeSpentWaitingForApplication=%0.1fms",
1241 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1242#endif
1243 return injectionResult;
1244}
1245
1246int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1247 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1248 bool* outConflictingPointerActions) {
1249 enum InjectionPermission {
1250 INJECTION_PERMISSION_UNKNOWN,
1251 INJECTION_PERMISSION_GRANTED,
1252 INJECTION_PERMISSION_DENIED
1253 };
1254
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 // For security reasons, we defer updating the touch state until we are sure that
1256 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 int32_t displayId = entry->displayId;
1258 int32_t action = entry->action;
1259 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1260
1261 // Update the touch state as needed based on the properties of the touch event.
1262 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1263 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1264 sp<InputWindowHandle> newHoverWindowHandle;
1265
Jeff Brownf086ddb2014-02-11 14:28:48 -08001266 // Copy current touch state into mTempTouchState.
1267 // This state is always reset at the end of this function, so if we don't find state
1268 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001269 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001270 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1271 if (oldStateIndex >= 0) {
1272 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1273 mTempTouchState.copyFrom(*oldState);
1274 }
1275
1276 bool isSplit = mTempTouchState.split;
1277 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1278 && (mTempTouchState.deviceId != entry->deviceId
1279 || mTempTouchState.source != entry->source
1280 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1282 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1283 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1284 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1285 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1286 || isHoverAction);
1287 bool wrongDevice = false;
1288 if (newGesture) {
1289 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001290 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001292 ALOGD("Dropping event because a pointer for a different device is already down "
1293 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001295 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1297 switchedDevice = false;
1298 wrongDevice = true;
1299 goto Failed;
1300 }
1301 mTempTouchState.reset();
1302 mTempTouchState.down = down;
1303 mTempTouchState.deviceId = entry->deviceId;
1304 mTempTouchState.source = entry->source;
1305 mTempTouchState.displayId = displayId;
1306 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001307 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1308#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001309 ALOGI("Dropping move event because a pointer for a different device is already active "
1310 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001311#endif
1312 // TODO: test multiple simultaneous input streams.
1313 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1314 switchedDevice = false;
1315 wrongDevice = true;
1316 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 }
1318
1319 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1320 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1321
1322 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1323 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1324 getAxisValue(AMOTION_EVENT_AXIS_X));
1325 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1326 getAxisValue(AMOTION_EVENT_AXIS_Y));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001327 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(
1328 displayId, x, y, maskedAction == AMOTION_EVENT_ACTION_DOWN, true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001331 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1333 // New window supports splitting.
1334 isSplit = true;
1335 } else if (isSplit) {
1336 // New window does not support splitting but we have already split events.
1337 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001338 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 }
1340
1341 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001342 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 // Try to assign the pointer to the first foreground window we find, if there is one.
1344 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001345 if (newTouchedWindowHandle == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08001346 ALOGI("Dropping event because there is no touchable window at (%d, %d) in display "
1347 "%" PRId32 ".", x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1349 goto Failed;
1350 }
1351 }
1352
1353 // Set target flags.
1354 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1355 if (isSplit) {
1356 targetFlags |= InputTarget::FLAG_SPLIT;
1357 }
1358 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1359 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001360 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1361 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 }
1363
1364 // Update hover state.
1365 if (isHoverAction) {
1366 newHoverWindowHandle = newTouchedWindowHandle;
1367 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1368 newHoverWindowHandle = mLastHoverWindowHandle;
1369 }
1370
1371 // Update the temporary touch state.
1372 BitSet32 pointerIds;
1373 if (isSplit) {
1374 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1375 pointerIds.markBit(pointerId);
1376 }
1377 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1378 } else {
1379 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1380
1381 // If the pointer is not currently down, then ignore the event.
1382 if (! mTempTouchState.down) {
1383#if DEBUG_FOCUS
1384 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001385 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386#endif
1387 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1388 goto Failed;
1389 }
1390
1391 // Check whether touches should slip outside of the current foreground window.
1392 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1393 && entry->pointerCount == 1
1394 && mTempTouchState.isSlippery()) {
1395 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1396 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1397
1398 sp<InputWindowHandle> oldTouchedWindowHandle =
1399 mTempTouchState.getFirstForegroundWindowHandle();
1400 sp<InputWindowHandle> newTouchedWindowHandle =
1401 findTouchedWindowAtLocked(displayId, x, y);
1402 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001403 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001405 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001406 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001407 newTouchedWindowHandle->getName().c_str(),
1408 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001409#endif
1410 // Make a slippery exit from the old window.
1411 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1412 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1413
1414 // Make a slippery entrance into the new window.
1415 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1416 isSplit = true;
1417 }
1418
1419 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1420 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1421 if (isSplit) {
1422 targetFlags |= InputTarget::FLAG_SPLIT;
1423 }
1424 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1425 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1426 }
1427
1428 BitSet32 pointerIds;
1429 if (isSplit) {
1430 pointerIds.markBit(entry->pointerProperties[0].id);
1431 }
1432 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1433 }
1434 }
1435 }
1436
1437 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1438 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001439 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440#if DEBUG_HOVER
1441 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001442 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443#endif
1444 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1445 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1446 }
1447
1448 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001449 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450#if DEBUG_HOVER
1451 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001452 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453#endif
1454 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1455 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1456 }
1457 }
1458
1459 // Check permission to inject into all touched foreground windows and ensure there
1460 // is at least one touched foreground window.
1461 {
1462 bool haveForegroundWindow = false;
1463 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1464 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1465 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1466 haveForegroundWindow = true;
1467 if (! checkInjectionPermission(touchedWindow.windowHandle,
1468 entry->injectionState)) {
1469 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1470 injectionPermission = INJECTION_PERMISSION_DENIED;
1471 goto Failed;
1472 }
1473 }
1474 }
1475 if (! haveForegroundWindow) {
1476#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001477 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1478 " to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479#endif
1480 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1481 goto Failed;
1482 }
1483
1484 // Permission granted to injection into all touched foreground windows.
1485 injectionPermission = INJECTION_PERMISSION_GRANTED;
1486 }
1487
1488 // Check whether windows listening for outside touches are owned by the same UID. If it is
1489 // set the policy flag that we will not reveal coordinate information to this window.
1490 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1491 sp<InputWindowHandle> foregroundWindowHandle =
1492 mTempTouchState.getFirstForegroundWindowHandle();
1493 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1494 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1495 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1496 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1497 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1498 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1499 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1500 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1501 }
1502 }
1503 }
1504 }
1505
1506 // Ensure all touched foreground windows are ready for new input.
1507 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1508 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1509 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001510 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001511 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001512 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001513 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001515 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 goto Unresponsive;
1517 }
1518 }
1519 }
1520
1521 // If this is the first pointer going down and the touched window has a wallpaper
1522 // then also add the touched wallpaper windows so they are locked in for the duration
1523 // of the touch gesture.
1524 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1525 // engine only supports touch events. We would need to add a mechanism similar
1526 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1527 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1528 sp<InputWindowHandle> foregroundWindowHandle =
1529 mTempTouchState.getFirstForegroundWindowHandle();
1530 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001531 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1532 size_t numWindows = windowHandles.size();
1533 for (size_t i = 0; i < numWindows; i++) {
1534 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535 const InputWindowInfo* info = windowHandle->getInfo();
1536 if (info->displayId == displayId
1537 && windowHandle->getInfo()->layoutParamsType
1538 == InputWindowInfo::TYPE_WALLPAPER) {
1539 mTempTouchState.addOrUpdateWindow(windowHandle,
1540 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001541 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 | InputTarget::FLAG_DISPATCH_AS_IS,
1543 BitSet32(0));
1544 }
1545 }
1546 }
1547 }
1548
1549 // Success! Output targets.
1550 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1551
1552 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1553 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1554 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1555 touchedWindow.pointerIds, inputTargets);
1556 }
1557
1558 // Drop the outside or hover touch windows since we will not care about them
1559 // in the next iteration.
1560 mTempTouchState.filterNonAsIsTouchWindows();
1561
1562Failed:
1563 // Check injection permission once and for all.
1564 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001565 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 injectionPermission = INJECTION_PERMISSION_GRANTED;
1567 } else {
1568 injectionPermission = INJECTION_PERMISSION_DENIED;
1569 }
1570 }
1571
1572 // Update final pieces of touch state if the injector had permission.
1573 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1574 if (!wrongDevice) {
1575 if (switchedDevice) {
1576#if DEBUG_FOCUS
1577 ALOGD("Conflicting pointer actions: Switched to a different device.");
1578#endif
1579 *outConflictingPointerActions = true;
1580 }
1581
1582 if (isHoverAction) {
1583 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001584 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585#if DEBUG_FOCUS
1586 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1587#endif
1588 *outConflictingPointerActions = true;
1589 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001590 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1592 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001593 mTempTouchState.deviceId = entry->deviceId;
1594 mTempTouchState.source = entry->source;
1595 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 }
1597 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1598 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1599 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001600 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1602 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001603 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604#if DEBUG_FOCUS
1605 ALOGD("Conflicting pointer actions: Down received while already down.");
1606#endif
1607 *outConflictingPointerActions = true;
1608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1610 // One pointer went up.
1611 if (isSplit) {
1612 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1613 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1614
1615 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1616 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1617 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1618 touchedWindow.pointerIds.clearBit(pointerId);
1619 if (touchedWindow.pointerIds.isEmpty()) {
1620 mTempTouchState.windows.removeAt(i);
1621 continue;
1622 }
1623 }
1624 i += 1;
1625 }
1626 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001627 }
1628
1629 // Save changes unless the action was scroll in which case the temporary touch
1630 // state was only valid for this one action.
1631 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1632 if (mTempTouchState.displayId >= 0) {
1633 if (oldStateIndex >= 0) {
1634 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1635 } else {
1636 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1637 }
1638 } else if (oldStateIndex >= 0) {
1639 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 }
1642
1643 // Update hover state.
1644 mLastHoverWindowHandle = newHoverWindowHandle;
1645 }
1646 } else {
1647#if DEBUG_FOCUS
1648 ALOGD("Not updating touch focus because injection was denied.");
1649#endif
1650 }
1651
1652Unresponsive:
1653 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1654 mTempTouchState.reset();
1655
1656 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001657 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658#if DEBUG_FOCUS
1659 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1660 "timeSpentWaitingForApplication=%0.1fms",
1661 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1662#endif
1663 return injectionResult;
1664}
1665
1666void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1667 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001668 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1669 if (inputChannel == nullptr) {
1670 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1671 return;
1672 }
1673
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 inputTargets.push();
1675
1676 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1677 InputTarget& target = inputTargets.editTop();
Arthur Hungceeb5d72018-12-05 16:14:18 +08001678 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 target.flags = targetFlags;
1680 target.xOffset = - windowInfo->frameLeft;
1681 target.yOffset = - windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001682 target.globalScaleFactor = windowInfo->globalScaleFactor;
1683 target.windowXScale = windowInfo->windowXScale;
1684 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 target.pointerIds = pointerIds;
1686}
1687
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001688void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001689 int32_t displayId, float xOffset, float yOffset) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001690 std::unordered_map<int32_t, Vector<sp<InputChannel>>>::const_iterator it =
1691 mMonitoringChannelsByDisplay.find(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001693 if (it != mMonitoringChannelsByDisplay.end()) {
1694 const Vector<sp<InputChannel>>& monitoringChannels = it->second;
1695 const size_t numChannels = monitoringChannels.size();
1696 for (size_t i = 0; i < numChannels; i++) {
1697 inputTargets.push();
1698
1699 InputTarget& target = inputTargets.editTop();
1700 target.inputChannel = monitoringChannels[i];
1701 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001702 target.xOffset = xOffset;
1703 target.yOffset = yOffset;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001704 target.pointerIds.clear();
Robert Carre07e1032018-11-26 12:55:53 -08001705 target.globalScaleFactor = 1.0f;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001706 }
1707 } else {
1708 // If there is no monitor channel registered or all monitor channel unregistered,
1709 // the display can't detect the extra system gesture by a copy of input events.
Arthur Hung3b413f22018-10-26 18:05:34 +08001710 ALOGW("There is no monitor channel found in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 }
1712}
1713
1714bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1715 const InjectionState* injectionState) {
1716 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001717 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1719 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001720 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1722 "owned by uid %d",
1723 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001724 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 windowHandle->getInfo()->ownerUid);
1726 } else {
1727 ALOGW("Permission denied: injecting event from pid %d uid %d",
1728 injectionState->injectorPid, injectionState->injectorUid);
1729 }
1730 return false;
1731 }
1732 return true;
1733}
1734
1735bool InputDispatcher::isWindowObscuredAtPointLocked(
1736 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1737 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001738 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1739 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001741 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 if (otherHandle == windowHandle) {
1743 break;
1744 }
1745
1746 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1747 if (otherInfo->displayId == displayId
1748 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1749 && otherInfo->frameContainsPoint(x, y)) {
1750 return true;
1751 }
1752 }
1753 return false;
1754}
1755
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001756
1757bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1758 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001759 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001760 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hungb92218b2018-08-14 12:00:21 +08001761 size_t numWindows = windowHandles.size();
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001762 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001763 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001764 if (otherHandle == windowHandle) {
1765 break;
1766 }
1767
1768 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1769 if (otherInfo->displayId == displayId
1770 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1771 && otherInfo->overlaps(windowInfo)) {
1772 return true;
1773 }
1774 }
1775 return false;
1776}
1777
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001778std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001779 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1780 const char* targetType) {
1781 // If the window is paused then keep waiting.
1782 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001783 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001784 }
1785
1786 // If the window's connection is not registered then keep waiting.
Robert Carr5c8a0262018-10-03 16:30:44 -07001787 ssize_t connectionIndex = getConnectionIndexLocked(
1788 getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001789 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001790 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001791 "registered with the input dispatcher. The window may be in the process "
1792 "of being removed.", targetType);
1793 }
1794
1795 // If the connection is dead then keep waiting.
1796 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1797 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001798 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001799 "The window may be in the process of being removed.", targetType,
1800 connection->getStatusLabel());
1801 }
1802
1803 // If the connection is backed up then keep waiting.
1804 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001805 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001806 "Outbound queue length: %d. Wait queue length: %d.",
1807 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1808 }
1809
1810 // Ensure that the dispatch queues aren't too far backed up for this event.
1811 if (eventEntry->type == EventEntry::TYPE_KEY) {
1812 // If the event is a key event, then we must wait for all previous events to
1813 // complete before delivering it because previous events may have the
1814 // side-effect of transferring focus to a different window and we want to
1815 // ensure that the following keys are sent to the new window.
1816 //
1817 // Suppose the user touches a button in a window then immediately presses "A".
1818 // If the button causes a pop-up window to appear then we want to ensure that
1819 // the "A" key is delivered to the new pop-up window. This is because users
1820 // often anticipate pending UI changes when typing on a keyboard.
1821 // To obtain this behavior, we must serialize key events with respect to all
1822 // prior input events.
1823 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001824 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001825 "finished processing all of the input events that were previously "
1826 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1827 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 }
Jeff Brownffb49772014-10-10 19:01:34 -07001829 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830 // Touch events can always be sent to a window immediately because the user intended
1831 // to touch whatever was visible at the time. Even if focus changes or a new
1832 // window appears moments later, the touch event was meant to be delivered to
1833 // whatever window happened to be on screen at the time.
1834 //
1835 // Generic motion events, such as trackball or joystick events are a little trickier.
1836 // Like key events, generic motion events are delivered to the focused window.
1837 // Unlike key events, generic motion events don't tend to transfer focus to other
1838 // windows and it is not important for them to be serialized. So we prefer to deliver
1839 // generic motion events as soon as possible to improve efficiency and reduce lag
1840 // through batching.
1841 //
1842 // The one case where we pause input event delivery is when the wait queue is piling
1843 // up with lots of events because the application is not responding.
1844 // This condition ensures that ANRs are detected reliably.
1845 if (!connection->waitQueue.isEmpty()
1846 && currentTime >= connection->waitQueue.head->deliveryTime
1847 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001848 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001849 "finished processing certain input events that were delivered to it over "
1850 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1851 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1852 connection->waitQueue.count(),
1853 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 }
1855 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001856 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857}
1858
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001859std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 const sp<InputApplicationHandle>& applicationHandle,
1861 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001862 if (applicationHandle != nullptr) {
1863 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001864 std::string label(applicationHandle->getName());
1865 label += " - ";
1866 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 return label;
1868 } else {
1869 return applicationHandle->getName();
1870 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001871 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872 return windowHandle->getName();
1873 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001874 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 }
1876}
1877
1878void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001879 int32_t displayId = getTargetDisplayId(eventEntry);
1880 sp<InputWindowHandle> focusedWindowHandle =
1881 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1882 if (focusedWindowHandle != nullptr) {
1883 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1885#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001886 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887#endif
1888 return;
1889 }
1890 }
1891
1892 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1893 switch (eventEntry->type) {
1894 case EventEntry::TYPE_MOTION: {
1895 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1896 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1897 return;
1898 }
1899
1900 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1901 eventType = USER_ACTIVITY_EVENT_TOUCH;
1902 }
1903 break;
1904 }
1905 case EventEntry::TYPE_KEY: {
1906 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1907 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1908 return;
1909 }
1910 eventType = USER_ACTIVITY_EVENT_BUTTON;
1911 break;
1912 }
1913 }
1914
1915 CommandEntry* commandEntry = postCommandLocked(
1916 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1917 commandEntry->eventTime = eventEntry->eventTime;
1918 commandEntry->userActivityEventType = eventType;
1919}
1920
1921void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1922 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1923#if DEBUG_DISPATCH_CYCLE
1924 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Robert Carre07e1032018-11-26 12:55:53 -08001925 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1926 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001927 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08001929 inputTarget->globalScaleFactor,
1930 inputTarget->windowXScale, inputTarget->windowYScale,
1931 inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932#endif
1933
1934 // Skip this event if the connection status is not normal.
1935 // We don't want to enqueue additional outbound events if the connection is broken.
1936 if (connection->status != Connection::STATUS_NORMAL) {
1937#if DEBUG_DISPATCH_CYCLE
1938 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001939 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940#endif
1941 return;
1942 }
1943
1944 // Split a motion event if needed.
1945 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1946 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1947
1948 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1949 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1950 MotionEntry* splitMotionEntry = splitMotionEvent(
1951 originalMotionEntry, inputTarget->pointerIds);
1952 if (!splitMotionEntry) {
1953 return; // split event was dropped
1954 }
1955#if DEBUG_FOCUS
1956 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001957 connection->getInputChannelName().c_str());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001958 logOutboundMotionDetails(" ", splitMotionEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959#endif
1960 enqueueDispatchEntriesLocked(currentTime, connection,
1961 splitMotionEntry, inputTarget);
1962 splitMotionEntry->release();
1963 return;
1964 }
1965 }
1966
1967 // Not splitting. Enqueue dispatch entries for the event as is.
1968 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1969}
1970
1971void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1972 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1973 bool wasEmpty = connection->outboundQueue.isEmpty();
1974
1975 // Enqueue dispatch entries for the requested modes.
1976 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1977 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1978 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1979 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1980 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1981 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1982 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1983 InputTarget::FLAG_DISPATCH_AS_IS);
1984 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1985 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1986 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1987 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1988
1989 // If the outbound queue was previously empty, start the dispatch cycle going.
1990 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1991 startDispatchCycleLocked(currentTime, connection);
1992 }
1993}
1994
1995void InputDispatcher::enqueueDispatchEntryLocked(
1996 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1997 int32_t dispatchMode) {
1998 int32_t inputTargetFlags = inputTarget->flags;
1999 if (!(inputTargetFlags & dispatchMode)) {
2000 return;
2001 }
2002 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2003
2004 // This is a new event.
2005 // Enqueue a new dispatch entry onto the outbound queue for this connection.
2006 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
2007 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08002008 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2009 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010
2011 // Apply target flags and update the connection's input state.
2012 switch (eventEntry->type) {
2013 case EventEntry::TYPE_KEY: {
2014 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2015 dispatchEntry->resolvedAction = keyEntry->action;
2016 dispatchEntry->resolvedFlags = keyEntry->flags;
2017
2018 if (!connection->inputState.trackKey(keyEntry,
2019 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2020#if DEBUG_DISPATCH_CYCLE
2021 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002022 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023#endif
2024 delete dispatchEntry;
2025 return; // skip the inconsistent event
2026 }
2027 break;
2028 }
2029
2030 case EventEntry::TYPE_MOTION: {
2031 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2032 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2033 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2034 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2035 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2036 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2037 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2038 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2039 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2040 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2041 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2042 } else {
2043 dispatchEntry->resolvedAction = motionEntry->action;
2044 }
2045 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2046 && !connection->inputState.isHovering(
2047 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2048#if DEBUG_DISPATCH_CYCLE
2049 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002050 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051#endif
2052 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2053 }
2054
2055 dispatchEntry->resolvedFlags = motionEntry->flags;
2056 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2057 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2058 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002059 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2060 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062
2063 if (!connection->inputState.trackMotion(motionEntry,
2064 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2065#if DEBUG_DISPATCH_CYCLE
2066 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002067 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068#endif
2069 delete dispatchEntry;
2070 return; // skip the inconsistent event
2071 }
2072 break;
2073 }
2074 }
2075
2076 // Remember that we are waiting for this dispatch to complete.
2077 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002078 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 }
2080
2081 // Enqueue the dispatch entry.
2082 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002083 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084}
2085
2086void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2087 const sp<Connection>& connection) {
2088#if DEBUG_DISPATCH_CYCLE
2089 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002090 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091#endif
2092
2093 while (connection->status == Connection::STATUS_NORMAL
2094 && !connection->outboundQueue.isEmpty()) {
2095 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2096 dispatchEntry->deliveryTime = currentTime;
2097
2098 // Publish the event.
2099 status_t status;
2100 EventEntry* eventEntry = dispatchEntry->eventEntry;
2101 switch (eventEntry->type) {
2102 case EventEntry::TYPE_KEY: {
2103 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2104
2105 // Publish the key event.
2106 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002107 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2109 keyEntry->keyCode, keyEntry->scanCode,
2110 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2111 keyEntry->eventTime);
2112 break;
2113 }
2114
2115 case EventEntry::TYPE_MOTION: {
2116 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2117
2118 PointerCoords scaledCoords[MAX_POINTERS];
2119 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2120
2121 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002122 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2124 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002125 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2126 float wxs = dispatchEntry->windowXScale;
2127 float wys = dispatchEntry->windowYScale;
2128 xOffset = dispatchEntry->xOffset * wxs;
2129 yOffset = dispatchEntry->yOffset * wys;
2130 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002131 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002133 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134 }
2135 usingCoords = scaledCoords;
2136 }
2137 } else {
2138 xOffset = 0.0f;
2139 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140
2141 // We don't want the dispatch target to know.
2142 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002143 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 scaledCoords[i].clear();
2145 }
2146 usingCoords = scaledCoords;
2147 }
2148 }
2149
2150 // Publish the motion event.
2151 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002152 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002153 dispatchEntry->resolvedAction, motionEntry->actionButton,
2154 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002155 motionEntry->metaState, motionEntry->buttonState, motionEntry->classification,
Michael Wright7b159c92015-05-14 14:48:03 +01002156 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 motionEntry->downTime, motionEntry->eventTime,
2158 motionEntry->pointerCount, motionEntry->pointerProperties,
2159 usingCoords);
2160 break;
2161 }
2162
2163 default:
2164 ALOG_ASSERT(false);
2165 return;
2166 }
2167
2168 // Check the result.
2169 if (status) {
2170 if (status == WOULD_BLOCK) {
2171 if (connection->waitQueue.isEmpty()) {
2172 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2173 "This is unexpected because the wait queue is empty, so the pipe "
2174 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002175 "event to it, status=%d", connection->getInputChannelName().c_str(),
2176 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2178 } else {
2179 // Pipe is full and we are waiting for the app to finish process some events
2180 // before sending more events to it.
2181#if DEBUG_DISPATCH_CYCLE
2182 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2183 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002184 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185#endif
2186 connection->inputPublisherBlocked = true;
2187 }
2188 } else {
2189 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002190 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2192 }
2193 return;
2194 }
2195
2196 // Re-enqueue the event on the wait queue.
2197 connection->outboundQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002198 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 connection->waitQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002200 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 }
2202}
2203
2204void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2205 const sp<Connection>& connection, uint32_t seq, bool handled) {
2206#if DEBUG_DISPATCH_CYCLE
2207 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002208 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209#endif
2210
2211 connection->inputPublisherBlocked = false;
2212
2213 if (connection->status == Connection::STATUS_BROKEN
2214 || connection->status == Connection::STATUS_ZOMBIE) {
2215 return;
2216 }
2217
2218 // Notify other system components and prepare to start the next dispatch cycle.
2219 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2220}
2221
2222void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2223 const sp<Connection>& connection, bool notify) {
2224#if DEBUG_DISPATCH_CYCLE
2225 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002226 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227#endif
2228
2229 // Clear the dispatch queues.
2230 drainDispatchQueueLocked(&connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002231 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 drainDispatchQueueLocked(&connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002233 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234
2235 // The connection appears to be unrecoverably broken.
2236 // Ignore already broken or zombie connections.
2237 if (connection->status == Connection::STATUS_NORMAL) {
2238 connection->status = Connection::STATUS_BROKEN;
2239
2240 if (notify) {
2241 // Notify other system components.
2242 onDispatchCycleBrokenLocked(currentTime, connection);
2243 }
2244 }
2245}
2246
2247void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2248 while (!queue->isEmpty()) {
2249 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2250 releaseDispatchEntryLocked(dispatchEntry);
2251 }
2252}
2253
2254void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2255 if (dispatchEntry->hasForegroundTarget()) {
2256 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2257 }
2258 delete dispatchEntry;
2259}
2260
2261int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2262 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2263
2264 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002265 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266
2267 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2268 if (connectionIndex < 0) {
2269 ALOGE("Received spurious receive callback for unknown input channel. "
2270 "fd=%d, events=0x%x", fd, events);
2271 return 0; // remove the callback
2272 }
2273
2274 bool notify;
2275 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2276 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2277 if (!(events & ALOOPER_EVENT_INPUT)) {
2278 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002279 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 return 1;
2281 }
2282
2283 nsecs_t currentTime = now();
2284 bool gotOne = false;
2285 status_t status;
2286 for (;;) {
2287 uint32_t seq;
2288 bool handled;
2289 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2290 if (status) {
2291 break;
2292 }
2293 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2294 gotOne = true;
2295 }
2296 if (gotOne) {
2297 d->runCommandsLockedInterruptible();
2298 if (status == WOULD_BLOCK) {
2299 return 1;
2300 }
2301 }
2302
2303 notify = status != DEAD_OBJECT || !connection->monitor;
2304 if (notify) {
2305 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002306 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 }
2308 } else {
2309 // Monitor channels are never explicitly unregistered.
2310 // We do it automatically when the remote endpoint is closed so don't warn
2311 // about them.
2312 notify = !connection->monitor;
2313 if (notify) {
2314 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002315 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 }
2317 }
2318
2319 // Unregister the channel.
2320 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2321 return 0; // remove the callback
2322 } // release lock
2323}
2324
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002325void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked (
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 const CancelationOptions& options) {
2327 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2328 synthesizeCancelationEventsForConnectionLocked(
2329 mConnectionsByFd.valueAt(i), options);
2330 }
2331}
2332
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002333void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked (
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002334 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002335 for (auto& it : mMonitoringChannelsByDisplay) {
2336 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
2337 const size_t numChannels = monitoringChannels.size();
2338 for (size_t i = 0; i < numChannels; i++) {
2339 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2340 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002341 }
2342}
2343
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2345 const sp<InputChannel>& channel, const CancelationOptions& options) {
2346 ssize_t index = getConnectionIndexLocked(channel);
2347 if (index >= 0) {
2348 synthesizeCancelationEventsForConnectionLocked(
2349 mConnectionsByFd.valueAt(index), options);
2350 }
2351}
2352
2353void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2354 const sp<Connection>& connection, const CancelationOptions& options) {
2355 if (connection->status == Connection::STATUS_BROKEN) {
2356 return;
2357 }
2358
2359 nsecs_t currentTime = now();
2360
2361 Vector<EventEntry*> cancelationEvents;
2362 connection->inputState.synthesizeCancelationEvents(currentTime,
2363 cancelationEvents, options);
2364
2365 if (!cancelationEvents.isEmpty()) {
2366#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002367 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002369 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 options.reason, options.mode);
2371#endif
2372 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2373 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2374 switch (cancelationEventEntry->type) {
2375 case EventEntry::TYPE_KEY:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002376 logOutboundKeyDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377 static_cast<KeyEntry*>(cancelationEventEntry));
2378 break;
2379 case EventEntry::TYPE_MOTION:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002380 logOutboundMotionDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381 static_cast<MotionEntry*>(cancelationEventEntry));
2382 break;
2383 }
2384
2385 InputTarget target;
chaviwfbe5d9c2018-12-26 12:23:37 -08002386 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(
2387 connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002388 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2390 target.xOffset = -windowInfo->frameLeft;
2391 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002392 target.globalScaleFactor = windowInfo->globalScaleFactor;
2393 target.windowXScale = windowInfo->windowXScale;
2394 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 } else {
2396 target.xOffset = 0;
2397 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002398 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 }
2400 target.inputChannel = connection->inputChannel;
2401 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2402
2403 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2404 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2405
2406 cancelationEventEntry->release();
2407 }
2408
2409 startDispatchCycleLocked(currentTime, connection);
2410 }
2411}
2412
2413InputDispatcher::MotionEntry*
2414InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2415 ALOG_ASSERT(pointerIds.value != 0);
2416
2417 uint32_t splitPointerIndexMap[MAX_POINTERS];
2418 PointerProperties splitPointerProperties[MAX_POINTERS];
2419 PointerCoords splitPointerCoords[MAX_POINTERS];
2420
2421 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2422 uint32_t splitPointerCount = 0;
2423
2424 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2425 originalPointerIndex++) {
2426 const PointerProperties& pointerProperties =
2427 originalMotionEntry->pointerProperties[originalPointerIndex];
2428 uint32_t pointerId = uint32_t(pointerProperties.id);
2429 if (pointerIds.hasBit(pointerId)) {
2430 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2431 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2432 splitPointerCoords[splitPointerCount].copyFrom(
2433 originalMotionEntry->pointerCoords[originalPointerIndex]);
2434 splitPointerCount += 1;
2435 }
2436 }
2437
2438 if (splitPointerCount != pointerIds.count()) {
2439 // This is bad. We are missing some of the pointers that we expected to deliver.
2440 // Most likely this indicates that we received an ACTION_MOVE events that has
2441 // different pointer ids than we expected based on the previous ACTION_DOWN
2442 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2443 // in this way.
2444 ALOGW("Dropping split motion event because the pointer count is %d but "
2445 "we expected there to be %d pointers. This probably means we received "
2446 "a broken sequence of pointer ids from the input device.",
2447 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002448 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 }
2450
2451 int32_t action = originalMotionEntry->action;
2452 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2453 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2454 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2455 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2456 const PointerProperties& pointerProperties =
2457 originalMotionEntry->pointerProperties[originalPointerIndex];
2458 uint32_t pointerId = uint32_t(pointerProperties.id);
2459 if (pointerIds.hasBit(pointerId)) {
2460 if (pointerIds.count() == 1) {
2461 // The first/last pointer went down/up.
2462 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2463 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2464 } else {
2465 // A secondary pointer went down/up.
2466 uint32_t splitPointerIndex = 0;
2467 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2468 splitPointerIndex += 1;
2469 }
2470 action = maskedAction | (splitPointerIndex
2471 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2472 }
2473 } else {
2474 // An unrelated pointer changed.
2475 action = AMOTION_EVENT_ACTION_MOVE;
2476 }
2477 }
2478
2479 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002480 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481 originalMotionEntry->eventTime,
2482 originalMotionEntry->deviceId,
2483 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002484 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485 originalMotionEntry->policyFlags,
2486 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002487 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 originalMotionEntry->flags,
2489 originalMotionEntry->metaState,
2490 originalMotionEntry->buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002491 originalMotionEntry->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492 originalMotionEntry->edgeFlags,
2493 originalMotionEntry->xPrecision,
2494 originalMotionEntry->yPrecision,
2495 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002496 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497
2498 if (originalMotionEntry->injectionState) {
2499 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2500 splitMotionEntry->injectionState->refCount += 1;
2501 }
2502
2503 return splitMotionEntry;
2504}
2505
2506void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2507#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002508 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509#endif
2510
2511 bool needWake;
2512 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002513 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514
Prabir Pradhan42611e02018-11-27 14:04:02 -08002515 ConfigurationChangedEntry* newEntry =
2516 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517 needWake = enqueueInboundEventLocked(newEntry);
2518 } // release lock
2519
2520 if (needWake) {
2521 mLooper->wake();
2522 }
2523}
2524
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002525/**
2526 * If one of the meta shortcuts is detected, process them here:
2527 * Meta + Backspace -> generate BACK
2528 * Meta + Enter -> generate HOME
2529 * This will potentially overwrite keyCode and metaState.
2530 */
2531void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2532 int32_t& keyCode, int32_t& metaState) {
2533 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2534 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2535 if (keyCode == AKEYCODE_DEL) {
2536 newKeyCode = AKEYCODE_BACK;
2537 } else if (keyCode == AKEYCODE_ENTER) {
2538 newKeyCode = AKEYCODE_HOME;
2539 }
2540 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002541 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002542 struct KeyReplacement replacement = {keyCode, deviceId};
2543 mReplacedKeys.add(replacement, newKeyCode);
2544 keyCode = newKeyCode;
2545 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2546 }
2547 } else if (action == AKEY_EVENT_ACTION_UP) {
2548 // In order to maintain a consistent stream of up and down events, check to see if the key
2549 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2550 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002551 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002552 struct KeyReplacement replacement = {keyCode, deviceId};
2553 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2554 if (index >= 0) {
2555 keyCode = mReplacedKeys.valueAt(index);
2556 mReplacedKeys.removeItemsAt(index);
2557 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2558 }
2559 }
2560}
2561
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2563#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002564 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002565 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002566 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002567 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002569 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570#endif
2571 if (!validateKeyEvent(args->action)) {
2572 return;
2573 }
2574
2575 uint32_t policyFlags = args->policyFlags;
2576 int32_t flags = args->flags;
2577 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002578 // InputDispatcher tracks and generates key repeats on behalf of
2579 // whatever notifies it, so repeatCount should always be set to 0
2580 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2582 policyFlags |= POLICY_FLAG_VIRTUAL;
2583 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 if (policyFlags & POLICY_FLAG_FUNCTION) {
2586 metaState |= AMETA_FUNCTION_ON;
2587 }
2588
2589 policyFlags |= POLICY_FLAG_TRUSTED;
2590
Michael Wright78f24442014-08-06 15:55:28 -07002591 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002592 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002593
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002595 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002596 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 args->downTime, args->eventTime);
2598
Michael Wright2b3c3302018-03-02 17:19:13 +00002599 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002601 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2602 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2603 std::to_string(t.duration().count()).c_str());
2604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002605
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606 bool needWake;
2607 { // acquire lock
2608 mLock.lock();
2609
2610 if (shouldSendKeyToInputFilterLocked(args)) {
2611 mLock.unlock();
2612
2613 policyFlags |= POLICY_FLAG_FILTERED;
2614 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2615 return; // event was consumed by the filter
2616 }
2617
2618 mLock.lock();
2619 }
2620
Prabir Pradhan42611e02018-11-27 14:04:02 -08002621 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002622 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002623 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624 metaState, repeatCount, args->downTime);
2625
2626 needWake = enqueueInboundEventLocked(newEntry);
2627 mLock.unlock();
2628 } // release lock
2629
2630 if (needWake) {
2631 mLooper->wake();
2632 }
2633}
2634
2635bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2636 return mInputFilterEnabled;
2637}
2638
2639void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2640#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002641 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2642 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002643 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002644 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2645 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002646 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002647 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 for (uint32_t i = 0; i < args->pointerCount; i++) {
2649 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2650 "x=%f, y=%f, pressure=%f, size=%f, "
2651 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2652 "orientation=%f",
2653 i, args->pointerProperties[i].id,
2654 args->pointerProperties[i].toolType,
2655 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2656 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2657 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2658 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2659 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2660 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2661 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2662 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2663 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2664 }
2665#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002666 if (!validateMotionEvent(args->action, args->actionButton,
2667 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668 return;
2669 }
2670
2671 uint32_t policyFlags = args->policyFlags;
2672 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002673
2674 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002675 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002676 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2677 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2678 std::to_string(t.duration().count()).c_str());
2679 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680
2681 bool needWake;
2682 { // acquire lock
2683 mLock.lock();
2684
2685 if (shouldSendMotionToInputFilterLocked(args)) {
2686 mLock.unlock();
2687
2688 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002689 event.initialize(args->deviceId, args->source, args->displayId,
2690 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002691 args->flags, args->edgeFlags, args->metaState, args->buttonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002692 args->classification, 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693 args->downTime, args->eventTime,
2694 args->pointerCount, args->pointerProperties, args->pointerCoords);
2695
2696 policyFlags |= POLICY_FLAG_FILTERED;
2697 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2698 return; // event was consumed by the filter
2699 }
2700
2701 mLock.lock();
2702 }
2703
2704 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002705 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002706 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002707 args->action, args->actionButton, args->flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002708 args->metaState, args->buttonState, args->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002710 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711
2712 needWake = enqueueInboundEventLocked(newEntry);
2713 mLock.unlock();
2714 } // release lock
2715
2716 if (needWake) {
2717 mLooper->wake();
2718 }
2719}
2720
2721bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002722 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723}
2724
2725void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2726#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002727 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2728 "switchMask=0x%08x",
2729 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730#endif
2731
2732 uint32_t policyFlags = args->policyFlags;
2733 policyFlags |= POLICY_FLAG_TRUSTED;
2734 mPolicy->notifySwitch(args->eventTime,
2735 args->switchValues, args->switchMask, policyFlags);
2736}
2737
2738void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2739#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002740 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741 args->eventTime, args->deviceId);
2742#endif
2743
2744 bool needWake;
2745 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002746 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747
Prabir Pradhan42611e02018-11-27 14:04:02 -08002748 DeviceResetEntry* newEntry =
2749 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 needWake = enqueueInboundEventLocked(newEntry);
2751 } // release lock
2752
2753 if (needWake) {
2754 mLooper->wake();
2755 }
2756}
2757
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002758int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2760 uint32_t policyFlags) {
2761#if DEBUG_INBOUND_EVENT_DETAILS
2762 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002763 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2764 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765#endif
2766
2767 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2768
2769 policyFlags |= POLICY_FLAG_INJECTED;
2770 if (hasInjectionPermission(injectorPid, injectorUid)) {
2771 policyFlags |= POLICY_FLAG_TRUSTED;
2772 }
2773
2774 EventEntry* firstInjectedEntry;
2775 EventEntry* lastInjectedEntry;
2776 switch (event->getType()) {
2777 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002778 KeyEvent keyEvent;
2779 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2780 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781 if (! validateKeyEvent(action)) {
2782 return INPUT_EVENT_INJECTION_FAILED;
2783 }
2784
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002785 int32_t flags = keyEvent.getFlags();
2786 int32_t keyCode = keyEvent.getKeyCode();
2787 int32_t metaState = keyEvent.getMetaState();
2788 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2789 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002790 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002791 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002792 keyEvent.getDownTime(), keyEvent.getEventTime());
2793
Michael Wrightd02c5b62014-02-10 15:10:22 -08002794 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2795 policyFlags |= POLICY_FLAG_VIRTUAL;
2796 }
2797
2798 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002799 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002800 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002801 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2802 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2803 std::to_string(t.duration().count()).c_str());
2804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 }
2806
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002808 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002809 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002811 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2812 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813 lastInjectedEntry = firstInjectedEntry;
2814 break;
2815 }
2816
2817 case AINPUT_EVENT_TYPE_MOTION: {
2818 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819 int32_t action = motionEvent->getAction();
2820 size_t pointerCount = motionEvent->getPointerCount();
2821 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002822 int32_t actionButton = motionEvent->getActionButton();
Charles Chen3611f1f2019-01-29 17:26:18 +08002823 int32_t displayId = motionEvent->getDisplayId();
Michael Wright7b159c92015-05-14 14:48:03 +01002824 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 return INPUT_EVENT_INJECTION_FAILED;
2826 }
2827
2828 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2829 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002830 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002831 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002832 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2833 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2834 std::to_string(t.duration().count()).c_str());
2835 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836 }
2837
2838 mLock.lock();
2839 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2840 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002841 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002842 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2843 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002844 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002846 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002848 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002849 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2850 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 lastInjectedEntry = firstInjectedEntry;
2852 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2853 sampleEventTimes += 1;
2854 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002855 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2856 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002857 motionEvent->getDeviceId(), motionEvent->getSource(),
2858 motionEvent->getDisplayId(), 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->next = nextInjectedEntry;
2867 lastInjectedEntry = nextInjectedEntry;
2868 }
2869 break;
2870 }
2871
2872 default:
2873 ALOGW("Cannot inject event of type %d", event->getType());
2874 return INPUT_EVENT_INJECTION_FAILED;
2875 }
2876
2877 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2878 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2879 injectionState->injectionIsAsync = true;
2880 }
2881
2882 injectionState->refCount += 1;
2883 lastInjectedEntry->injectionState = injectionState;
2884
2885 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002886 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887 EventEntry* nextEntry = entry->next;
2888 needWake |= enqueueInboundEventLocked(entry);
2889 entry = nextEntry;
2890 }
2891
2892 mLock.unlock();
2893
2894 if (needWake) {
2895 mLooper->wake();
2896 }
2897
2898 int32_t injectionResult;
2899 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002900 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901
2902 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2903 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2904 } else {
2905 for (;;) {
2906 injectionResult = injectionState->injectionResult;
2907 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2908 break;
2909 }
2910
2911 nsecs_t remainingTimeout = endTime - now();
2912 if (remainingTimeout <= 0) {
2913#if DEBUG_INJECTION
2914 ALOGD("injectInputEvent - Timed out waiting for injection result "
2915 "to become available.");
2916#endif
2917 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2918 break;
2919 }
2920
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002921 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922 }
2923
2924 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2925 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2926 while (injectionState->pendingForegroundDispatches != 0) {
2927#if DEBUG_INJECTION
2928 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2929 injectionState->pendingForegroundDispatches);
2930#endif
2931 nsecs_t remainingTimeout = endTime - now();
2932 if (remainingTimeout <= 0) {
2933#if DEBUG_INJECTION
2934 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2935 "dispatches to finish.");
2936#endif
2937 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2938 break;
2939 }
2940
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002941 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942 }
2943 }
2944 }
2945
2946 injectionState->release();
2947 } // release lock
2948
2949#if DEBUG_INJECTION
2950 ALOGD("injectInputEvent - Finished with result %d. "
2951 "injectorPid=%d, injectorUid=%d",
2952 injectionResult, injectorPid, injectorUid);
2953#endif
2954
2955 return injectionResult;
2956}
2957
2958bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2959 return injectorUid == 0
2960 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2961}
2962
2963void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2964 InjectionState* injectionState = entry->injectionState;
2965 if (injectionState) {
2966#if DEBUG_INJECTION
2967 ALOGD("Setting input event injection result to %d. "
2968 "injectorPid=%d, injectorUid=%d",
2969 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2970#endif
2971
2972 if (injectionState->injectionIsAsync
2973 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2974 // Log the outcome since the injector did not wait for the injection result.
2975 switch (injectionResult) {
2976 case INPUT_EVENT_INJECTION_SUCCEEDED:
2977 ALOGV("Asynchronous input event injection succeeded.");
2978 break;
2979 case INPUT_EVENT_INJECTION_FAILED:
2980 ALOGW("Asynchronous input event injection failed.");
2981 break;
2982 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2983 ALOGW("Asynchronous input event injection permission denied.");
2984 break;
2985 case INPUT_EVENT_INJECTION_TIMED_OUT:
2986 ALOGW("Asynchronous input event injection timed out.");
2987 break;
2988 }
2989 }
2990
2991 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002992 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993 }
2994}
2995
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002996void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997 InjectionState* injectionState = entry->injectionState;
2998 if (injectionState) {
2999 injectionState->pendingForegroundDispatches += 1;
3000 }
3001}
3002
3003void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3004 InjectionState* injectionState = entry->injectionState;
3005 if (injectionState) {
3006 injectionState->pendingForegroundDispatches -= 1;
3007
3008 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003009 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003010 }
3011 }
3012}
3013
Arthur Hungb92218b2018-08-14 12:00:21 +08003014Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
3015 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003016 mWindowHandlesByDisplay.find(displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003017 if(it != mWindowHandlesByDisplay.end()) {
3018 return it->second;
3019 }
3020
3021 // Return an empty one if nothing found.
3022 return Vector<sp<InputWindowHandle>>();
3023}
3024
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003026 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003027 for (auto& it : mWindowHandlesByDisplay) {
3028 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3029 size_t numWindows = windowHandles.size();
3030 for (size_t i = 0; i < numWindows; i++) {
3031 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
chaviwfbe5d9c2018-12-26 12:23:37 -08003032 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003033 return windowHandle;
3034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003035 }
3036 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003037 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038}
3039
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003040bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003041 for (auto& it : mWindowHandlesByDisplay) {
3042 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3043 size_t numWindows = windowHandles.size();
3044 for (size_t i = 0; i < numWindows; i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003045 if (windowHandles.itemAt(i)->getToken()
3046 == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003047 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003048 ALOGE("Found window %s in display %" PRId32
3049 ", but it should belong to display %" PRId32,
3050 windowHandle->getName().c_str(), it.first,
3051 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003052 }
3053 return true;
3054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055 }
3056 }
3057 return false;
3058}
3059
Robert Carr5c8a0262018-10-03 16:30:44 -07003060sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3061 size_t count = mInputChannelsByToken.count(token);
3062 if (count == 0) {
3063 return nullptr;
3064 }
3065 return mInputChannelsByToken.at(token);
3066}
3067
Arthur Hungb92218b2018-08-14 12:00:21 +08003068/**
3069 * Called from InputManagerService, update window handle list by displayId that can receive input.
3070 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3071 * If set an empty list, remove all handles from the specific display.
3072 * For focused handle, check if need to change and send a cancel event to previous one.
3073 * For removed handle, check if need to send a cancel event if already in touch.
3074 */
3075void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
chaviw291d88a2019-02-14 10:33:58 -08003076 int32_t displayId, const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003078 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079#endif
3080 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003081 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082
Arthur Hungb92218b2018-08-14 12:00:21 +08003083 // Copy old handles for release if they are no longer present.
3084 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085
Tiger Huang721e26f2018-07-24 22:26:19 +08003086 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003088
3089 if (inputWindowHandles.isEmpty()) {
3090 // Remove all handles on a display if there are no windows left.
3091 mWindowHandlesByDisplay.erase(displayId);
3092 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003093 // Since we compare the pointer of input window handles across window updates, we need
3094 // to make sure the handle object for the same window stays unchanged across updates.
3095 const Vector<sp<InputWindowHandle>>& oldHandles = mWindowHandlesByDisplay[displayId];
3096 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3097 for (size_t i = 0; i < oldHandles.size(); i++) {
3098 const sp<InputWindowHandle>& handle = oldHandles.itemAt(i);
3099 oldHandlesByTokens[handle->getToken()] = handle;
3100 }
3101
3102 const size_t numWindows = inputWindowHandles.size();
3103 Vector<sp<InputWindowHandle>> newHandles;
Arthur Hungb92218b2018-08-14 12:00:21 +08003104 for (size_t i = 0; i < numWindows; i++) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003105 const sp<InputWindowHandle>& handle = inputWindowHandles.itemAt(i);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003106 if (!handle->updateInfo() || (getInputChannelLocked(handle->getToken()) == nullptr
3107 && handle->getInfo()->portalToDisplayId == ADISPLAY_ID_NONE)) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003108 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003109 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003110 continue;
3111 }
3112
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003113 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003114 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003115 handle->getName().c_str(), displayId,
3116 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003117 continue;
3118 }
3119
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003120 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3121 const sp<InputWindowHandle> oldHandle =
3122 oldHandlesByTokens.at(handle->getToken());
3123 oldHandle->updateFrom(handle);
3124 newHandles.push_back(oldHandle);
3125 } else {
3126 newHandles.push_back(handle);
3127 }
3128 }
3129
3130 for (size_t i = 0; i < newHandles.size(); i++) {
3131 const sp<InputWindowHandle>& windowHandle = newHandles.itemAt(i);
Arthur Hung7ab76b12019-01-09 19:17:20 +08003132 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3133 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus
3134 && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003135 newFocusedWindowHandle = windowHandle;
3136 }
3137 if (windowHandle == mLastHoverWindowHandle) {
3138 foundHoveredWindow = true;
3139 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003140 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003141
3142 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003143 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003144 }
3145
3146 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003147 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 }
3149
Tiger Huang721e26f2018-07-24 22:26:19 +08003150 sp<InputWindowHandle> oldFocusedWindowHandle =
3151 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3152
3153 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3154 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003156 ALOGD("Focus left window: %s in display %" PRId32,
3157 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003159 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3160 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003161 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3163 "focus left window");
3164 synthesizeCancelationEventsForInputChannelLocked(
3165 focusedInputChannel, options);
3166 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003167 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003169 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003171 ALOGD("Focus entered window: %s in display %" PRId32,
3172 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003174 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 }
Robert Carrf759f162018-11-13 12:57:11 -08003176
3177 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003178 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003179 }
3180
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
3182
Arthur Hungb92218b2018-08-14 12:00:21 +08003183 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3184 if (stateIndex >= 0) {
3185 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003186 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003187 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003188 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003190 ALOGD("Touched window was removed: %s in display %" PRId32,
3191 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003193 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003194 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003195 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003196 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3197 "touched window was removed");
3198 synthesizeCancelationEventsForInputChannelLocked(
3199 touchedInputChannel, options);
3200 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003201 state.windows.removeAt(i);
3202 } else {
3203 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 }
3206 }
3207
3208 // Release information for windows that are no longer present.
3209 // This ensures that unused input channels are released promptly.
3210 // Otherwise, they might stick around until the window handle is destroyed
3211 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003212 size_t numWindows = oldWindowHandles.size();
3213 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003215 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003217 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003219 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 }
3221 }
3222 } // release lock
3223
3224 // Wake up poll loop since it may need to make new input dispatching choices.
3225 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003226
3227 if (setInputWindowsListener) {
3228 setInputWindowsListener->onSetInputWindowsFinished();
3229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230}
3231
3232void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003233 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003235 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236#endif
3237 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003238 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239
Tiger Huang721e26f2018-07-24 22:26:19 +08003240 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3241 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003242 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003243 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3244 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003246 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003248 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003250 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003252 oldFocusedApplicationHandle->releaseInfo();
3253 oldFocusedApplicationHandle.clear();
3254 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 }
3256
3257#if DEBUG_FOCUS
3258 //logDispatchStateLocked();
3259#endif
3260 } // release lock
3261
3262 // Wake up poll loop since it may need to make new input dispatching choices.
3263 mLooper->wake();
3264}
3265
Tiger Huang721e26f2018-07-24 22:26:19 +08003266/**
3267 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3268 * the display not specified.
3269 *
3270 * We track any unreleased events for each window. If a window loses the ability to receive the
3271 * released event, we will send a cancel event to it. So when the focused display is changed, we
3272 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3273 * display. The display-specified events won't be affected.
3274 */
3275void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3276#if DEBUG_FOCUS
3277 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3278#endif
3279 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003280 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003281
3282 if (mFocusedDisplayId != displayId) {
3283 sp<InputWindowHandle> oldFocusedWindowHandle =
3284 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3285 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003286 sp<InputChannel> inputChannel =
3287 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003288 if (inputChannel != nullptr) {
3289 CancelationOptions options(
3290 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3291 "The display which contains this window no longer has focus.");
3292 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3293 }
3294 }
3295 mFocusedDisplayId = displayId;
3296
3297 // Sanity check
3298 sp<InputWindowHandle> newFocusedWindowHandle =
3299 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003300 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003301
Tiger Huang721e26f2018-07-24 22:26:19 +08003302 if (newFocusedWindowHandle == nullptr) {
3303 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3304 if (!mFocusedWindowHandlesByDisplay.empty()) {
3305 ALOGE("But another display has a focused window:");
3306 for (auto& it : mFocusedWindowHandlesByDisplay) {
3307 const int32_t displayId = it.first;
3308 const sp<InputWindowHandle>& windowHandle = it.second;
3309 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3310 displayId, windowHandle->getName().c_str());
3311 }
3312 }
3313 }
3314 }
3315
3316#if DEBUG_FOCUS
3317 logDispatchStateLocked();
3318#endif
3319 } // release lock
3320
3321 // Wake up poll loop since it may need to make new input dispatching choices.
3322 mLooper->wake();
3323}
3324
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3326#if DEBUG_FOCUS
3327 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3328#endif
3329
3330 bool changed;
3331 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003332 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333
3334 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3335 if (mDispatchFrozen && !frozen) {
3336 resetANRTimeoutsLocked();
3337 }
3338
3339 if (mDispatchEnabled && !enabled) {
3340 resetAndDropEverythingLocked("dispatcher is being disabled");
3341 }
3342
3343 mDispatchEnabled = enabled;
3344 mDispatchFrozen = frozen;
3345 changed = true;
3346 } else {
3347 changed = false;
3348 }
3349
3350#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003351 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352#endif
3353 } // release lock
3354
3355 if (changed) {
3356 // Wake up poll loop since it may need to make new input dispatching choices.
3357 mLooper->wake();
3358 }
3359}
3360
3361void InputDispatcher::setInputFilterEnabled(bool enabled) {
3362#if DEBUG_FOCUS
3363 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3364#endif
3365
3366 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003367 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368
3369 if (mInputFilterEnabled == enabled) {
3370 return;
3371 }
3372
3373 mInputFilterEnabled = enabled;
3374 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3375 } // release lock
3376
3377 // Wake up poll loop since there might be work to do to drop everything.
3378 mLooper->wake();
3379}
3380
chaviwfbe5d9c2018-12-26 12:23:37 -08003381bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3382 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003384 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003386 return true;
3387 }
3388
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003390 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391
chaviwfbe5d9c2018-12-26 12:23:37 -08003392 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3393 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003394 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003395 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 return false;
3397 }
chaviw4f2dd402018-12-26 15:30:27 -08003398#if DEBUG_FOCUS
3399 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3400 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3401#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3403#if DEBUG_FOCUS
3404 ALOGD("Cannot transfer focus because windows are on different displays.");
3405#endif
3406 return false;
3407 }
3408
3409 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003410 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3411 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3412 for (size_t i = 0; i < state.windows.size(); i++) {
3413 const TouchedWindow& touchedWindow = state.windows[i];
3414 if (touchedWindow.windowHandle == fromWindowHandle) {
3415 int32_t oldTargetFlags = touchedWindow.targetFlags;
3416 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417
Jeff Brownf086ddb2014-02-11 14:28:48 -08003418 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419
Jeff Brownf086ddb2014-02-11 14:28:48 -08003420 int32_t newTargetFlags = oldTargetFlags
3421 & (InputTarget::FLAG_FOREGROUND
3422 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3423 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424
Jeff Brownf086ddb2014-02-11 14:28:48 -08003425 found = true;
3426 goto Found;
3427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428 }
3429 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003430Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431
3432 if (! found) {
3433#if DEBUG_FOCUS
3434 ALOGD("Focus transfer failed because from window did not have focus.");
3435#endif
3436 return false;
3437 }
3438
chaviwfbe5d9c2018-12-26 12:23:37 -08003439
3440 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3441 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3443 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3444 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3445 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3446 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3447
3448 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3449 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3450 "transferring touch focus from this window to another window");
3451 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3452 }
3453
3454#if DEBUG_FOCUS
3455 logDispatchStateLocked();
3456#endif
3457 } // release lock
3458
3459 // Wake up poll loop since it may need to make new input dispatching choices.
3460 mLooper->wake();
3461 return true;
3462}
3463
3464void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3465#if DEBUG_FOCUS
3466 ALOGD("Resetting and dropping all events (%s).", reason);
3467#endif
3468
3469 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3470 synthesizeCancelationEventsForAllConnectionsLocked(options);
3471
3472 resetKeyRepeatLocked();
3473 releasePendingEventLocked();
3474 drainInboundQueueLocked();
3475 resetANRTimeoutsLocked();
3476
Jeff Brownf086ddb2014-02-11 14:28:48 -08003477 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003479 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480}
3481
3482void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003483 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484 dumpDispatchStateLocked(dump);
3485
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003486 std::istringstream stream(dump);
3487 std::string line;
3488
3489 while (std::getline(stream, line, '\n')) {
3490 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491 }
3492}
3493
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003494void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3495 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3496 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003497 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498
Tiger Huang721e26f2018-07-24 22:26:19 +08003499 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3500 dump += StringPrintf(INDENT "FocusedApplications:\n");
3501 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3502 const int32_t displayId = it.first;
3503 const sp<InputApplicationHandle>& applicationHandle = it.second;
3504 dump += StringPrintf(
3505 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3506 displayId,
3507 applicationHandle->getName().c_str(),
3508 applicationHandle->getDispatchingTimeout(
3509 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003512 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003514
3515 if (!mFocusedWindowHandlesByDisplay.empty()) {
3516 dump += StringPrintf(INDENT "FocusedWindows:\n");
3517 for (auto& it : mFocusedWindowHandlesByDisplay) {
3518 const int32_t displayId = it.first;
3519 const sp<InputWindowHandle>& windowHandle = it.second;
3520 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3521 displayId, windowHandle->getName().c_str());
3522 }
3523 } else {
3524 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526
Jeff Brownf086ddb2014-02-11 14:28:48 -08003527 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003528 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003529 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3530 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003531 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003532 state.displayId, toString(state.down), toString(state.split),
3533 state.deviceId, state.source);
3534 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003535 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003536 for (size_t i = 0; i < state.windows.size(); i++) {
3537 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003538 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3539 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003540 touchedWindow.pointerIds.value,
3541 touchedWindow.targetFlags);
3542 }
3543 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003544 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003545 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003546 if (!state.portalWindows.isEmpty()) {
3547 dump += INDENT3 "Portal windows:\n";
3548 for (size_t i = 0; i < state.portalWindows.size(); i++) {
3549 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows.itemAt(i);
3550 dump += StringPrintf(INDENT4 "%zu: name='%s'\n",
3551 i, portalWindowHandle->getName().c_str());
3552 }
3553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554 }
3555 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003556 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 }
3558
Arthur Hungb92218b2018-08-14 12:00:21 +08003559 if (!mWindowHandlesByDisplay.empty()) {
3560 for (auto& it : mWindowHandlesByDisplay) {
3561 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003562 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003563 if (!windowHandles.isEmpty()) {
3564 dump += INDENT2 "Windows:\n";
3565 for (size_t i = 0; i < windowHandles.size(); i++) {
3566 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3567 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003568
Arthur Hungb92218b2018-08-14 12:00:21 +08003569 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003570 "portalToDisplayId=%d, paused=%s, hasFocus=%s, hasWallpaper=%s, "
Arthur Hungb92218b2018-08-14 12:00:21 +08003571 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003572 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003573 "touchableRegion=",
3574 i, windowInfo->name.c_str(), windowInfo->displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003575 windowInfo->portalToDisplayId,
Arthur Hungb92218b2018-08-14 12:00:21 +08003576 toString(windowInfo->paused),
3577 toString(windowInfo->hasFocus),
3578 toString(windowInfo->hasWallpaper),
3579 toString(windowInfo->visible),
3580 toString(windowInfo->canReceiveKeys),
3581 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3582 windowInfo->layer,
3583 windowInfo->frameLeft, windowInfo->frameTop,
3584 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003585 windowInfo->globalScaleFactor,
3586 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003587 dumpRegion(dump, windowInfo->touchableRegion);
3588 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3589 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3590 windowInfo->ownerPid, windowInfo->ownerUid,
3591 windowInfo->dispatchingTimeout / 1000000.0);
3592 }
3593 } else {
3594 dump += INDENT2 "Windows: <none>\n";
3595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 }
3597 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003598 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 }
3600
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003601 if (!mMonitoringChannelsByDisplay.empty()) {
3602 for (auto& it : mMonitoringChannelsByDisplay) {
3603 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003604 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003605 const size_t numChannels = monitoringChannels.size();
3606 for (size_t i = 0; i < numChannels; i++) {
3607 const sp<InputChannel>& channel = monitoringChannels[i];
3608 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3609 }
3610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003612 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 }
3614
3615 nsecs_t currentTime = now();
3616
3617 // Dump recently dispatched or dropped events from oldest to newest.
3618 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003619 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003621 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003623 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 (currentTime - entry->eventTime) * 0.000001f);
3625 }
3626 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003627 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628 }
3629
3630 // Dump event currently being dispatched.
3631 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003632 dump += INDENT "PendingEvent:\n";
3633 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003635 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3637 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003638 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 }
3640
3641 // Dump inbound events from oldest to newest.
3642 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003643 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003645 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003647 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 (currentTime - entry->eventTime) * 0.000001f);
3649 }
3650 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003651 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 }
3653
Michael Wright78f24442014-08-06 15:55:28 -07003654 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003655 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003656 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3657 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3658 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003659 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003660 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3661 }
3662 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003663 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003664 }
3665
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003667 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3669 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003670 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003671 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003672 i, connection->getInputChannelName().c_str(),
3673 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 connection->getStatusLabel(), toString(connection->monitor),
3675 toString(connection->inputPublisherBlocked));
3676
3677 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003678 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679 connection->outboundQueue.count());
3680 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3681 entry = entry->next) {
3682 dump.append(INDENT4);
3683 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003684 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 entry->targetFlags, entry->resolvedAction,
3686 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3687 }
3688 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003689 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 }
3691
3692 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003693 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 connection->waitQueue.count());
3695 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3696 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003697 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003699 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 "age=%0.1fms, wait=%0.1fms\n",
3701 entry->targetFlags, entry->resolvedAction,
3702 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3703 (currentTime - entry->deliveryTime) * 0.000001f);
3704 }
3705 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003706 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 }
3708 }
3709 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003710 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 }
3712
3713 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003714 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 (mAppSwitchDueTime - now()) / 1000000.0);
3716 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003717 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 }
3719
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003720 dump += INDENT "Configuration:\n";
3721 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003723 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 mConfig.keyRepeatTimeout * 0.000001f);
3725}
3726
Robert Carr803535b2018-08-02 16:38:15 -07003727status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003729 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3730 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731#endif
3732
3733 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003734 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735
Robert Carr4e670e52018-08-15 13:26:12 -07003736 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3737 // treat inputChannel as monitor channel for displayId.
3738 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3739 if (monitor) {
3740 inputChannel->setToken(new BBinder());
3741 }
3742
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 if (getConnectionIndexLocked(inputChannel) >= 0) {
3744 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003745 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 return BAD_VALUE;
3747 }
3748
Robert Carr803535b2018-08-02 16:38:15 -07003749 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750
3751 int fd = inputChannel->getFd();
3752 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003753 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003755 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003757 Vector<sp<InputChannel>>& monitoringChannels =
3758 mMonitoringChannelsByDisplay[displayId];
3759 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 }
3761
3762 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3763 } // release lock
3764
3765 // Wake the looper because some connections have changed.
3766 mLooper->wake();
3767 return OK;
3768}
3769
3770status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3771#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003772 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773#endif
3774
3775 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003776 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777
3778 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3779 if (status) {
3780 return status;
3781 }
3782 } // release lock
3783
3784 // Wake the poll loop because removing the connection may have changed the current
3785 // synchronization state.
3786 mLooper->wake();
3787 return OK;
3788}
3789
3790status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3791 bool notify) {
3792 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3793 if (connectionIndex < 0) {
3794 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003795 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 return BAD_VALUE;
3797 }
3798
3799 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3800 mConnectionsByFd.removeItemsAt(connectionIndex);
3801
Robert Carr5c8a0262018-10-03 16:30:44 -07003802 mInputChannelsByToken.erase(inputChannel->getToken());
3803
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 if (connection->monitor) {
3805 removeMonitorChannelLocked(inputChannel);
3806 }
3807
3808 mLooper->removeFd(inputChannel->getFd());
3809
3810 nsecs_t currentTime = now();
3811 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3812
3813 connection->status = Connection::STATUS_ZOMBIE;
3814 return OK;
3815}
3816
3817void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003818 for (auto it = mMonitoringChannelsByDisplay.begin();
3819 it != mMonitoringChannelsByDisplay.end(); ) {
3820 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3821 const size_t numChannels = monitoringChannels.size();
3822 for (size_t i = 0; i < numChannels; i++) {
3823 if (monitoringChannels[i] == inputChannel) {
3824 monitoringChannels.removeAt(i);
3825 break;
3826 }
3827 }
3828 if (monitoringChannels.empty()) {
3829 it = mMonitoringChannelsByDisplay.erase(it);
3830 } else {
3831 ++it;
3832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 }
3834}
3835
3836ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003837 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003838 return -1;
3839 }
3840
Robert Carr4e670e52018-08-15 13:26:12 -07003841 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3842 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3843 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3844 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003845 }
3846 }
Robert Carr4e670e52018-08-15 13:26:12 -07003847
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 return -1;
3849}
3850
3851void InputDispatcher::onDispatchCycleFinishedLocked(
3852 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3853 CommandEntry* commandEntry = postCommandLocked(
3854 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3855 commandEntry->connection = connection;
3856 commandEntry->eventTime = currentTime;
3857 commandEntry->seq = seq;
3858 commandEntry->handled = handled;
3859}
3860
3861void InputDispatcher::onDispatchCycleBrokenLocked(
3862 nsecs_t currentTime, const sp<Connection>& connection) {
3863 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003864 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865
3866 CommandEntry* commandEntry = postCommandLocked(
3867 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3868 commandEntry->connection = connection;
3869}
3870
chaviw0c06c6e2019-01-09 13:27:07 -08003871void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
3872 const sp<InputWindowHandle>& newFocus) {
3873 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
3874 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08003875 CommandEntry* commandEntry = postCommandLocked(
3876 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08003877 commandEntry->oldToken = oldToken;
3878 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003879}
3880
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881void InputDispatcher::onANRLocked(
3882 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3883 const sp<InputWindowHandle>& windowHandle,
3884 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3885 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3886 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3887 ALOGI("Application is not responding: %s. "
3888 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003889 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890 dispatchLatency, waitDuration, reason);
3891
3892 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003893 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894 struct tm tm;
3895 localtime_r(&t, &tm);
3896 char timestr[64];
3897 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3898 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003899 mLastANRState += INDENT "ANR:\n";
3900 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3901 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003902 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003903 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3904 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3905 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906 dumpDispatchStateLocked(mLastANRState);
3907
3908 CommandEntry* commandEntry = postCommandLocked(
3909 & InputDispatcher::doNotifyANRLockedInterruptible);
3910 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003911 commandEntry->inputChannel = windowHandle != nullptr ?
3912 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913 commandEntry->reason = reason;
3914}
3915
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003916void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible (
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 CommandEntry* commandEntry) {
3918 mLock.unlock();
3919
3920 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3921
3922 mLock.lock();
3923}
3924
3925void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3926 CommandEntry* commandEntry) {
3927 sp<Connection> connection = commandEntry->connection;
3928
3929 if (connection->status != Connection::STATUS_ZOMBIE) {
3930 mLock.unlock();
3931
Robert Carr803535b2018-08-02 16:38:15 -07003932 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933
3934 mLock.lock();
3935 }
3936}
3937
Robert Carrf759f162018-11-13 12:57:11 -08003938void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3939 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08003940 sp<IBinder> oldToken = commandEntry->oldToken;
3941 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003942 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08003943 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08003944 mLock.lock();
3945}
3946
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947void InputDispatcher::doNotifyANRLockedInterruptible(
3948 CommandEntry* commandEntry) {
3949 mLock.unlock();
3950
3951 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003952 commandEntry->inputApplicationHandle,
3953 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 commandEntry->reason);
3955
3956 mLock.lock();
3957
3958 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003959 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960}
3961
3962void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3963 CommandEntry* commandEntry) {
3964 KeyEntry* entry = commandEntry->keyEntry;
3965
3966 KeyEvent event;
3967 initializeKeyEvent(&event, entry);
3968
3969 mLock.unlock();
3970
Michael Wright2b3c3302018-03-02 17:19:13 +00003971 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003972 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3973 commandEntry->inputChannel->getToken() : nullptr;
3974 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003976 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3977 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3978 std::to_string(t.duration().count()).c_str());
3979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980
3981 mLock.lock();
3982
3983 if (delay < 0) {
3984 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3985 } else if (!delay) {
3986 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3987 } else {
3988 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3989 entry->interceptKeyWakeupTime = now() + delay;
3990 }
3991 entry->release();
3992}
3993
3994void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3995 CommandEntry* commandEntry) {
3996 sp<Connection> connection = commandEntry->connection;
3997 nsecs_t finishTime = commandEntry->eventTime;
3998 uint32_t seq = commandEntry->seq;
3999 bool handled = commandEntry->handled;
4000
4001 // Handle post-event policy actions.
4002 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
4003 if (dispatchEntry) {
4004 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4005 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004006 std::string msg =
4007 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004008 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004010 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 }
4012
4013 bool restartEvent;
4014 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4015 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4016 restartEvent = afterKeyEventLockedInterruptible(connection,
4017 dispatchEntry, keyEntry, handled);
4018 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4019 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4020 restartEvent = afterMotionEventLockedInterruptible(connection,
4021 dispatchEntry, motionEntry, handled);
4022 } else {
4023 restartEvent = false;
4024 }
4025
4026 // Dequeue the event and start the next cycle.
4027 // Note that because the lock might have been released, it is possible that the
4028 // contents of the wait queue to have been drained, so we need to double-check
4029 // a few things.
4030 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4031 connection->waitQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004032 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4034 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004035 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036 } else {
4037 releaseDispatchEntryLocked(dispatchEntry);
4038 }
4039 }
4040
4041 // Start the next dispatch cycle for this connection.
4042 startDispatchCycleLocked(now(), connection);
4043 }
4044}
4045
4046bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4047 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004048 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004049 if (!handled) {
4050 // Report the key as unhandled, since the fallback was not handled.
4051 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4052 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004053 return false;
4054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004056 // Get the fallback key state.
4057 // Clear it out after dispatching the UP.
4058 int32_t originalKeyCode = keyEntry->keyCode;
4059 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4060 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4061 connection->inputState.removeFallbackKey(originalKeyCode);
4062 }
4063
4064 if (handled || !dispatchEntry->hasForegroundTarget()) {
4065 // If the application handles the original key for which we previously
4066 // generated a fallback or if the window is not a foreground window,
4067 // then cancel the associated fallback key, if any.
4068 if (fallbackKeyCode != -1) {
4069 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004071 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4073 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4074 keyEntry->policyFlags);
4075#endif
4076 KeyEvent event;
4077 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004078 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079
4080 mLock.unlock();
4081
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004082 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4083 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084
4085 mLock.lock();
4086
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004087 // Cancel the fallback key.
4088 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004090 "application handled the original non-fallback key "
4091 "or is no longer a foreground target, "
4092 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 options.keyCode = fallbackKeyCode;
4094 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004096 connection->inputState.removeFallbackKey(originalKeyCode);
4097 }
4098 } else {
4099 // If the application did not handle a non-fallback key, first check
4100 // that we are in a good state to perform unhandled key event processing
4101 // Then ask the policy what to do with it.
4102 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4103 && keyEntry->repeatCount == 0;
4104 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004106 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4107 "since this is not an initial down. "
4108 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4109 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4110 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004112 return false;
4113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004115 // Dispatch the unhandled key to the policy.
4116#if DEBUG_OUTBOUND_EVENT_DETAILS
4117 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4118 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4119 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4120 keyEntry->policyFlags);
4121#endif
4122 KeyEvent event;
4123 initializeKeyEvent(&event, keyEntry);
4124
4125 mLock.unlock();
4126
4127 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4128 &event, keyEntry->policyFlags, &event);
4129
4130 mLock.lock();
4131
4132 if (connection->status != Connection::STATUS_NORMAL) {
4133 connection->inputState.removeFallbackKey(originalKeyCode);
4134 return false;
4135 }
4136
4137 // Latch the fallback keycode for this key on an initial down.
4138 // The fallback keycode cannot change at any other point in the lifecycle.
4139 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004141 fallbackKeyCode = event.getKeyCode();
4142 } else {
4143 fallbackKeyCode = AKEYCODE_UNKNOWN;
4144 }
4145 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4146 }
4147
4148 ALOG_ASSERT(fallbackKeyCode != -1);
4149
4150 // Cancel the fallback key if the policy decides not to send it anymore.
4151 // We will continue to dispatch the key to the policy but we will no
4152 // longer dispatch a fallback key to the application.
4153 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4154 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4155#if DEBUG_OUTBOUND_EVENT_DETAILS
4156 if (fallback) {
4157 ALOGD("Unhandled key event: Policy requested to send key %d"
4158 "as a fallback for %d, but on the DOWN it had requested "
4159 "to send %d instead. Fallback canceled.",
4160 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4161 } else {
4162 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4163 "but on the DOWN it had requested to send %d. "
4164 "Fallback canceled.",
4165 originalKeyCode, fallbackKeyCode);
4166 }
4167#endif
4168
4169 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4170 "canceling fallback, policy no longer desires it");
4171 options.keyCode = fallbackKeyCode;
4172 synthesizeCancelationEventsForConnectionLocked(connection, options);
4173
4174 fallback = false;
4175 fallbackKeyCode = AKEYCODE_UNKNOWN;
4176 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4177 connection->inputState.setFallbackKey(originalKeyCode,
4178 fallbackKeyCode);
4179 }
4180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181
4182#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004183 {
4184 std::string msg;
4185 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4186 connection->inputState.getFallbackKeys();
4187 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4188 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4189 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004191 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4192 fallbackKeys.size(), msg.c_str());
4193 }
4194#endif
4195
4196 if (fallback) {
4197 // Restart the dispatch cycle using the fallback key.
4198 keyEntry->eventTime = event.getEventTime();
4199 keyEntry->deviceId = event.getDeviceId();
4200 keyEntry->source = event.getSource();
4201 keyEntry->displayId = event.getDisplayId();
4202 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4203 keyEntry->keyCode = fallbackKeyCode;
4204 keyEntry->scanCode = event.getScanCode();
4205 keyEntry->metaState = event.getMetaState();
4206 keyEntry->repeatCount = event.getRepeatCount();
4207 keyEntry->downTime = event.getDownTime();
4208 keyEntry->syntheticRepeat = false;
4209
4210#if DEBUG_OUTBOUND_EVENT_DETAILS
4211 ALOGD("Unhandled key event: Dispatching fallback key. "
4212 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4213 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4214#endif
4215 return true; // restart the event
4216 } else {
4217#if DEBUG_OUTBOUND_EVENT_DETAILS
4218 ALOGD("Unhandled key event: No fallback key.");
4219#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004220
4221 // Report the key as unhandled, since there is no fallback key.
4222 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 }
4224 }
4225 return false;
4226}
4227
4228bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4229 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4230 return false;
4231}
4232
4233void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4234 mLock.unlock();
4235
4236 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4237
4238 mLock.lock();
4239}
4240
4241void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004242 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4244 entry->downTime, entry->eventTime);
4245}
4246
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004247void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4249 // TODO Write some statistics about how long we spend waiting.
4250}
4251
4252void InputDispatcher::traceInboundQueueLengthLocked() {
4253 if (ATRACE_ENABLED()) {
4254 ATRACE_INT("iq", mInboundQueue.count());
4255 }
4256}
4257
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004258void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259 if (ATRACE_ENABLED()) {
4260 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004261 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 ATRACE_INT(counterName, connection->outboundQueue.count());
4263 }
4264}
4265
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004266void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 if (ATRACE_ENABLED()) {
4268 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004269 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 ATRACE_INT(counterName, connection->waitQueue.count());
4271 }
4272}
4273
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004274void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004275 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004277 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 dumpDispatchStateLocked(dump);
4279
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004280 if (!mLastANRState.empty()) {
4281 dump += "\nInput Dispatcher State at time of last ANR:\n";
4282 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 }
4284}
4285
4286void InputDispatcher::monitor() {
4287 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004288 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004290 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291}
4292
4293
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294// --- InputDispatcher::InjectionState ---
4295
4296InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4297 refCount(1),
4298 injectorPid(injectorPid), injectorUid(injectorUid),
4299 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4300 pendingForegroundDispatches(0) {
4301}
4302
4303InputDispatcher::InjectionState::~InjectionState() {
4304}
4305
4306void InputDispatcher::InjectionState::release() {
4307 refCount -= 1;
4308 if (refCount == 0) {
4309 delete this;
4310 } else {
4311 ALOG_ASSERT(refCount > 0);
4312 }
4313}
4314
4315
4316// --- InputDispatcher::EventEntry ---
4317
Prabir Pradhan42611e02018-11-27 14:04:02 -08004318InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4319 nsecs_t eventTime, uint32_t policyFlags) :
4320 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4321 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322}
4323
4324InputDispatcher::EventEntry::~EventEntry() {
4325 releaseInjectionState();
4326}
4327
4328void InputDispatcher::EventEntry::release() {
4329 refCount -= 1;
4330 if (refCount == 0) {
4331 delete this;
4332 } else {
4333 ALOG_ASSERT(refCount > 0);
4334 }
4335}
4336
4337void InputDispatcher::EventEntry::releaseInjectionState() {
4338 if (injectionState) {
4339 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004340 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 }
4342}
4343
4344
4345// --- InputDispatcher::ConfigurationChangedEntry ---
4346
Prabir Pradhan42611e02018-11-27 14:04:02 -08004347InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4348 uint32_t sequenceNum, nsecs_t eventTime) :
4349 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350}
4351
4352InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4353}
4354
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004355void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4356 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357}
4358
4359
4360// --- InputDispatcher::DeviceResetEntry ---
4361
Prabir Pradhan42611e02018-11-27 14:04:02 -08004362InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4363 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4364 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 deviceId(deviceId) {
4366}
4367
4368InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4369}
4370
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004371void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4372 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 deviceId, policyFlags);
4374}
4375
4376
4377// --- InputDispatcher::KeyEntry ---
4378
Prabir Pradhan42611e02018-11-27 14:04:02 -08004379InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004380 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4382 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004383 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004384 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4386 repeatCount(repeatCount), downTime(downTime),
4387 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4388 interceptKeyWakeupTime(0) {
4389}
4390
4391InputDispatcher::KeyEntry::~KeyEntry() {
4392}
4393
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004394void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004395 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4397 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004398 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004399 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400}
4401
4402void InputDispatcher::KeyEntry::recycle() {
4403 releaseInjectionState();
4404
4405 dispatchInProgress = false;
4406 syntheticRepeat = false;
4407 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4408 interceptKeyWakeupTime = 0;
4409}
4410
4411
4412// --- InputDispatcher::MotionEntry ---
4413
Prabir Pradhan42611e02018-11-27 14:04:02 -08004414InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004415 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4416 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004417 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4418 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004419 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004420 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4421 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004422 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004424 deviceId(deviceId), source(source), displayId(displayId), action(action),
4425 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004426 classification(classification), edgeFlags(edgeFlags),
4427 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004428 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 for (uint32_t i = 0; i < pointerCount; i++) {
4430 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4431 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004432 if (xOffset || yOffset) {
4433 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435 }
4436}
4437
4438InputDispatcher::MotionEntry::~MotionEntry() {
4439}
4440
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004441void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004442 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004443 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004444 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004445 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004446 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4447 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004448
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 for (uint32_t i = 0; i < pointerCount; i++) {
4450 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004451 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004453 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 pointerCoords[i].getX(), pointerCoords[i].getY());
4455 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004456 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457}
4458
4459
4460// --- InputDispatcher::DispatchEntry ---
4461
4462volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4463
4464InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004465 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4466 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467 seq(nextSeq()),
4468 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004469 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4470 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4472 eventEntry->refCount += 1;
4473}
4474
4475InputDispatcher::DispatchEntry::~DispatchEntry() {
4476 eventEntry->release();
4477}
4478
4479uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4480 // Sequence number 0 is reserved and will never be returned.
4481 uint32_t seq;
4482 do {
4483 seq = android_atomic_inc(&sNextSeqAtomic);
4484 } while (!seq);
4485 return seq;
4486}
4487
4488
4489// --- InputDispatcher::InputState ---
4490
4491InputDispatcher::InputState::InputState() {
4492}
4493
4494InputDispatcher::InputState::~InputState() {
4495}
4496
4497bool InputDispatcher::InputState::isNeutral() const {
4498 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4499}
4500
4501bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4502 int32_t displayId) const {
4503 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4504 const MotionMemento& memento = mMotionMementos.itemAt(i);
4505 if (memento.deviceId == deviceId
4506 && memento.source == source
4507 && memento.displayId == displayId
4508 && memento.hovering) {
4509 return true;
4510 }
4511 }
4512 return false;
4513}
4514
4515bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4516 int32_t action, int32_t flags) {
4517 switch (action) {
4518 case AKEY_EVENT_ACTION_UP: {
4519 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4520 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4521 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4522 mFallbackKeys.removeItemsAt(i);
4523 } else {
4524 i += 1;
4525 }
4526 }
4527 }
4528 ssize_t index = findKeyMemento(entry);
4529 if (index >= 0) {
4530 mKeyMementos.removeAt(index);
4531 return true;
4532 }
4533 /* FIXME: We can't just drop the key up event because that prevents creating
4534 * popup windows that are automatically shown when a key is held and then
4535 * dismissed when the key is released. The problem is that the popup will
4536 * not have received the original key down, so the key up will be considered
4537 * to be inconsistent with its observed state. We could perhaps handle this
4538 * by synthesizing a key down but that will cause other problems.
4539 *
4540 * So for now, allow inconsistent key up events to be dispatched.
4541 *
4542#if DEBUG_OUTBOUND_EVENT_DETAILS
4543 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4544 "keyCode=%d, scanCode=%d",
4545 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4546#endif
4547 return false;
4548 */
4549 return true;
4550 }
4551
4552 case AKEY_EVENT_ACTION_DOWN: {
4553 ssize_t index = findKeyMemento(entry);
4554 if (index >= 0) {
4555 mKeyMementos.removeAt(index);
4556 }
4557 addKeyMemento(entry, flags);
4558 return true;
4559 }
4560
4561 default:
4562 return true;
4563 }
4564}
4565
4566bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4567 int32_t action, int32_t flags) {
4568 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4569 switch (actionMasked) {
4570 case AMOTION_EVENT_ACTION_UP:
4571 case AMOTION_EVENT_ACTION_CANCEL: {
4572 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4573 if (index >= 0) {
4574 mMotionMementos.removeAt(index);
4575 return true;
4576 }
4577#if DEBUG_OUTBOUND_EVENT_DETAILS
4578 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004579 "displayId=%" PRId32 ", actionMasked=%d",
4580 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581#endif
4582 return false;
4583 }
4584
4585 case AMOTION_EVENT_ACTION_DOWN: {
4586 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4587 if (index >= 0) {
4588 mMotionMementos.removeAt(index);
4589 }
4590 addMotionMemento(entry, flags, false /*hovering*/);
4591 return true;
4592 }
4593
4594 case AMOTION_EVENT_ACTION_POINTER_UP:
4595 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4596 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004597 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4598 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4599 // generate cancellation events for these since they're based in relative rather than
4600 // absolute units.
4601 return true;
4602 }
4603
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004605
4606 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4607 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4608 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4609 // other value and we need to track the motion so we can send cancellation events for
4610 // anything generating fallback events (e.g. DPad keys for joystick movements).
4611 if (index >= 0) {
4612 if (entry->pointerCoords[0].isEmpty()) {
4613 mMotionMementos.removeAt(index);
4614 } else {
4615 MotionMemento& memento = mMotionMementos.editItemAt(index);
4616 memento.setPointers(entry);
4617 }
4618 } else if (!entry->pointerCoords[0].isEmpty()) {
4619 addMotionMemento(entry, flags, false /*hovering*/);
4620 }
4621
4622 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4623 return true;
4624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 if (index >= 0) {
4626 MotionMemento& memento = mMotionMementos.editItemAt(index);
4627 memento.setPointers(entry);
4628 return true;
4629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630#if DEBUG_OUTBOUND_EVENT_DETAILS
4631 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004632 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4633 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634#endif
4635 return false;
4636 }
4637
4638 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4639 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4640 if (index >= 0) {
4641 mMotionMementos.removeAt(index);
4642 return true;
4643 }
4644#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004645 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4646 "displayId=%" PRId32,
4647 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004648#endif
4649 return false;
4650 }
4651
4652 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4653 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4654 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4655 if (index >= 0) {
4656 mMotionMementos.removeAt(index);
4657 }
4658 addMotionMemento(entry, flags, true /*hovering*/);
4659 return true;
4660 }
4661
4662 default:
4663 return true;
4664 }
4665}
4666
4667ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4668 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4669 const KeyMemento& memento = mKeyMementos.itemAt(i);
4670 if (memento.deviceId == entry->deviceId
4671 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004672 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673 && memento.keyCode == entry->keyCode
4674 && memento.scanCode == entry->scanCode) {
4675 return i;
4676 }
4677 }
4678 return -1;
4679}
4680
4681ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4682 bool hovering) const {
4683 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4684 const MotionMemento& memento = mMotionMementos.itemAt(i);
4685 if (memento.deviceId == entry->deviceId
4686 && memento.source == entry->source
4687 && memento.displayId == entry->displayId
4688 && memento.hovering == hovering) {
4689 return i;
4690 }
4691 }
4692 return -1;
4693}
4694
4695void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4696 mKeyMementos.push();
4697 KeyMemento& memento = mKeyMementos.editTop();
4698 memento.deviceId = entry->deviceId;
4699 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004700 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701 memento.keyCode = entry->keyCode;
4702 memento.scanCode = entry->scanCode;
4703 memento.metaState = entry->metaState;
4704 memento.flags = flags;
4705 memento.downTime = entry->downTime;
4706 memento.policyFlags = entry->policyFlags;
4707}
4708
4709void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4710 int32_t flags, bool hovering) {
4711 mMotionMementos.push();
4712 MotionMemento& memento = mMotionMementos.editTop();
4713 memento.deviceId = entry->deviceId;
4714 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004715 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716 memento.flags = flags;
4717 memento.xPrecision = entry->xPrecision;
4718 memento.yPrecision = entry->yPrecision;
4719 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 memento.setPointers(entry);
4721 memento.hovering = hovering;
4722 memento.policyFlags = entry->policyFlags;
4723}
4724
4725void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4726 pointerCount = entry->pointerCount;
4727 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4728 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4729 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4730 }
4731}
4732
4733void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4734 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4735 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4736 const KeyMemento& memento = mKeyMementos.itemAt(i);
4737 if (shouldCancelKey(memento, options)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08004738 outEvents.push(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004739 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4741 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4742 }
4743 }
4744
4745 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4746 const MotionMemento& memento = mMotionMementos.itemAt(i);
4747 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004748 const int32_t action = memento.hovering ?
4749 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan42611e02018-11-27 14:04:02 -08004750 outEvents.push(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004751 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004752 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4753 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004755 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004756 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757 }
4758 }
4759}
4760
4761void InputDispatcher::InputState::clear() {
4762 mKeyMementos.clear();
4763 mMotionMementos.clear();
4764 mFallbackKeys.clear();
4765}
4766
4767void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4768 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4769 const MotionMemento& memento = mMotionMementos.itemAt(i);
4770 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4771 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4772 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4773 if (memento.deviceId == otherMemento.deviceId
4774 && memento.source == otherMemento.source
4775 && memento.displayId == otherMemento.displayId) {
4776 other.mMotionMementos.removeAt(j);
4777 } else {
4778 j += 1;
4779 }
4780 }
4781 other.mMotionMementos.push(memento);
4782 }
4783 }
4784}
4785
4786int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4787 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4788 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4789}
4790
4791void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4792 int32_t fallbackKeyCode) {
4793 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4794 if (index >= 0) {
4795 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4796 } else {
4797 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4798 }
4799}
4800
4801void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4802 mFallbackKeys.removeItem(originalKeyCode);
4803}
4804
4805bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4806 const CancelationOptions& options) {
4807 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4808 return false;
4809 }
4810
4811 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4812 return false;
4813 }
4814
4815 switch (options.mode) {
4816 case CancelationOptions::CANCEL_ALL_EVENTS:
4817 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4818 return true;
4819 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4820 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004821 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4822 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823 default:
4824 return false;
4825 }
4826}
4827
4828bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4829 const CancelationOptions& options) {
4830 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4831 return false;
4832 }
4833
4834 switch (options.mode) {
4835 case CancelationOptions::CANCEL_ALL_EVENTS:
4836 return true;
4837 case CancelationOptions::CANCEL_POINTER_EVENTS:
4838 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4839 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4840 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004841 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4842 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843 default:
4844 return false;
4845 }
4846}
4847
4848
4849// --- InputDispatcher::Connection ---
4850
Robert Carr803535b2018-08-02 16:38:15 -07004851InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4852 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 monitor(monitor),
4854 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4855}
4856
4857InputDispatcher::Connection::~Connection() {
4858}
4859
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004860const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004861 if (inputChannel != nullptr) {
4862 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 }
4864 if (monitor) {
4865 return "monitor";
4866 }
4867 return "?";
4868}
4869
4870const char* InputDispatcher::Connection::getStatusLabel() const {
4871 switch (status) {
4872 case STATUS_NORMAL:
4873 return "NORMAL";
4874
4875 case STATUS_BROKEN:
4876 return "BROKEN";
4877
4878 case STATUS_ZOMBIE:
4879 return "ZOMBIE";
4880
4881 default:
4882 return "UNKNOWN";
4883 }
4884}
4885
4886InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004887 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004888 if (entry->seq == seq) {
4889 return entry;
4890 }
4891 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004892 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893}
4894
4895
4896// --- InputDispatcher::CommandEntry ---
4897
4898InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004899 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900 seq(0), handled(false) {
4901}
4902
4903InputDispatcher::CommandEntry::~CommandEntry() {
4904}
4905
4906
4907// --- InputDispatcher::TouchState ---
4908
4909InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004910 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911}
4912
4913InputDispatcher::TouchState::~TouchState() {
4914}
4915
4916void InputDispatcher::TouchState::reset() {
4917 down = false;
4918 split = false;
4919 deviceId = -1;
4920 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004921 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 windows.clear();
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004923 portalWindows.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924}
4925
4926void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4927 down = other.down;
4928 split = other.split;
4929 deviceId = other.deviceId;
4930 source = other.source;
4931 displayId = other.displayId;
4932 windows = other.windows;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004933 portalWindows = other.portalWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934}
4935
4936void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4937 int32_t targetFlags, BitSet32 pointerIds) {
4938 if (targetFlags & InputTarget::FLAG_SPLIT) {
4939 split = true;
4940 }
4941
4942 for (size_t i = 0; i < windows.size(); i++) {
4943 TouchedWindow& touchedWindow = windows.editItemAt(i);
4944 if (touchedWindow.windowHandle == windowHandle) {
4945 touchedWindow.targetFlags |= targetFlags;
4946 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4947 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4948 }
4949 touchedWindow.pointerIds.value |= pointerIds.value;
4950 return;
4951 }
4952 }
4953
4954 windows.push();
4955
4956 TouchedWindow& touchedWindow = windows.editTop();
4957 touchedWindow.windowHandle = windowHandle;
4958 touchedWindow.targetFlags = targetFlags;
4959 touchedWindow.pointerIds = pointerIds;
4960}
4961
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004962void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) {
4963 size_t numWindows = portalWindows.size();
4964 for (size_t i = 0; i < numWindows; i++) {
4965 sp<InputWindowHandle> portalWindowHandle = portalWindows.itemAt(i);
4966 if (portalWindowHandle == windowHandle) {
4967 return;
4968 }
4969 }
4970 portalWindows.push_back(windowHandle);
4971}
4972
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4974 for (size_t i = 0; i < windows.size(); i++) {
4975 if (windows.itemAt(i).windowHandle == windowHandle) {
4976 windows.removeAt(i);
4977 return;
4978 }
4979 }
4980}
4981
Robert Carr803535b2018-08-02 16:38:15 -07004982void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4983 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004984 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004985 windows.removeAt(i);
4986 return;
4987 }
4988 }
4989}
4990
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4992 for (size_t i = 0 ; i < windows.size(); ) {
4993 TouchedWindow& window = windows.editItemAt(i);
4994 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4995 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4996 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4997 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4998 i += 1;
4999 } else {
5000 windows.removeAt(i);
5001 }
5002 }
5003}
5004
5005sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
5006 for (size_t i = 0; i < windows.size(); i++) {
5007 const TouchedWindow& window = windows.itemAt(i);
5008 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5009 return window.windowHandle;
5010 }
5011 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005012 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013}
5014
5015bool InputDispatcher::TouchState::isSlippery() const {
5016 // Must have exactly one foreground window.
5017 bool haveSlipperyForegroundWindow = false;
5018 for (size_t i = 0; i < windows.size(); i++) {
5019 const TouchedWindow& window = windows.itemAt(i);
5020 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