blob: 44100086c471148f67d7144533e1aa3ff98c75aa [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
Michael Wright3dd60e22019-03-27 22:06:44 +000020#define LOG_NDEBUG 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
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
Garfield Tan73007b62019-08-29 17:28:41 -070048#include "Connection.h"
49
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <errno.h>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080051#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <limits.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070053#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080054#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070055#include <unistd.h>
Garfield Tane4fc0102019-09-11 13:16:25 -070056#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070057
Michael Wright2b3c3302018-03-02 17:19:13 +000058#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080059#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070060#include <binder/Binder.h>
Garfield Tane4fc0102019-09-11 13:16:25 -070061#include <log/log.h>
62#include <powermanager/PowerManager.h>
63#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
65#define INDENT " "
66#define INDENT2 " "
67#define INDENT3 " "
68#define INDENT4 " "
69
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080070using android::base::StringPrintf;
71
Garfield Tan73007b62019-08-29 17:28:41 -070072namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080073
74// Default input dispatching timeout if there is no focused application or paused window
75// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000076constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080077
78// Amount of time to allow for all pending events to be processed when an app switch
79// key is on the way. This is used to preempt input dispatch and drop input events
80// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000081constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Amount of time to allow for an event to be dispatched (measured since its eventTime)
84// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000085constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080086
87// Amount of time to allow touch events to be streamed out to a connection before requiring
88// that the first event be finished. This value extends the ANR timeout by the specified
89// amount. For example, if streaming is allowed to get ahead by one second relative to the
90// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000091constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
93// 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 +000094constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
95
96// Log a warning when an interception call takes longer than this to process.
97constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080098
99// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000100constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
101
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102static inline nsecs_t now() {
103 return systemTime(SYSTEM_TIME_MONOTONIC);
104}
105
106static inline const char* toString(bool value) {
107 return value ? "true" : "false";
108}
109
110static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700111 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
112 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800113}
114
115static bool isValidKeyAction(int32_t action) {
116 switch (action) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700117 case AKEY_EVENT_ACTION_DOWN:
118 case AKEY_EVENT_ACTION_UP:
119 return true;
120 default:
121 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122 }
123}
124
125static bool validateKeyEvent(int32_t action) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700126 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127 ALOGE("Key event has invalid action code 0x%x", action);
128 return false;
129 }
130 return true;
131}
132
Michael Wright7b159c92015-05-14 14:48:03 +0100133static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700135 case AMOTION_EVENT_ACTION_DOWN:
136 case AMOTION_EVENT_ACTION_UP:
137 case AMOTION_EVENT_ACTION_CANCEL:
138 case AMOTION_EVENT_ACTION_MOVE:
139 case AMOTION_EVENT_ACTION_OUTSIDE:
140 case AMOTION_EVENT_ACTION_HOVER_ENTER:
141 case AMOTION_EVENT_ACTION_HOVER_MOVE:
142 case AMOTION_EVENT_ACTION_HOVER_EXIT:
143 case AMOTION_EVENT_ACTION_SCROLL:
144 return true;
145 case AMOTION_EVENT_ACTION_POINTER_DOWN:
146 case AMOTION_EVENT_ACTION_POINTER_UP: {
147 int32_t index = getMotionEventActionPointerIndex(action);
148 return index >= 0 && index < pointerCount;
149 }
150 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
151 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
152 return actionButton != 0;
153 default:
154 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800155 }
156}
157
Michael Wright7b159c92015-05-14 14:48:03 +0100158static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tane4fc0102019-09-11 13:16:25 -0700159 const PointerProperties* pointerProperties) {
160 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800161 ALOGE("Motion event has invalid action code 0x%x", action);
162 return false;
163 }
164 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000165 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tane4fc0102019-09-11 13:16:25 -0700166 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800167 return false;
168 }
169 BitSet32 pointerIdBits;
170 for (size_t i = 0; i < pointerCount; i++) {
171 int32_t id = pointerProperties[i].id;
172 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700173 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
174 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 return false;
176 }
177 if (pointerIdBits.hasBit(id)) {
178 ALOGE("Motion event has duplicate pointer id %d", id);
179 return false;
180 }
181 pointerIdBits.markBit(id);
182 }
183 return true;
184}
185
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800186static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800188 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 return;
190 }
191
192 bool first = true;
193 Region::const_iterator cur = region.begin();
194 Region::const_iterator const tail = region.end();
195 while (cur != tail) {
196 if (first) {
197 first = false;
198 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800199 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800200 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800201 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 cur++;
203 }
204}
205
Garfield Tane4fc0102019-09-11 13:16:25 -0700206template <typename T, typename U>
Tiger Huang721e26f2018-07-24 22:26:19 +0800207static T getValueByKey(std::unordered_map<U, T>& map, U key) {
208 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
209 return it != map.end() ? it->second : T{};
210}
211
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212// --- InputDispatcher ---
213
Garfield Tane4fc0102019-09-11 13:16:25 -0700214InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
215 : mPolicy(policy),
216 mPendingEvent(nullptr),
217 mLastDropReason(DROP_REASON_NOT_DROPPED),
218 mAppSwitchSawKeyDown(false),
219 mAppSwitchDueTime(LONG_LONG_MAX),
220 mNextUnblockedEvent(nullptr),
221 mDispatchEnabled(false),
222 mDispatchFrozen(false),
223 mInputFilterEnabled(false),
224 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
225 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800227 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228
Yi Kong9b14ac62018-07-17 13:48:38 -0700229 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230
231 policy->getDispatcherConfiguration(&mConfig);
232}
233
234InputDispatcher::~InputDispatcher() {
235 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800236 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237
238 resetKeyRepeatLocked();
239 releasePendingEventLocked();
240 drainInboundQueueLocked();
241 }
242
243 while (mConnectionsByFd.size() != 0) {
244 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
245 }
246}
247
248void InputDispatcher::dispatchOnce() {
249 nsecs_t nextWakeupTime = LONG_LONG_MAX;
250 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800251 std::scoped_lock _l(mLock);
252 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253
254 // Run a dispatch loop if there are no pending commands.
255 // The dispatch loop might enqueue commands to run afterwards.
256 if (!haveCommandsLocked()) {
257 dispatchOnceInnerLocked(&nextWakeupTime);
258 }
259
260 // Run all pending commands if there are any.
261 // If any commands were run then force the next poll to wake up immediately.
262 if (runCommandsLockedInterruptible()) {
263 nextWakeupTime = LONG_LONG_MIN;
264 }
265 } // release lock
266
267 // Wait for callback or timeout or wake. (make sure we round up, not down)
268 nsecs_t currentTime = now();
269 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
270 mLooper->pollOnce(timeoutMillis);
271}
272
273void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
274 nsecs_t currentTime = now();
275
Jeff Browndc5992e2014-04-11 01:27:26 -0700276 // Reset the key repeat timer whenever normal dispatch is suspended while the
277 // device is in a non-interactive state. This is to ensure that we abort a key
278 // repeat if the device is just coming out of sleep.
279 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800280 resetKeyRepeatLocked();
281 }
282
283 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
284 if (mDispatchFrozen) {
285#if DEBUG_FOCUS
286 ALOGD("Dispatch frozen. Waiting some more.");
287#endif
288 return;
289 }
290
291 // Optimize latency of app switches.
292 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
293 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
294 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
295 if (mAppSwitchDueTime < *nextWakeupTime) {
296 *nextWakeupTime = mAppSwitchDueTime;
297 }
298
299 // Ready to start a new event.
300 // If we don't already have a pending event, go grab one.
Garfield Tane4fc0102019-09-11 13:16:25 -0700301 if (!mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800302 if (mInboundQueue.isEmpty()) {
303 if (isAppSwitchDue) {
304 // The inbound queue is empty so the app switch key we were waiting
305 // for will never arrive. Stop waiting for it.
306 resetPendingAppSwitchLocked(false);
307 isAppSwitchDue = false;
308 }
309
310 // Synthesize a key repeat if appropriate.
311 if (mKeyRepeatState.lastKeyEntry) {
312 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
313 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
314 } else {
315 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
316 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
317 }
318 }
319 }
320
321 // Nothing to do if there is no pending event.
322 if (!mPendingEvent) {
323 return;
324 }
325 } else {
326 // Inbound queue has at least one entry.
327 mPendingEvent = mInboundQueue.dequeueAtHead();
328 traceInboundQueueLengthLocked();
329 }
330
331 // Poke user activity for this event.
332 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
333 pokeUserActivityLocked(mPendingEvent);
334 }
335
336 // Get ready to dispatch the event.
337 resetANRTimeoutsLocked();
338 }
339
340 // Now we have an event to dispatch.
341 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700342 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800343 bool done = false;
344 DropReason dropReason = DROP_REASON_NOT_DROPPED;
345 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
346 dropReason = DROP_REASON_POLICY;
347 } else if (!mDispatchEnabled) {
348 dropReason = DROP_REASON_DISABLED;
349 }
350
351 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700352 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800353 }
354
355 switch (mPendingEvent->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700356 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
357 ConfigurationChangedEntry* typedEntry =
358 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
359 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
360 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
361 break;
362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800363
Garfield Tane4fc0102019-09-11 13:16:25 -0700364 case EventEntry::TYPE_DEVICE_RESET: {
365 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
366 done = dispatchDeviceResetLocked(currentTime, typedEntry);
367 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
368 break;
369 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800370
Garfield Tane4fc0102019-09-11 13:16:25 -0700371 case EventEntry::TYPE_KEY: {
372 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
373 if (isAppSwitchDue) {
374 if (isAppSwitchKeyEvent(typedEntry)) {
375 resetPendingAppSwitchLocked(true);
376 isAppSwitchDue = false;
377 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
378 dropReason = DROP_REASON_APP_SWITCH;
379 }
380 }
381 if (dropReason == DROP_REASON_NOT_DROPPED && isStaleEvent(currentTime, typedEntry)) {
382 dropReason = DROP_REASON_STALE;
383 }
384 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
385 dropReason = DROP_REASON_BLOCKED;
386 }
387 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
388 break;
389 }
390
391 case EventEntry::TYPE_MOTION: {
392 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
393 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800394 dropReason = DROP_REASON_APP_SWITCH;
395 }
Garfield Tane4fc0102019-09-11 13:16:25 -0700396 if (dropReason == DROP_REASON_NOT_DROPPED && isStaleEvent(currentTime, typedEntry)) {
397 dropReason = DROP_REASON_STALE;
398 }
399 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
400 dropReason = DROP_REASON_BLOCKED;
401 }
402 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
403 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800405
Garfield Tane4fc0102019-09-11 13:16:25 -0700406 default:
407 ALOG_ASSERT(false);
408 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 }
410
411 if (done) {
412 if (dropReason != DROP_REASON_NOT_DROPPED) {
413 dropInboundEventLocked(mPendingEvent, dropReason);
414 }
Michael Wright3a981722015-06-10 15:26:13 +0100415 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800416
417 releasePendingEventLocked();
Garfield Tane4fc0102019-09-11 13:16:25 -0700418 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419 }
420}
421
422bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
423 bool needWake = mInboundQueue.isEmpty();
424 mInboundQueue.enqueueAtTail(entry);
425 traceInboundQueueLengthLocked();
426
427 switch (entry->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700428 case EventEntry::TYPE_KEY: {
429 // Optimize app switch latency.
430 // If the application takes too long to catch up then we drop all events preceding
431 // the app switch key.
432 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
433 if (isAppSwitchKeyEvent(keyEntry)) {
434 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
435 mAppSwitchSawKeyDown = true;
436 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
437 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438#if DEBUG_APP_SWITCH
Garfield Tane4fc0102019-09-11 13:16:25 -0700439 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440#endif
Garfield Tane4fc0102019-09-11 13:16:25 -0700441 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
442 mAppSwitchSawKeyDown = false;
443 needWake = true;
444 }
445 }
446 }
447 break;
448 }
449
450 case EventEntry::TYPE_MOTION: {
451 // Optimize case where the current application is unresponsive and the user
452 // decides to touch a window in a different application.
453 // If the application takes too long to catch up then we drop all events preceding
454 // the touch into the other window.
455 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
456 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
457 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
458 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
459 mInputTargetWaitApplicationToken != nullptr) {
460 int32_t displayId = motionEntry->displayId;
461 int32_t x =
462 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
463 int32_t y =
464 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
465 sp<InputWindowHandle> touchedWindowHandle =
466 findTouchedWindowAtLocked(displayId, x, y);
467 if (touchedWindowHandle != nullptr &&
468 touchedWindowHandle->getApplicationToken() !=
469 mInputTargetWaitApplicationToken) {
470 // User touched a different application than the one we are waiting on.
471 // Flag the event, and start pruning the input queue.
472 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800473 needWake = true;
474 }
475 }
Garfield Tane4fc0102019-09-11 13:16:25 -0700476 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478 }
479
480 return needWake;
481}
482
483void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
484 entry->refCount += 1;
485 mRecentQueue.enqueueAtTail(entry);
486 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
487 mRecentQueue.dequeueAtHead()->release();
488 }
489}
490
Garfield Tane4fc0102019-09-11 13:16:25 -0700491sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
492 int32_t y, bool addOutsideTargets,
493 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800495 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
496 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800497 const InputWindowInfo* windowInfo = windowHandle->getInfo();
498 if (windowInfo->displayId == displayId) {
499 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500
501 if (windowInfo->visible) {
502 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700503 bool isTouchModal = (flags &
504 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
505 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800507 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tane4fc0102019-09-11 13:16:25 -0700508 if (portalToDisplayId != ADISPLAY_ID_NONE &&
509 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800510 if (addPortalWindows) {
511 // For the monitoring channels of the display.
512 mTempTouchState.addPortalWindow(windowHandle);
513 }
Garfield Tane4fc0102019-09-11 13:16:25 -0700514 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
515 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800516 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800517 // Found window.
518 return windowHandle;
519 }
520 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800521
522 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700523 mTempTouchState.addOrUpdateWindow(windowHandle,
524 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
525 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 }
529 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700530 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531}
532
Garfield Tan73007b62019-08-29 17:28:41 -0700533std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000534 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
535 std::vector<TouchedMonitor> touchedMonitors;
536
537 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
538 addGestureMonitors(monitors, touchedMonitors);
539 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
540 const InputWindowInfo* windowInfo = portalWindow->getInfo();
541 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tane4fc0102019-09-11 13:16:25 -0700542 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
543 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000544 }
545 return touchedMonitors;
546}
547
548void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tane4fc0102019-09-11 13:16:25 -0700549 std::vector<TouchedMonitor>& outTouchedMonitors,
550 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000551 if (monitors.empty()) {
552 return;
553 }
554 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
555 for (const Monitor& monitor : monitors) {
556 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
557 }
558}
559
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
561 const char* reason;
562 switch (dropReason) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700563 case DROP_REASON_POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tane4fc0102019-09-11 13:16:25 -0700565 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800566#endif
Garfield Tane4fc0102019-09-11 13:16:25 -0700567 reason = "inbound event was dropped because the policy consumed it";
568 break;
569 case DROP_REASON_DISABLED:
570 if (mLastDropReason != DROP_REASON_DISABLED) {
571 ALOGI("Dropped event because input dispatch is disabled.");
572 }
573 reason = "inbound event was dropped because input dispatch is disabled";
574 break;
575 case DROP_REASON_APP_SWITCH:
576 ALOGI("Dropped event because of pending overdue app switch.");
577 reason = "inbound event was dropped because of pending overdue app switch";
578 break;
579 case DROP_REASON_BLOCKED:
580 ALOGI("Dropped event because the current application is not responding and the user "
581 "has started interacting with a different application.");
582 reason = "inbound event was dropped because the current application is not responding "
583 "and the user has started interacting with a different application";
584 break;
585 case DROP_REASON_STALE:
586 ALOGI("Dropped event because it is stale.");
587 reason = "inbound event was dropped because it is stale";
588 break;
589 default:
590 ALOG_ASSERT(false);
591 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800592 }
593
594 switch (entry->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700595 case EventEntry::TYPE_KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
597 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tane4fc0102019-09-11 13:16:25 -0700598 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599 }
Garfield Tane4fc0102019-09-11 13:16:25 -0700600 case EventEntry::TYPE_MOTION: {
601 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
602 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
603 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
604 synthesizeCancelationEventsForAllConnectionsLocked(options);
605 } else {
606 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
607 synthesizeCancelationEventsForAllConnectionsLocked(options);
608 }
609 break;
610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 }
612}
613
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800614static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700615 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
616 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617}
618
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800619bool InputDispatcher::isAppSwitchKeyEvent(KeyEntry* keyEntry) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700620 return !(keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry->keyCode) &&
621 (keyEntry->policyFlags & POLICY_FLAG_TRUSTED) &&
622 (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623}
624
625bool InputDispatcher::isAppSwitchPendingLocked() {
626 return mAppSwitchDueTime != LONG_LONG_MAX;
627}
628
629void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
630 mAppSwitchDueTime = LONG_LONG_MAX;
631
632#if DEBUG_APP_SWITCH
633 if (handled) {
634 ALOGD("App switch has arrived.");
635 } else {
636 ALOGD("App switch was abandoned.");
637 }
638#endif
639}
640
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800641bool InputDispatcher::isStaleEvent(nsecs_t currentTime, EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
643}
644
645bool InputDispatcher::haveCommandsLocked() const {
646 return !mCommandQueue.isEmpty();
647}
648
649bool InputDispatcher::runCommandsLockedInterruptible() {
650 if (mCommandQueue.isEmpty()) {
651 return false;
652 }
653
654 do {
655 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
656
657 Command command = commandEntry->command;
658 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
659
660 commandEntry->connection.clear();
661 delete commandEntry;
Garfield Tane4fc0102019-09-11 13:16:25 -0700662 } while (!mCommandQueue.isEmpty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663 return true;
664}
665
Garfield Tan73007b62019-08-29 17:28:41 -0700666CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800667 CommandEntry* commandEntry = new CommandEntry(command);
668 mCommandQueue.enqueueAtTail(commandEntry);
669 return commandEntry;
670}
671
672void InputDispatcher::drainInboundQueueLocked() {
Garfield Tane4fc0102019-09-11 13:16:25 -0700673 while (!mInboundQueue.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 EventEntry* entry = mInboundQueue.dequeueAtHead();
675 releaseInboundEventLocked(entry);
676 }
677 traceInboundQueueLengthLocked();
678}
679
680void InputDispatcher::releasePendingEventLocked() {
681 if (mPendingEvent) {
682 resetANRTimeoutsLocked();
683 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700684 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685 }
686}
687
688void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
689 InjectionState* injectionState = entry->injectionState;
690 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
691#if DEBUG_DISPATCH_CYCLE
692 ALOGD("Injected inbound event was dropped.");
693#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800694 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695 }
696 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700697 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
699 addRecentEventLocked(entry);
700 entry->release();
701}
702
703void InputDispatcher::resetKeyRepeatLocked() {
704 if (mKeyRepeatState.lastKeyEntry) {
705 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700706 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 }
708}
709
Garfield Tan73007b62019-08-29 17:28:41 -0700710KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
712
713 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700714 uint32_t policyFlags = entry->policyFlags &
715 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 if (entry->refCount == 1) {
717 entry->recycle();
718 entry->eventTime = currentTime;
719 entry->policyFlags = policyFlags;
720 entry->repeatCount += 1;
721 } else {
Garfield Tane4fc0102019-09-11 13:16:25 -0700722 KeyEntry* newEntry =
723 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId,
724 entry->source, entry->displayId, policyFlags, entry->action,
725 entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
726 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727
728 mKeyRepeatState.lastKeyEntry = newEntry;
729 entry->release();
730
731 entry = newEntry;
732 }
733 entry->syntheticRepeat = true;
734
735 // Increment reference count since we keep a reference to the event in
736 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
737 entry->refCount += 1;
738
739 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
740 return entry;
741}
742
Garfield Tane4fc0102019-09-11 13:16:25 -0700743bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
744 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700746 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747#endif
748
749 // Reset key repeating in case a keyboard device was added or removed or something.
750 resetKeyRepeatLocked();
751
752 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Garfield Tane4fc0102019-09-11 13:16:25 -0700753 CommandEntry* commandEntry =
754 postCommandLocked(&InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 commandEntry->eventTime = entry->eventTime;
756 return true;
757}
758
Garfield Tane4fc0102019-09-11 13:16:25 -0700759bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700761 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tane4fc0102019-09-11 13:16:25 -0700762 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763#endif
764
Garfield Tane4fc0102019-09-11 13:16:25 -0700765 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 options.deviceId = entry->deviceId;
767 synthesizeCancelationEventsForAllConnectionsLocked(options);
768 return true;
769}
770
771bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tane4fc0102019-09-11 13:16:25 -0700772 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 // Preprocessing.
Garfield Tane4fc0102019-09-11 13:16:25 -0700774 if (!entry->dispatchInProgress) {
775 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
776 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
777 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
778 if (mKeyRepeatState.lastKeyEntry &&
779 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 // We have seen two identical key downs in a row which indicates that the device
781 // driver is automatically generating key repeats itself. We take note of the
782 // repeat here, but we disable our own next key repeat timer since it is clear that
783 // we will not need to synthesize key repeats ourselves.
784 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
785 resetKeyRepeatLocked();
786 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
787 } else {
788 // Not a repeat. Save key down state in case we do see a repeat later.
789 resetKeyRepeatLocked();
790 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
791 }
792 mKeyRepeatState.lastKeyEntry = entry;
793 entry->refCount += 1;
Garfield Tane4fc0102019-09-11 13:16:25 -0700794 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795 resetKeyRepeatLocked();
796 }
797
798 if (entry->repeatCount == 1) {
799 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
800 } else {
801 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
802 }
803
804 entry->dispatchInProgress = true;
805
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800806 logOutboundKeyDetails("dispatchKey - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807 }
808
809 // Handle case where the policy asked us to try again later last time.
810 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
811 if (currentTime < entry->interceptKeyWakeupTime) {
812 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
813 *nextWakeupTime = entry->interceptKeyWakeupTime;
814 }
815 return false; // wait until next wakeup
816 }
817 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
818 entry->interceptKeyWakeupTime = 0;
819 }
820
821 // Give the policy a chance to intercept the key.
822 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
823 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
824 CommandEntry* commandEntry = postCommandLocked(
Garfield Tane4fc0102019-09-11 13:16:25 -0700825 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800826 sp<InputWindowHandle> focusedWindowHandle =
827 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
828 if (focusedWindowHandle != nullptr) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700829 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830 }
831 commandEntry->keyEntry = entry;
832 entry->refCount += 1;
833 return false; // wait for the command to run
834 } else {
835 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
836 }
837 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
838 if (*dropReason == DROP_REASON_NOT_DROPPED) {
839 *dropReason = DROP_REASON_POLICY;
840 }
841 }
842
843 // Clean up if dropping the event.
844 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700845 setInjectionResult(entry,
846 *dropReason == DROP_REASON_POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
847 : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800848 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 return true;
850 }
851
852 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800853 std::vector<InputTarget> inputTargets;
Garfield Tane4fc0102019-09-11 13:16:25 -0700854 int32_t injectionResult =
855 findFocusedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
857 return false;
858 }
859
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800860 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
862 return true;
863 }
864
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800865 // Add monitor channels from event's or focused display.
Michael Wright3dd60e22019-03-27 22:06:44 +0000866 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867
868 // Dispatch the key.
869 dispatchEventLocked(currentTime, entry, inputTargets);
870 return true;
871}
872
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800873void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100875 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tane4fc0102019-09-11 13:16:25 -0700876 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
877 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
878 prefix, entry->eventTime, entry->deviceId, entry->source, entry->displayId,
879 entry->policyFlags, entry->action, entry->flags, entry->keyCode, entry->scanCode,
880 entry->metaState, entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881#endif
882}
883
Garfield Tane4fc0102019-09-11 13:16:25 -0700884bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
885 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000886 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 // Preprocessing.
Garfield Tane4fc0102019-09-11 13:16:25 -0700888 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 entry->dispatchInProgress = true;
890
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800891 logOutboundMotionDetails("dispatchMotion - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 }
893
894 // Clean up if dropping the event.
895 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700896 setInjectionResult(entry,
897 *dropReason == DROP_REASON_POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
898 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 return true;
900 }
901
902 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
903
904 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800905 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906
907 bool conflictingPointerActions = false;
908 int32_t injectionResult;
909 if (isPointerEvent) {
910 // Pointer event. (eg. touchscreen)
Garfield Tane4fc0102019-09-11 13:16:25 -0700911 injectionResult =
912 findTouchedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime,
913 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 } else {
915 // Non touch event. (eg. trackball)
Garfield Tane4fc0102019-09-11 13:16:25 -0700916 injectionResult =
917 findFocusedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800918 }
919 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
920 return false;
921 }
922
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800923 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100925 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tane4fc0102019-09-11 13:16:25 -0700926 CancelationOptions::Mode mode(isPointerEvent
927 ? CancelationOptions::CANCEL_POINTER_EVENTS
928 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100929 CancelationOptions options(mode, "input event injection failed");
930 synthesizeCancelationEventsForMonitorsLocked(options);
931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 return true;
933 }
934
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800935 // Add monitor channels from event's or focused display.
Michael Wright3dd60e22019-03-27 22:06:44 +0000936 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800938 if (isPointerEvent) {
939 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
940 if (stateIndex >= 0) {
941 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800942 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800943 // The event has gone through these portal windows, so we add monitoring targets of
944 // the corresponding displays as well.
945 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800946 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +0000947 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tane4fc0102019-09-11 13:16:25 -0700948 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800949 }
950 }
951 }
952 }
953
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 // Dispatch the motion.
955 if (conflictingPointerActions) {
956 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tane4fc0102019-09-11 13:16:25 -0700957 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958 synthesizeCancelationEventsForAllConnectionsLocked(options);
959 }
960 dispatchEventLocked(currentTime, entry, inputTargets);
961 return true;
962}
963
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800964void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800966 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tane4fc0102019-09-11 13:16:25 -0700967 ", policyFlags=0x%x, "
968 "action=0x%x, actionButton=0x%x, flags=0x%x, "
969 "metaState=0x%x, buttonState=0x%x,"
970 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
971 prefix, entry->eventTime, entry->deviceId, entry->source, entry->displayId,
972 entry->policyFlags, entry->action, entry->actionButton, entry->flags, entry->metaState,
973 entry->buttonState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
974 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975
976 for (uint32_t i = 0; i < entry->pointerCount; i++) {
977 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tane4fc0102019-09-11 13:16:25 -0700978 "x=%f, y=%f, pressure=%f, size=%f, "
979 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
980 "orientation=%f",
981 i, entry->pointerProperties[i].id, entry->pointerProperties[i].toolType,
982 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
983 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
984 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
985 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
986 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
987 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
988 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
989 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
990 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 }
992#endif
993}
994
Garfield Tane4fc0102019-09-11 13:16:25 -0700995void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
996 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000997 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998#if DEBUG_DISPATCH_CYCLE
999 ALOGD("dispatchEventToCurrentInputTargets");
1000#endif
1001
1002 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1003
1004 pokeUserActivityLocked(eventEntry);
1005
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001006 for (const InputTarget& inputTarget : inputTargets) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
1008 if (connectionIndex >= 0) {
1009 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1010 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1011 } else {
1012#if DEBUG_FOCUS
1013 ALOGD("Dropping event delivery to target with channel '%s' because it "
Garfield Tane4fc0102019-09-11 13:16:25 -07001014 "is no longer registered with the input dispatcher.",
1015 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016#endif
1017 }
1018 }
1019}
1020
Garfield Tane4fc0102019-09-11 13:16:25 -07001021int32_t InputDispatcher::handleTargetsNotReadyLocked(
1022 nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001024 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001025 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1027#if DEBUG_FOCUS
1028 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1029#endif
1030 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1031 mInputTargetWaitStartTime = currentTime;
1032 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1033 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001034 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035 }
1036 } else {
1037 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1038#if DEBUG_FOCUS
1039 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Garfield Tane4fc0102019-09-11 13:16:25 -07001040 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041#endif
1042 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001043 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001045 } else if (applicationHandle != nullptr) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001046 timeout =
1047 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 } else {
1049 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1050 }
1051
1052 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1053 mInputTargetWaitStartTime = currentTime;
1054 mInputTargetWaitTimeoutTime = currentTime + timeout;
1055 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001056 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057
Yi Kong9b14ac62018-07-17 13:48:38 -07001058 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001059 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 }
Robert Carr740167f2018-10-11 19:03:41 -07001061 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1062 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 }
1064 }
1065 }
1066
1067 if (mInputTargetWaitTimeoutExpired) {
1068 return INPUT_EVENT_INJECTION_TIMED_OUT;
1069 }
1070
1071 if (currentTime >= mInputTargetWaitTimeoutTime) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001072 onANRLocked(currentTime, applicationHandle, windowHandle, entry->eventTime,
1073 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074
1075 // Force poll loop to wake up immediately on next iteration once we get the
1076 // ANR response back from the policy.
1077 *nextWakeupTime = LONG_LONG_MIN;
1078 return INPUT_EVENT_INJECTION_PENDING;
1079 } else {
1080 // Force poll loop to wake up when timeout is due.
1081 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1082 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1083 }
1084 return INPUT_EVENT_INJECTION_PENDING;
1085 }
1086}
1087
Robert Carr803535b2018-08-02 16:38:15 -07001088void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1089 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1090 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1091 state.removeWindowByToken(token);
1092 }
1093}
1094
Garfield Tane4fc0102019-09-11 13:16:25 -07001095void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
1096 nsecs_t newTimeout, const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 if (newTimeout > 0) {
1098 // Extend the timeout.
1099 mInputTargetWaitTimeoutTime = now() + newTimeout;
1100 } else {
1101 // Give up.
1102 mInputTargetWaitTimeoutExpired = true;
1103
1104 // Input state will not be realistic. Mark it out of sync.
1105 if (inputChannel.get()) {
1106 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1107 if (connectionIndex >= 0) {
1108 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001109 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110
Robert Carr803535b2018-08-02 16:38:15 -07001111 if (token != nullptr) {
1112 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113 }
1114
1115 if (connection->status == Connection::STATUS_NORMAL) {
1116 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Garfield Tane4fc0102019-09-11 13:16:25 -07001117 "application not responding");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 synthesizeCancelationEventsForConnectionLocked(connection, options);
1119 }
1120 }
1121 }
1122 }
1123}
1124
Garfield Tane4fc0102019-09-11 13:16:25 -07001125nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1127 return currentTime - mInputTargetWaitStartTime;
1128 }
1129 return 0;
1130}
1131
1132void InputDispatcher::resetANRTimeoutsLocked() {
1133#if DEBUG_FOCUS
Garfield Tane4fc0102019-09-11 13:16:25 -07001134 ALOGD("Resetting ANR timeouts.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135#endif
1136
1137 // Reset input target wait timeout.
1138 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001139 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140}
1141
Tiger Huang721e26f2018-07-24 22:26:19 +08001142/**
1143 * Get the display id that the given event should go to. If this event specifies a valid display id,
1144 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1145 * Focused display is the display that the user most recently interacted with.
1146 */
1147int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1148 int32_t displayId;
1149 switch (entry->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001150 case EventEntry::TYPE_KEY: {
1151 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1152 displayId = typedEntry->displayId;
1153 break;
1154 }
1155 case EventEntry::TYPE_MOTION: {
1156 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1157 displayId = typedEntry->displayId;
1158 break;
1159 }
1160 default: {
1161 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1162 return ADISPLAY_ID_NONE;
1163 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001164 }
1165 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1166}
1167
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07001169 const EventEntry* entry,
1170 std::vector<InputTarget>& inputTargets,
1171 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001173 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174
Tiger Huang721e26f2018-07-24 22:26:19 +08001175 int32_t displayId = getTargetDisplayId(entry);
1176 sp<InputWindowHandle> focusedWindowHandle =
1177 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1178 sp<InputApplicationHandle> focusedApplicationHandle =
1179 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1180
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 // If there is no currently focused window and no focused application
1182 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001183 if (focusedWindowHandle == nullptr) {
1184 if (focusedApplicationHandle != nullptr) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001185 injectionResult =
1186 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1187 nullptr, nextWakeupTime,
1188 "Waiting because no window has focus but there is "
1189 "a "
1190 "focused application that may eventually add a "
1191 "window "
1192 "when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 goto Unresponsive;
1194 }
1195
Arthur Hung3b413f22018-10-26 18:05:34 +08001196 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tane4fc0102019-09-11 13:16:25 -07001197 "%" PRId32 ".",
1198 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1200 goto Failed;
1201 }
1202
1203 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001204 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1206 goto Failed;
1207 }
1208
Jeff Brownffb49772014-10-10 19:01:34 -07001209 // Check whether the window is ready for more input.
Garfield Tane4fc0102019-09-11 13:16:25 -07001210 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001211 if (!reason.empty()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001212 injectionResult =
1213 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1214 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 goto Unresponsive;
1216 }
1217
1218 // Success! Output targets.
1219 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001220 addWindowTargetLocked(focusedWindowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001221 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1222 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223
1224 // Done.
1225Failed:
1226Unresponsive:
1227 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001228 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229#if DEBUG_FOCUS
1230 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07001231 "timeSpentWaitingForApplication=%0.1fms",
1232 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233#endif
1234 return injectionResult;
1235}
1236
1237int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07001238 const MotionEntry* entry,
1239 std::vector<InputTarget>& inputTargets,
1240 nsecs_t* nextWakeupTime,
1241 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001242 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 enum InjectionPermission {
1244 INJECTION_PERMISSION_UNKNOWN,
1245 INJECTION_PERMISSION_GRANTED,
1246 INJECTION_PERMISSION_DENIED
1247 };
1248
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 // For security reasons, we defer updating the touch state until we are sure that
1250 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 int32_t displayId = entry->displayId;
1252 int32_t action = entry->action;
1253 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1254
1255 // Update the touch state as needed based on the properties of the touch event.
1256 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1257 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1258 sp<InputWindowHandle> newHoverWindowHandle;
1259
Jeff Brownf086ddb2014-02-11 14:28:48 -08001260 // Copy current touch state into mTempTouchState.
1261 // This state is always reset at the end of this function, so if we don't find state
1262 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001263 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001264 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1265 if (oldStateIndex >= 0) {
1266 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1267 mTempTouchState.copyFrom(*oldState);
1268 }
1269
1270 bool isSplit = mTempTouchState.split;
Garfield Tane4fc0102019-09-11 13:16:25 -07001271 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
1272 (mTempTouchState.deviceId != entry->deviceId ||
1273 mTempTouchState.source != entry->source || mTempTouchState.displayId != displayId);
1274 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1275 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1276 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1277 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1278 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 bool wrongDevice = false;
1280 if (newGesture) {
1281 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001282 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001284 ALOGD("Dropping event because a pointer for a different device is already down "
Garfield Tane4fc0102019-09-11 13:16:25 -07001285 "in display %" PRId32,
1286 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001288 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1290 switchedDevice = false;
1291 wrongDevice = true;
1292 goto Failed;
1293 }
1294 mTempTouchState.reset();
1295 mTempTouchState.down = down;
1296 mTempTouchState.deviceId = entry->deviceId;
1297 mTempTouchState.source = entry->source;
1298 mTempTouchState.displayId = displayId;
1299 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001300 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1301#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001302 ALOGI("Dropping move event because a pointer for a different device is already active "
Garfield Tane4fc0102019-09-11 13:16:25 -07001303 "in display %" PRId32,
1304 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001305#endif
1306 // TODO: test multiple simultaneous input streams.
1307 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1308 switchedDevice = false;
1309 wrongDevice = true;
1310 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311 }
1312
1313 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1314 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1315
1316 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tane4fc0102019-09-11 13:16:25 -07001317 int32_t x = int32_t(entry->pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1318 int32_t y = int32_t(entry->pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wright3dd60e22019-03-27 22:06:44 +00001319 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tane4fc0102019-09-11 13:16:25 -07001320 sp<InputWindowHandle> newTouchedWindowHandle =
1321 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1322 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001323
1324 std::vector<TouchedMonitor> newGestureMonitors = isDown
1325 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1326 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 // Figure out whether splitting will be allowed for this window.
Garfield Tane4fc0102019-09-11 13:16:25 -07001329 if (newTouchedWindowHandle != nullptr &&
1330 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 // New window supports splitting.
1332 isSplit = true;
1333 } else if (isSplit) {
1334 // New window does not support splitting but we have already split events.
1335 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001336 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 }
1338
1339 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001340 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 // Try to assign the pointer to the first foreground window we find, if there is one.
1342 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001343 }
1344
1345 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1346 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tane4fc0102019-09-11 13:16:25 -07001347 "(%d, %d) in display %" PRId32 ".",
1348 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001349 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1350 goto Failed;
1351 }
1352
1353 if (newTouchedWindowHandle != nullptr) {
1354 // Set target flags.
1355 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1356 if (isSplit) {
1357 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001359 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1360 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1361 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1362 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1363 }
1364
1365 // Update hover state.
1366 if (isHoverAction) {
1367 newHoverWindowHandle = newTouchedWindowHandle;
1368 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1369 newHoverWindowHandle = mLastHoverWindowHandle;
1370 }
1371
1372 // Update the temporary touch state.
1373 BitSet32 pointerIds;
1374 if (isSplit) {
1375 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1376 pointerIds.markBit(pointerId);
1377 }
1378 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 }
1380
Michael Wright3dd60e22019-03-27 22:06:44 +00001381 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 } else {
1383 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1384
1385 // If the pointer is not currently down, then ignore the event.
Garfield Tane4fc0102019-09-11 13:16:25 -07001386 if (!mTempTouchState.down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387#if DEBUG_FOCUS
1388 ALOGD("Dropping event because the pointer is not down or we previously "
Garfield Tane4fc0102019-09-11 13:16:25 -07001389 "dropped the pointer down event in display %" PRId32,
1390 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391#endif
1392 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1393 goto Failed;
1394 }
1395
1396 // Check whether touches should slip outside of the current foreground window.
Garfield Tane4fc0102019-09-11 13:16:25 -07001397 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry->pointerCount == 1 &&
1398 mTempTouchState.isSlippery()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1400 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1401
1402 sp<InputWindowHandle> oldTouchedWindowHandle =
1403 mTempTouchState.getFirstForegroundWindowHandle();
1404 sp<InputWindowHandle> newTouchedWindowHandle =
1405 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tane4fc0102019-09-11 13:16:25 -07001406 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1407 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001409 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Garfield Tane4fc0102019-09-11 13:16:25 -07001410 oldTouchedWindowHandle->getName().c_str(),
1411 newTouchedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412#endif
1413 // Make a slippery exit from the old window.
1414 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001415 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1416 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417
1418 // Make a slippery entrance into the new window.
1419 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1420 isSplit = true;
1421 }
1422
Garfield Tane4fc0102019-09-11 13:16:25 -07001423 int32_t targetFlags =
1424 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 if (isSplit) {
1426 targetFlags |= InputTarget::FLAG_SPLIT;
1427 }
1428 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1429 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1430 }
1431
1432 BitSet32 pointerIds;
1433 if (isSplit) {
1434 pointerIds.markBit(entry->pointerProperties[0].id);
1435 }
1436 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1437 }
1438 }
1439 }
1440
1441 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1442 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001443 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444#if DEBUG_HOVER
1445 ALOGD("Sending hover exit event to window %s.",
Garfield Tane4fc0102019-09-11 13:16:25 -07001446 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447#endif
1448 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001449 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1450 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 }
1452
1453 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001454 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455#if DEBUG_HOVER
1456 ALOGD("Sending hover enter event to window %s.",
Garfield Tane4fc0102019-09-11 13:16:25 -07001457 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458#endif
1459 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001460 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1461 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 }
1463 }
1464
1465 // Check permission to inject into all touched foreground windows and ensure there
1466 // is at least one touched foreground window.
1467 {
1468 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001469 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1471 haveForegroundWindow = true;
Garfield Tane4fc0102019-09-11 13:16:25 -07001472 if (!checkInjectionPermission(touchedWindow.windowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1474 injectionPermission = INJECTION_PERMISSION_DENIED;
1475 goto Failed;
1476 }
1477 }
1478 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001479 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1480 if (!haveForegroundWindow && !hasGestureMonitor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481#if DEBUG_FOCUS
Garfield Tane4fc0102019-09-11 13:16:25 -07001482 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1483 " or gesture monitor to receive it.",
1484 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485#endif
1486 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1487 goto Failed;
1488 }
1489
1490 // Permission granted to injection into all touched foreground windows.
1491 injectionPermission = INJECTION_PERMISSION_GRANTED;
1492 }
1493
1494 // Check whether windows listening for outside touches are owned by the same UID. If it is
1495 // set the policy flag that we will not reveal coordinate information to this window.
1496 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1497 sp<InputWindowHandle> foregroundWindowHandle =
1498 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001499 if (foregroundWindowHandle) {
1500 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1501 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1502 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1503 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1504 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1505 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001506 InputTarget::FLAG_ZERO_COORDS,
1507 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001508 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 }
1510 }
1511 }
1512 }
1513
1514 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001515 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001517 // Check whether the window is ready for more input.
Garfield Tane4fc0102019-09-11 13:16:25 -07001518 std::string reason =
1519 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1520 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001521 if (!reason.empty()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001522 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1523 touchedWindow.windowHandle,
1524 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 goto Unresponsive;
1526 }
1527 }
1528 }
1529
1530 // If this is the first pointer going down and the touched window has a wallpaper
1531 // then also add the touched wallpaper windows so they are locked in for the duration
1532 // of the touch gesture.
1533 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1534 // engine only supports touch events. We would need to add a mechanism similar
1535 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1536 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1537 sp<InputWindowHandle> foregroundWindowHandle =
1538 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001539 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001540 const std::vector<sp<InputWindowHandle>> windowHandles =
1541 getWindowHandlesLocked(displayId);
1542 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tane4fc0102019-09-11 13:16:25 -07001544 if (info->displayId == displayId &&
1545 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1546 mTempTouchState
1547 .addOrUpdateWindow(windowHandle,
1548 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1549 InputTarget::
1550 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1551 InputTarget::FLAG_DISPATCH_AS_IS,
1552 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 }
1554 }
1555 }
1556 }
1557
1558 // Success! Output targets.
1559 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1560
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001561 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tane4fc0102019-09-11 13:16:25 -07001563 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 }
1565
Michael Wright3dd60e22019-03-27 22:06:44 +00001566 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1567 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tane4fc0102019-09-11 13:16:25 -07001568 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001569 }
1570
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 // Drop the outside or hover touch windows since we will not care about them
1572 // in the next iteration.
1573 mTempTouchState.filterNonAsIsTouchWindows();
1574
1575Failed:
1576 // Check injection permission once and for all.
1577 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001578 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 injectionPermission = INJECTION_PERMISSION_GRANTED;
1580 } else {
1581 injectionPermission = INJECTION_PERMISSION_DENIED;
1582 }
1583 }
1584
1585 // Update final pieces of touch state if the injector had permission.
1586 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1587 if (!wrongDevice) {
1588 if (switchedDevice) {
1589#if DEBUG_FOCUS
1590 ALOGD("Conflicting pointer actions: Switched to a different device.");
1591#endif
1592 *outConflictingPointerActions = true;
1593 }
1594
1595 if (isHoverAction) {
1596 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001597 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598#if DEBUG_FOCUS
1599 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1600#endif
1601 *outConflictingPointerActions = true;
1602 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001603 mTempTouchState.reset();
Garfield Tane4fc0102019-09-11 13:16:25 -07001604 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1605 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001606 mTempTouchState.deviceId = entry->deviceId;
1607 mTempTouchState.source = entry->source;
1608 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609 }
Garfield Tane4fc0102019-09-11 13:16:25 -07001610 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1611 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001613 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1615 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001616 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617#if DEBUG_FOCUS
1618 ALOGD("Conflicting pointer actions: Down received while already down.");
1619#endif
1620 *outConflictingPointerActions = true;
1621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1623 // One pointer went up.
1624 if (isSplit) {
1625 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1626 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1627
Garfield Tane4fc0102019-09-11 13:16:25 -07001628 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001629 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1631 touchedWindow.pointerIds.clearBit(pointerId);
1632 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001633 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634 continue;
1635 }
1636 }
1637 i += 1;
1638 }
1639 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001640 }
1641
1642 // Save changes unless the action was scroll in which case the temporary touch
1643 // state was only valid for this one action.
1644 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1645 if (mTempTouchState.displayId >= 0) {
1646 if (oldStateIndex >= 0) {
1647 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1648 } else {
1649 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1650 }
1651 } else if (oldStateIndex >= 0) {
1652 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 }
1655
1656 // Update hover state.
1657 mLastHoverWindowHandle = newHoverWindowHandle;
1658 }
1659 } else {
1660#if DEBUG_FOCUS
1661 ALOGD("Not updating touch focus because injection was denied.");
1662#endif
1663 }
1664
1665Unresponsive:
1666 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1667 mTempTouchState.reset();
1668
1669 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001670 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671#if DEBUG_FOCUS
1672 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07001673 "timeSpentWaitingForApplication=%0.1fms",
1674 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675#endif
1676 return injectionResult;
1677}
1678
1679void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001680 int32_t targetFlags, BitSet32 pointerIds,
1681 std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001682 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1683 if (inputChannel == nullptr) {
1684 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1685 return;
1686 }
1687
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001689 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001690 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691 target.flags = targetFlags;
Garfield Tane4fc0102019-09-11 13:16:25 -07001692 target.xOffset = -windowInfo->frameLeft;
1693 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001694 target.globalScaleFactor = windowInfo->globalScaleFactor;
1695 target.windowXScale = windowInfo->windowXScale;
1696 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001698 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001699}
1700
Michael Wright3dd60e22019-03-27 22:06:44 +00001701void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tane4fc0102019-09-11 13:16:25 -07001702 int32_t displayId, float xOffset,
1703 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001704 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1705 mGlobalMonitorsByDisplay.find(displayId);
1706
1707 if (it != mGlobalMonitorsByDisplay.end()) {
1708 const std::vector<Monitor>& monitors = it->second;
1709 for (const Monitor& monitor : monitors) {
1710 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 }
1713}
1714
Garfield Tane4fc0102019-09-11 13:16:25 -07001715void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1716 float yOffset,
1717 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001718 InputTarget target;
1719 target.inputChannel = monitor.inputChannel;
1720 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1721 target.xOffset = xOffset;
1722 target.yOffset = yOffset;
1723 target.pointerIds.clear();
1724 target.globalScaleFactor = 1.0f;
1725 inputTargets.push_back(target);
1726}
1727
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tane4fc0102019-09-11 13:16:25 -07001729 const InjectionState* injectionState) {
1730 if (injectionState &&
1731 (windowHandle == nullptr ||
1732 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1733 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001734 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tane4fc0102019-09-11 13:16:25 -07001736 "owned by uid %d",
1737 injectionState->injectorPid, injectionState->injectorUid,
1738 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 } else {
1740 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tane4fc0102019-09-11 13:16:25 -07001741 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 }
1743 return false;
1744 }
1745 return true;
1746}
1747
Garfield Tane4fc0102019-09-11 13:16:25 -07001748bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1749 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001751 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1752 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753 if (otherHandle == windowHandle) {
1754 break;
1755 }
1756
1757 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tane4fc0102019-09-11 13:16:25 -07001758 if (otherInfo->displayId == displayId && otherInfo->visible &&
1759 !otherInfo->isTrustedOverlay() && otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760 return true;
1761 }
1762 }
1763 return false;
1764}
1765
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001766bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1767 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001768 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001769 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001770 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001771 if (otherHandle == windowHandle) {
1772 break;
1773 }
1774
1775 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tane4fc0102019-09-11 13:16:25 -07001776 if (otherInfo->displayId == displayId && otherInfo->visible &&
1777 !otherInfo->isTrustedOverlay() && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001778 return true;
1779 }
1780 }
1781 return false;
1782}
1783
Garfield Tane4fc0102019-09-11 13:16:25 -07001784std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
1785 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
1786 const EventEntry* eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07001787 // If the window is paused then keep waiting.
1788 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001789 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001790 }
1791
1792 // If the window's connection is not registered then keep waiting.
Garfield Tane4fc0102019-09-11 13:16:25 -07001793 ssize_t connectionIndex =
1794 getConnectionIndexLocked(getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001795 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001796 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tane4fc0102019-09-11 13:16:25 -07001797 "registered with the input dispatcher. The window may be in the "
1798 "process "
1799 "of being removed.",
1800 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001801 }
1802
1803 // If the connection is dead then keep waiting.
1804 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1805 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001806 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tane4fc0102019-09-11 13:16:25 -07001807 "The window may be in the process of being removed.",
1808 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07001809 }
1810
1811 // If the connection is backed up then keep waiting.
1812 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001813 return StringPrintf("Waiting because the %s window's input channel is full. "
Garfield Tane4fc0102019-09-11 13:16:25 -07001814 "Outbound queue length: %d. Wait queue length: %d.",
1815 targetType, connection->outboundQueue.count(),
1816 connection->waitQueue.count());
Jeff Brownffb49772014-10-10 19:01:34 -07001817 }
1818
1819 // Ensure that the dispatch queues aren't too far backed up for this event.
1820 if (eventEntry->type == EventEntry::TYPE_KEY) {
1821 // If the event is a key event, then we must wait for all previous events to
1822 // complete before delivering it because previous events may have the
1823 // side-effect of transferring focus to a different window and we want to
1824 // ensure that the following keys are sent to the new window.
1825 //
1826 // Suppose the user touches a button in a window then immediately presses "A".
1827 // If the button causes a pop-up window to appear then we want to ensure that
1828 // the "A" key is delivered to the new pop-up window. This is because users
1829 // often anticipate pending UI changes when typing on a keyboard.
1830 // To obtain this behavior, we must serialize key events with respect to all
1831 // prior input events.
1832 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001833 return StringPrintf("Waiting to send key event because the %s window has not "
Garfield Tane4fc0102019-09-11 13:16:25 -07001834 "finished processing all of the input events that were previously "
1835 "delivered to it. Outbound queue length: %d. Wait queue length: "
1836 "%d.",
1837 targetType, connection->outboundQueue.count(),
1838 connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 }
Jeff Brownffb49772014-10-10 19:01:34 -07001840 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 // Touch events can always be sent to a window immediately because the user intended
1842 // to touch whatever was visible at the time. Even if focus changes or a new
1843 // window appears moments later, the touch event was meant to be delivered to
1844 // whatever window happened to be on screen at the time.
1845 //
1846 // Generic motion events, such as trackball or joystick events are a little trickier.
1847 // Like key events, generic motion events are delivered to the focused window.
1848 // Unlike key events, generic motion events don't tend to transfer focus to other
1849 // windows and it is not important for them to be serialized. So we prefer to deliver
1850 // generic motion events as soon as possible to improve efficiency and reduce lag
1851 // through batching.
1852 //
1853 // The one case where we pause input event delivery is when the wait queue is piling
1854 // up with lots of events because the application is not responding.
1855 // This condition ensures that ANRs are detected reliably.
Garfield Tane4fc0102019-09-11 13:16:25 -07001856 if (!connection->waitQueue.isEmpty() &&
1857 currentTime >= connection->waitQueue.head->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001858 return StringPrintf("Waiting to send non-key event because the %s window has not "
Garfield Tane4fc0102019-09-11 13:16:25 -07001859 "finished processing certain input events that were delivered to "
1860 "it over "
1861 "%0.1fms ago. Wait queue length: %d. Wait queue head age: "
1862 "%0.1fms.",
1863 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1864 connection->waitQueue.count(),
1865 (currentTime - connection->waitQueue.head->deliveryTime) *
1866 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 }
1868 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001869 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870}
1871
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001872std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 const sp<InputApplicationHandle>& applicationHandle,
1874 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001875 if (applicationHandle != nullptr) {
1876 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001877 std::string label(applicationHandle->getName());
1878 label += " - ";
1879 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880 return label;
1881 } else {
1882 return applicationHandle->getName();
1883 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001884 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 return windowHandle->getName();
1886 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001887 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 }
1889}
1890
1891void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001892 int32_t displayId = getTargetDisplayId(eventEntry);
1893 sp<InputWindowHandle> focusedWindowHandle =
1894 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1895 if (focusedWindowHandle != nullptr) {
1896 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1898#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001899 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900#endif
1901 return;
1902 }
1903 }
1904
1905 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1906 switch (eventEntry->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001907 case EventEntry::TYPE_MOTION: {
1908 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1909 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1910 return;
1911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912
Garfield Tane4fc0102019-09-11 13:16:25 -07001913 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1914 eventType = USER_ACTIVITY_EVENT_TOUCH;
1915 }
1916 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 }
Garfield Tane4fc0102019-09-11 13:16:25 -07001918 case EventEntry::TYPE_KEY: {
1919 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1920 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1921 return;
1922 }
1923 eventType = USER_ACTIVITY_EVENT_BUTTON;
1924 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 }
1927
Garfield Tane4fc0102019-09-11 13:16:25 -07001928 CommandEntry* commandEntry =
1929 postCommandLocked(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 commandEntry->eventTime = eventEntry->eventTime;
1931 commandEntry->userActivityEventType = eventType;
1932}
1933
1934void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07001935 const sp<Connection>& connection,
1936 EventEntry* eventEntry,
1937 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001938 if (ATRACE_ENABLED()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001939 std::string message =
1940 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
1941 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00001942 ATRACE_NAME(message.c_str());
1943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944#if DEBUG_DISPATCH_CYCLE
1945 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Garfield Tane4fc0102019-09-11 13:16:25 -07001946 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1947 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
1948 connection->getInputChannelName().c_str(), inputTarget->flags, inputTarget->xOffset,
1949 inputTarget->yOffset, inputTarget->globalScaleFactor, inputTarget->windowXScale,
1950 inputTarget->windowYScale, inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951#endif
1952
1953 // Skip this event if the connection status is not normal.
1954 // We don't want to enqueue additional outbound events if the connection is broken.
1955 if (connection->status != Connection::STATUS_NORMAL) {
1956#if DEBUG_DISPATCH_CYCLE
1957 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tane4fc0102019-09-11 13:16:25 -07001958 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959#endif
1960 return;
1961 }
1962
1963 // Split a motion event if needed.
1964 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1965 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1966
1967 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1968 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001969 MotionEntry* splitMotionEntry =
1970 splitMotionEvent(originalMotionEntry, inputTarget->pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 if (!splitMotionEntry) {
1972 return; // split event was dropped
1973 }
1974#if DEBUG_FOCUS
Garfield Tane4fc0102019-09-11 13:16:25 -07001975 ALOGD("channel '%s' ~ Split motion event.", connection->getInputChannelName().c_str());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001976 logOutboundMotionDetails(" ", splitMotionEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977#endif
Garfield Tane4fc0102019-09-11 13:16:25 -07001978 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 splitMotionEntry->release();
1980 return;
1981 }
1982 }
1983
1984 // Not splitting. Enqueue dispatch entries for the event as is.
1985 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1986}
1987
1988void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07001989 const sp<Connection>& connection,
1990 EventEntry* eventEntry,
1991 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001992 if (ATRACE_ENABLED()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07001993 std::string message =
1994 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32
1995 ")",
1996 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00001997 ATRACE_NAME(message.c_str());
1998 }
1999
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 bool wasEmpty = connection->outboundQueue.isEmpty();
2001
2002 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002003 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tane4fc0102019-09-11 13:16:25 -07002004 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002005 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tane4fc0102019-09-11 13:16:25 -07002006 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002007 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tane4fc0102019-09-11 13:16:25 -07002008 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002009 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tane4fc0102019-09-11 13:16:25 -07002010 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002011 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tane4fc0102019-09-11 13:16:25 -07002012 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002013 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tane4fc0102019-09-11 13:16:25 -07002014 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015
2016 // If the outbound queue was previously empty, start the dispatch cycle going.
2017 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
2018 startDispatchCycleLocked(currentTime, connection);
2019 }
2020}
2021
Garfield Tane4fc0102019-09-11 13:16:25 -07002022void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2023 EventEntry* eventEntry,
2024 const InputTarget* inputTarget,
2025 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002026 if (ATRACE_ENABLED()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002027 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2028 connection->getInputChannelName().c_str(),
2029 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002030 ATRACE_NAME(message.c_str());
2031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032 int32_t inputTargetFlags = inputTarget->flags;
2033 if (!(inputTargetFlags & dispatchMode)) {
2034 return;
2035 }
2036 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2037
2038 // This is a new event.
2039 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Garfield Tane4fc0102019-09-11 13:16:25 -07002040 DispatchEntry* dispatchEntry =
2041 new DispatchEntry(eventEntry, // increments ref
2042 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
2043 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2044 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045
2046 // Apply target flags and update the connection's input state.
2047 switch (eventEntry->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002048 case EventEntry::TYPE_KEY: {
2049 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2050 dispatchEntry->resolvedAction = keyEntry->action;
2051 dispatchEntry->resolvedFlags = keyEntry->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052
Garfield Tane4fc0102019-09-11 13:16:25 -07002053 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2054 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055#if DEBUG_DISPATCH_CYCLE
Garfield Tane4fc0102019-09-11 13:16:25 -07002056 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2057 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058#endif
Garfield Tane4fc0102019-09-11 13:16:25 -07002059 delete dispatchEntry;
2060 return; // skip the inconsistent event
2061 }
2062 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064
Garfield Tane4fc0102019-09-11 13:16:25 -07002065 case EventEntry::TYPE_MOTION: {
2066 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2067 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2068 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2069 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2070 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2071 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2072 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2073 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2074 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2075 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2076 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2077 } else {
2078 dispatchEntry->resolvedAction = motionEntry->action;
2079 }
2080 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
2081 !connection->inputState.isHovering(motionEntry->deviceId, motionEntry->source,
2082 motionEntry->displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083#if DEBUG_DISPATCH_CYCLE
Garfield Tane4fc0102019-09-11 13:16:25 -07002084 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2085 "event",
2086 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087#endif
Garfield Tane4fc0102019-09-11 13:16:25 -07002088 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090
Garfield Tane4fc0102019-09-11 13:16:25 -07002091 dispatchEntry->resolvedFlags = motionEntry->flags;
2092 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2093 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2094 }
2095 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2096 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098
Garfield Tane4fc0102019-09-11 13:16:25 -07002099 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2100 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101#if DEBUG_DISPATCH_CYCLE
Garfield Tane4fc0102019-09-11 13:16:25 -07002102 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2103 "event",
2104 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105#endif
Garfield Tane4fc0102019-09-11 13:16:25 -07002106 delete dispatchEntry;
2107 return; // skip the inconsistent event
2108 }
2109
2110 dispatchPointerDownOutsideFocus(motionEntry->source, dispatchEntry->resolvedAction,
2111 inputTarget->inputChannel->getToken());
2112
2113 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 }
2116
2117 // Remember that we are waiting for this dispatch to complete.
2118 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002119 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 }
2121
2122 // Enqueue the dispatch entry.
2123 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002124 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002125}
2126
chaviwfd6d3512019-03-25 13:23:49 -07002127void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tane4fc0102019-09-11 13:16:25 -07002128 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002129 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002130 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2131 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002132 return;
2133 }
2134
2135 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2136 if (inputWindowHandle == nullptr) {
2137 return;
2138 }
2139
chaviw8c9cf542019-03-25 13:02:48 -07002140 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002141 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002142
2143 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2144
2145 if (!hasFocusChanged) {
2146 return;
2147 }
2148
Garfield Tane4fc0102019-09-11 13:16:25 -07002149 CommandEntry* commandEntry =
2150 postCommandLocked(&InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002151 commandEntry->newToken = newToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152}
2153
2154void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07002155 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002156 if (ATRACE_ENABLED()) {
2157 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tane4fc0102019-09-11 13:16:25 -07002158 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002159 ATRACE_NAME(message.c_str());
2160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161#if DEBUG_DISPATCH_CYCLE
Garfield Tane4fc0102019-09-11 13:16:25 -07002162 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163#endif
2164
Garfield Tane4fc0102019-09-11 13:16:25 -07002165 while (connection->status == Connection::STATUS_NORMAL &&
2166 !connection->outboundQueue.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2168 dispatchEntry->deliveryTime = currentTime;
2169
2170 // Publish the event.
2171 status_t status;
2172 EventEntry* eventEntry = dispatchEntry->eventEntry;
2173 switch (eventEntry->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002174 case EventEntry::TYPE_KEY: {
2175 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176
Garfield Tane4fc0102019-09-11 13:16:25 -07002177 // Publish the key event.
2178 status = connection->inputPublisher
2179 .publishKeyEvent(dispatchEntry->seq, keyEntry->deviceId,
2180 keyEntry->source, keyEntry->displayId,
2181 dispatchEntry->resolvedAction,
2182 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2183 keyEntry->scanCode, keyEntry->metaState,
2184 keyEntry->repeatCount, keyEntry->downTime,
2185 keyEntry->eventTime);
2186 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 }
2188
Garfield Tane4fc0102019-09-11 13:16:25 -07002189 case EventEntry::TYPE_MOTION: {
2190 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191
Garfield Tane4fc0102019-09-11 13:16:25 -07002192 PointerCoords scaledCoords[MAX_POINTERS];
2193 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2194
2195 // Set the X and Y offset depending on the input source.
2196 float xOffset, yOffset;
2197 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2198 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2199 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2200 float wxs = dispatchEntry->windowXScale;
2201 float wys = dispatchEntry->windowYScale;
2202 xOffset = dispatchEntry->xOffset * wxs;
2203 yOffset = dispatchEntry->yOffset * wys;
2204 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
2205 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2206 scaledCoords[i] = motionEntry->pointerCoords[i];
2207 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
2208 }
2209 usingCoords = scaledCoords;
2210 }
2211 } else {
2212 xOffset = 0.0f;
2213 yOffset = 0.0f;
2214
2215 // We don't want the dispatch target to know.
2216 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2217 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2218 scaledCoords[i].clear();
2219 }
2220 usingCoords = scaledCoords;
2221 }
2222 }
2223
2224 // Publish the motion event.
2225 status = connection->inputPublisher
2226 .publishMotionEvent(dispatchEntry->seq, motionEntry->deviceId,
2227 motionEntry->source, motionEntry->displayId,
2228 dispatchEntry->resolvedAction,
2229 motionEntry->actionButton,
2230 dispatchEntry->resolvedFlags,
2231 motionEntry->edgeFlags, motionEntry->metaState,
2232 motionEntry->buttonState,
2233 motionEntry->classification, xOffset, yOffset,
2234 motionEntry->xPrecision,
2235 motionEntry->yPrecision, motionEntry->downTime,
2236 motionEntry->eventTime,
2237 motionEntry->pointerCount,
2238 motionEntry->pointerProperties, usingCoords);
2239 break;
2240 }
2241
2242 default:
2243 ALOG_ASSERT(false);
2244 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 }
2246
2247 // Check the result.
2248 if (status) {
2249 if (status == WOULD_BLOCK) {
2250 if (connection->waitQueue.isEmpty()) {
2251 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tane4fc0102019-09-11 13:16:25 -07002252 "This is unexpected because the wait queue is empty, so the pipe "
2253 "should be empty and we shouldn't have any problems writing an "
2254 "event to it, status=%d",
2255 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2257 } else {
2258 // Pipe is full and we are waiting for the app to finish process some events
2259 // before sending more events to it.
2260#if DEBUG_DISPATCH_CYCLE
2261 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tane4fc0102019-09-11 13:16:25 -07002262 "waiting for the application to catch up",
2263 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264#endif
2265 connection->inputPublisherBlocked = true;
2266 }
2267 } else {
2268 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tane4fc0102019-09-11 13:16:25 -07002269 "status=%d",
2270 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2272 }
2273 return;
2274 }
2275
2276 // Re-enqueue the event on the wait queue.
2277 connection->outboundQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002278 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 connection->waitQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002280 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 }
2282}
2283
2284void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07002285 const sp<Connection>& connection, uint32_t seq,
2286 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287#if DEBUG_DISPATCH_CYCLE
2288 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tane4fc0102019-09-11 13:16:25 -07002289 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290#endif
2291
2292 connection->inputPublisherBlocked = false;
2293
Garfield Tane4fc0102019-09-11 13:16:25 -07002294 if (connection->status == Connection::STATUS_BROKEN ||
2295 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 return;
2297 }
2298
2299 // Notify other system components and prepare to start the next dispatch cycle.
2300 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2301}
2302
2303void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tane4fc0102019-09-11 13:16:25 -07002304 const sp<Connection>& connection,
2305 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306#if DEBUG_DISPATCH_CYCLE
2307 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tane4fc0102019-09-11 13:16:25 -07002308 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309#endif
2310
2311 // Clear the dispatch queues.
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002312 drainDispatchQueue(&connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002313 traceOutboundQueueLength(connection);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002314 drainDispatchQueue(&connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002315 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316
2317 // The connection appears to be unrecoverably broken.
2318 // Ignore already broken or zombie connections.
2319 if (connection->status == Connection::STATUS_NORMAL) {
2320 connection->status = Connection::STATUS_BROKEN;
2321
2322 if (notify) {
2323 // Notify other system components.
2324 onDispatchCycleBrokenLocked(currentTime, connection);
2325 }
2326 }
2327}
2328
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002329void InputDispatcher::drainDispatchQueue(Queue<DispatchEntry>* queue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 while (!queue->isEmpty()) {
2331 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002332 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 }
2334}
2335
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002336void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002338 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 }
2340 delete dispatchEntry;
2341}
2342
2343int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2344 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2345
2346 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002347 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348
2349 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2350 if (connectionIndex < 0) {
2351 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tane4fc0102019-09-11 13:16:25 -07002352 "fd=%d, events=0x%x",
2353 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 return 0; // remove the callback
2355 }
2356
2357 bool notify;
2358 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2359 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2360 if (!(events & ALOOPER_EVENT_INPUT)) {
2361 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tane4fc0102019-09-11 13:16:25 -07002362 "events=0x%x",
2363 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364 return 1;
2365 }
2366
2367 nsecs_t currentTime = now();
2368 bool gotOne = false;
2369 status_t status;
2370 for (;;) {
2371 uint32_t seq;
2372 bool handled;
2373 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2374 if (status) {
2375 break;
2376 }
2377 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2378 gotOne = true;
2379 }
2380 if (gotOne) {
2381 d->runCommandsLockedInterruptible();
2382 if (status == WOULD_BLOCK) {
2383 return 1;
2384 }
2385 }
2386
2387 notify = status != DEAD_OBJECT || !connection->monitor;
2388 if (notify) {
2389 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tane4fc0102019-09-11 13:16:25 -07002390 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391 }
2392 } else {
2393 // Monitor channels are never explicitly unregistered.
2394 // We do it automatically when the remote endpoint is closed so don't warn
2395 // about them.
2396 notify = !connection->monitor;
2397 if (notify) {
2398 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tane4fc0102019-09-11 13:16:25 -07002399 "events=0x%x",
2400 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401 }
2402 }
2403
2404 // Unregister the channel.
2405 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2406 return 0; // remove the callback
Garfield Tane4fc0102019-09-11 13:16:25 -07002407 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408}
2409
Garfield Tane4fc0102019-09-11 13:16:25 -07002410void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002411 const CancelationOptions& options) {
2412 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002413 synthesizeCancelationEventsForConnectionLocked(mConnectionsByFd.valueAt(i), options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414 }
2415}
2416
Garfield Tane4fc0102019-09-11 13:16:25 -07002417void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002418 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002419 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2420 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2421}
2422
2423void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2424 const CancelationOptions& options,
2425 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2426 for (const auto& it : monitorsByDisplay) {
2427 const std::vector<Monitor>& monitors = it.second;
2428 for (const Monitor& monitor : monitors) {
2429 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002430 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002431 }
2432}
2433
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2435 const sp<InputChannel>& channel, const CancelationOptions& options) {
2436 ssize_t index = getConnectionIndexLocked(channel);
2437 if (index >= 0) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002438 synthesizeCancelationEventsForConnectionLocked(mConnectionsByFd.valueAt(index), options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439 }
2440}
2441
2442void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2443 const sp<Connection>& connection, const CancelationOptions& options) {
2444 if (connection->status == Connection::STATUS_BROKEN) {
2445 return;
2446 }
2447
2448 nsecs_t currentTime = now();
2449
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002450 std::vector<EventEntry*> cancelationEvents;
Garfield Tane4fc0102019-09-11 13:16:25 -07002451 connection->inputState.synthesizeCancelationEvents(currentTime, cancelationEvents, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002453 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002455 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Garfield Tane4fc0102019-09-11 13:16:25 -07002456 "with reality: %s, mode=%d.",
2457 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2458 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459#endif
2460 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002461 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 switch (cancelationEventEntry->type) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002463 case EventEntry::TYPE_KEY:
2464 logOutboundKeyDetails("cancel - ",
2465 static_cast<KeyEntry*>(cancelationEventEntry));
2466 break;
2467 case EventEntry::TYPE_MOTION:
2468 logOutboundMotionDetails("cancel - ",
2469 static_cast<MotionEntry*>(cancelationEventEntry));
2470 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 }
2472
2473 InputTarget target;
Garfield Tane4fc0102019-09-11 13:16:25 -07002474 sp<InputWindowHandle> windowHandle =
2475 getWindowHandleLocked(connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002476 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2478 target.xOffset = -windowInfo->frameLeft;
2479 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002480 target.globalScaleFactor = windowInfo->globalScaleFactor;
2481 target.windowXScale = windowInfo->windowXScale;
2482 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 } else {
2484 target.xOffset = 0;
2485 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002486 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487 }
2488 target.inputChannel = connection->inputChannel;
2489 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2490
chaviw8c9cf542019-03-25 13:02:48 -07002491 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Garfield Tane4fc0102019-09-11 13:16:25 -07002492 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493
2494 cancelationEventEntry->release();
2495 }
2496
2497 startDispatchCycleLocked(currentTime, connection);
2498 }
2499}
2500
Garfield Tan73007b62019-08-29 17:28:41 -07002501MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry,
2502 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 ALOG_ASSERT(pointerIds.value != 0);
2504
2505 uint32_t splitPointerIndexMap[MAX_POINTERS];
2506 PointerProperties splitPointerProperties[MAX_POINTERS];
2507 PointerCoords splitPointerCoords[MAX_POINTERS];
2508
2509 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2510 uint32_t splitPointerCount = 0;
2511
2512 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tane4fc0102019-09-11 13:16:25 -07002513 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514 const PointerProperties& pointerProperties =
2515 originalMotionEntry->pointerProperties[originalPointerIndex];
2516 uint32_t pointerId = uint32_t(pointerProperties.id);
2517 if (pointerIds.hasBit(pointerId)) {
2518 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2519 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2520 splitPointerCoords[splitPointerCount].copyFrom(
2521 originalMotionEntry->pointerCoords[originalPointerIndex]);
2522 splitPointerCount += 1;
2523 }
2524 }
2525
2526 if (splitPointerCount != pointerIds.count()) {
2527 // This is bad. We are missing some of the pointers that we expected to deliver.
2528 // Most likely this indicates that we received an ACTION_MOVE events that has
2529 // different pointer ids than we expected based on the previous ACTION_DOWN
2530 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2531 // in this way.
2532 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tane4fc0102019-09-11 13:16:25 -07002533 "we expected there to be %d pointers. This probably means we received "
2534 "a broken sequence of pointer ids from the input device.",
2535 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002536 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537 }
2538
2539 int32_t action = originalMotionEntry->action;
2540 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tane4fc0102019-09-11 13:16:25 -07002541 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2542 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2544 const PointerProperties& pointerProperties =
2545 originalMotionEntry->pointerProperties[originalPointerIndex];
2546 uint32_t pointerId = uint32_t(pointerProperties.id);
2547 if (pointerIds.hasBit(pointerId)) {
2548 if (pointerIds.count() == 1) {
2549 // The first/last pointer went down/up.
2550 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tane4fc0102019-09-11 13:16:25 -07002551 ? AMOTION_EVENT_ACTION_DOWN
2552 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 } else {
2554 // A secondary pointer went down/up.
2555 uint32_t splitPointerIndex = 0;
2556 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2557 splitPointerIndex += 1;
2558 }
Garfield Tane4fc0102019-09-11 13:16:25 -07002559 action = maskedAction |
2560 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561 }
2562 } else {
2563 // An unrelated pointer changed.
2564 action = AMOTION_EVENT_ACTION_MOVE;
2565 }
2566 }
2567
Garfield Tane4fc0102019-09-11 13:16:25 -07002568 MotionEntry* splitMotionEntry =
2569 new MotionEntry(originalMotionEntry->sequenceNum, originalMotionEntry->eventTime,
2570 originalMotionEntry->deviceId, originalMotionEntry->source,
2571 originalMotionEntry->displayId, originalMotionEntry->policyFlags,
2572 action, originalMotionEntry->actionButton, originalMotionEntry->flags,
2573 originalMotionEntry->metaState, originalMotionEntry->buttonState,
2574 originalMotionEntry->classification, originalMotionEntry->edgeFlags,
2575 originalMotionEntry->xPrecision, originalMotionEntry->yPrecision,
2576 originalMotionEntry->downTime, splitPointerCount,
2577 splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578
2579 if (originalMotionEntry->injectionState) {
2580 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2581 splitMotionEntry->injectionState->refCount += 1;
2582 }
2583
2584 return splitMotionEntry;
2585}
2586
2587void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2588#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002589 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002590#endif
2591
2592 bool needWake;
2593 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002594 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595
Prabir Pradhan42611e02018-11-27 14:04:02 -08002596 ConfigurationChangedEntry* newEntry =
2597 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 needWake = enqueueInboundEventLocked(newEntry);
2599 } // release lock
2600
2601 if (needWake) {
2602 mLooper->wake();
2603 }
2604}
2605
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002606/**
2607 * If one of the meta shortcuts is detected, process them here:
2608 * Meta + Backspace -> generate BACK
2609 * Meta + Enter -> generate HOME
2610 * This will potentially overwrite keyCode and metaState.
2611 */
2612void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tane4fc0102019-09-11 13:16:25 -07002613 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002614 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2615 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2616 if (keyCode == AKEYCODE_DEL) {
2617 newKeyCode = AKEYCODE_BACK;
2618 } else if (keyCode == AKEYCODE_ENTER) {
2619 newKeyCode = AKEYCODE_HOME;
2620 }
2621 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002622 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002623 struct KeyReplacement replacement = {keyCode, deviceId};
2624 mReplacedKeys.add(replacement, newKeyCode);
2625 keyCode = newKeyCode;
2626 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2627 }
2628 } else if (action == AKEY_EVENT_ACTION_UP) {
2629 // In order to maintain a consistent stream of up and down events, check to see if the key
2630 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2631 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002632 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002633 struct KeyReplacement replacement = {keyCode, deviceId};
2634 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2635 if (index >= 0) {
2636 keyCode = mReplacedKeys.valueAt(index);
2637 mReplacedKeys.removeItemsAt(index);
2638 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2639 }
2640 }
2641}
2642
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2644#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tane4fc0102019-09-11 13:16:25 -07002645 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2646 "policyFlags=0x%x, action=0x%x, "
2647 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2648 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2649 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2650 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651#endif
2652 if (!validateKeyEvent(args->action)) {
2653 return;
2654 }
2655
2656 uint32_t policyFlags = args->policyFlags;
2657 int32_t flags = args->flags;
2658 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002659 // InputDispatcher tracks and generates key repeats on behalf of
2660 // whatever notifies it, so repeatCount should always be set to 0
2661 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2663 policyFlags |= POLICY_FLAG_VIRTUAL;
2664 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002666 if (policyFlags & POLICY_FLAG_FUNCTION) {
2667 metaState |= AMETA_FUNCTION_ON;
2668 }
2669
2670 policyFlags |= POLICY_FLAG_TRUSTED;
2671
Michael Wright78f24442014-08-06 15:55:28 -07002672 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002673 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002674
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675 KeyEvent event;
Garfield Tane4fc0102019-09-11 13:16:25 -07002676 event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2677 args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678
Michael Wright2b3c3302018-03-02 17:19:13 +00002679 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002681 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2682 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tane4fc0102019-09-11 13:16:25 -07002683 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002684 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 bool needWake;
2687 { // acquire lock
2688 mLock.lock();
2689
2690 if (shouldSendKeyToInputFilterLocked(args)) {
2691 mLock.unlock();
2692
2693 policyFlags |= POLICY_FLAG_FILTERED;
2694 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2695 return; // event was consumed by the filter
2696 }
2697
2698 mLock.lock();
2699 }
2700
Garfield Tane4fc0102019-09-11 13:16:25 -07002701 KeyEntry* newEntry =
2702 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2703 args->displayId, policyFlags, args->action, flags, keyCode,
2704 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705
2706 needWake = enqueueInboundEventLocked(newEntry);
2707 mLock.unlock();
2708 } // release lock
2709
2710 if (needWake) {
2711 mLooper->wake();
2712 }
2713}
2714
2715bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2716 return mInputFilterEnabled;
2717}
2718
2719void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2720#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002721 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tane4fc0102019-09-11 13:16:25 -07002722 ", policyFlags=0x%x, "
2723 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
2724 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2725 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2726 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
2727 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728 for (uint32_t i = 0; i < args->pointerCount; i++) {
2729 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07002730 "x=%f, y=%f, pressure=%f, size=%f, "
2731 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2732 "orientation=%f",
2733 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2734 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2735 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2736 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2737 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2738 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2739 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2740 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2741 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2742 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743 }
2744#endif
Garfield Tane4fc0102019-09-11 13:16:25 -07002745 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2746 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747 return;
2748 }
2749
2750 uint32_t policyFlags = args->policyFlags;
2751 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002752
2753 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002754 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002755 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2756 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tane4fc0102019-09-11 13:16:25 -07002757 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759
2760 bool needWake;
2761 { // acquire lock
2762 mLock.lock();
2763
2764 if (shouldSendMotionToInputFilterLocked(args)) {
2765 mLock.unlock();
2766
2767 MotionEvent event;
Garfield Tane4fc0102019-09-11 13:16:25 -07002768 event.initialize(args->deviceId, args->source, args->displayId, args->action,
2769 args->actionButton, args->flags, args->edgeFlags, args->metaState,
2770 args->buttonState, args->classification, 0, 0, args->xPrecision,
2771 args->yPrecision, args->downTime, args->eventTime, args->pointerCount,
2772 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773
2774 policyFlags |= POLICY_FLAG_FILTERED;
2775 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2776 return; // event was consumed by the filter
2777 }
2778
2779 mLock.lock();
2780 }
2781
2782 // Just enqueue a new motion event.
Garfield Tane4fc0102019-09-11 13:16:25 -07002783 MotionEntry* newEntry =
2784 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2785 args->displayId, policyFlags, args->action, args->actionButton,
2786 args->flags, args->metaState, args->buttonState,
2787 args->classification, args->edgeFlags, args->xPrecision,
2788 args->yPrecision, args->downTime, args->pointerCount,
2789 args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790
2791 needWake = enqueueInboundEventLocked(newEntry);
2792 mLock.unlock();
2793 } // release lock
2794
2795 if (needWake) {
2796 mLooper->wake();
2797 }
2798}
2799
2800bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002801 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802}
2803
2804void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2805#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002806 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tane4fc0102019-09-11 13:16:25 -07002807 "switchMask=0x%08x",
2808 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809#endif
2810
2811 uint32_t policyFlags = args->policyFlags;
2812 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tane4fc0102019-09-11 13:16:25 -07002813 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814}
2815
2816void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2817#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tane4fc0102019-09-11 13:16:25 -07002818 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
2819 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820#endif
2821
2822 bool needWake;
2823 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002824 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825
Prabir Pradhan42611e02018-11-27 14:04:02 -08002826 DeviceResetEntry* newEntry =
2827 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 needWake = enqueueInboundEventLocked(newEntry);
2829 } // release lock
2830
2831 if (needWake) {
2832 mLooper->wake();
2833 }
2834}
2835
Garfield Tane4fc0102019-09-11 13:16:25 -07002836int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
2837 int32_t injectorUid, int32_t syncMode,
2838 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839#if DEBUG_INBOUND_EVENT_DETAILS
2840 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07002841 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2842 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843#endif
2844
2845 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2846
2847 policyFlags |= POLICY_FLAG_INJECTED;
2848 if (hasInjectionPermission(injectorPid, injectorUid)) {
2849 policyFlags |= POLICY_FLAG_TRUSTED;
2850 }
2851
2852 EventEntry* firstInjectedEntry;
2853 EventEntry* lastInjectedEntry;
2854 switch (event->getType()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07002855 case AINPUT_EVENT_TYPE_KEY: {
2856 KeyEvent keyEvent;
2857 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2858 int32_t action = keyEvent.getAction();
2859 if (!validateKeyEvent(action)) {
2860 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002861 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862
Garfield Tane4fc0102019-09-11 13:16:25 -07002863 int32_t flags = keyEvent.getFlags();
2864 int32_t keyCode = keyEvent.getKeyCode();
2865 int32_t metaState = keyEvent.getMetaState();
2866 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2867 /*byref*/ keyCode, /*byref*/ metaState);
2868 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
2869 keyEvent.getDisplayId(), action, flags, keyCode,
2870 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
2871 keyEvent.getDownTime(), keyEvent.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872
Garfield Tane4fc0102019-09-11 13:16:25 -07002873 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2874 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00002875 }
Garfield Tane4fc0102019-09-11 13:16:25 -07002876
2877 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2878 android::base::Timer t;
2879 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
2880 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2881 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2882 std::to_string(t.duration().count()).c_str());
2883 }
2884 }
2885
2886 mLock.lock();
2887 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2888 keyEvent.getEventTime(), keyEvent.getDeviceId(),
2889 keyEvent.getSource(), keyEvent.getDisplayId(),
2890 policyFlags, action, flags, keyEvent.getKeyCode(),
2891 keyEvent.getScanCode(), keyEvent.getMetaState(),
2892 keyEvent.getRepeatCount(), keyEvent.getDownTime());
2893 lastInjectedEntry = firstInjectedEntry;
2894 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895 }
2896
Garfield Tane4fc0102019-09-11 13:16:25 -07002897 case AINPUT_EVENT_TYPE_MOTION: {
2898 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2899 int32_t action = motionEvent->getAction();
2900 size_t pointerCount = motionEvent->getPointerCount();
2901 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2902 int32_t actionButton = motionEvent->getActionButton();
2903 int32_t displayId = motionEvent->getDisplayId();
2904 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
2905 return INPUT_EVENT_INJECTION_FAILED;
2906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907
Garfield Tane4fc0102019-09-11 13:16:25 -07002908 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2909 nsecs_t eventTime = motionEvent->getEventTime();
2910 android::base::Timer t;
2911 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
2912 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2913 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2914 std::to_string(t.duration().count()).c_str());
2915 }
2916 }
2917
2918 mLock.lock();
2919 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2920 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2921 firstInjectedEntry =
2922 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2923 motionEvent->getDeviceId(), motionEvent->getSource(),
2924 motionEvent->getDisplayId(), policyFlags, action, actionButton,
2925 motionEvent->getFlags(), motionEvent->getMetaState(),
2926 motionEvent->getButtonState(), motionEvent->getClassification(),
2927 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
2928 motionEvent->getYPrecision(), motionEvent->getDownTime(),
2929 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2930 motionEvent->getXOffset(), motionEvent->getYOffset());
2931 lastInjectedEntry = firstInjectedEntry;
2932 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2933 sampleEventTimes += 1;
2934 samplePointerCoords += pointerCount;
2935 MotionEntry* nextInjectedEntry =
2936 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2937 motionEvent->getDeviceId(), motionEvent->getSource(),
2938 motionEvent->getDisplayId(), policyFlags, action,
2939 actionButton, motionEvent->getFlags(),
2940 motionEvent->getMetaState(), motionEvent->getButtonState(),
2941 motionEvent->getClassification(),
2942 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
2943 motionEvent->getYPrecision(), motionEvent->getDownTime(),
2944 uint32_t(pointerCount), pointerProperties,
2945 samplePointerCoords, motionEvent->getXOffset(),
2946 motionEvent->getYOffset());
2947 lastInjectedEntry->next = nextInjectedEntry;
2948 lastInjectedEntry = nextInjectedEntry;
2949 }
2950 break;
2951 }
2952
2953 default:
2954 ALOGW("Cannot inject event of type %d", event->getType());
2955 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956 }
2957
2958 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2959 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2960 injectionState->injectionIsAsync = true;
2961 }
2962
2963 injectionState->refCount += 1;
2964 lastInjectedEntry->injectionState = injectionState;
2965
2966 bool needWake = false;
Garfield Tane4fc0102019-09-11 13:16:25 -07002967 for (EventEntry* entry = firstInjectedEntry; entry != nullptr;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968 EventEntry* nextEntry = entry->next;
2969 needWake |= enqueueInboundEventLocked(entry);
2970 entry = nextEntry;
2971 }
2972
2973 mLock.unlock();
2974
2975 if (needWake) {
2976 mLooper->wake();
2977 }
2978
2979 int32_t injectionResult;
2980 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002981 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002982
2983 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2984 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2985 } else {
2986 for (;;) {
2987 injectionResult = injectionState->injectionResult;
2988 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2989 break;
2990 }
2991
2992 nsecs_t remainingTimeout = endTime - now();
2993 if (remainingTimeout <= 0) {
2994#if DEBUG_INJECTION
2995 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tane4fc0102019-09-11 13:16:25 -07002996 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997#endif
2998 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2999 break;
3000 }
3001
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003002 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003 }
3004
Garfield Tane4fc0102019-09-11 13:16:25 -07003005 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3006 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007 while (injectionState->pendingForegroundDispatches != 0) {
3008#if DEBUG_INJECTION
3009 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tane4fc0102019-09-11 13:16:25 -07003010 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011#endif
3012 nsecs_t remainingTimeout = endTime - now();
3013 if (remainingTimeout <= 0) {
3014#if DEBUG_INJECTION
Garfield Tane4fc0102019-09-11 13:16:25 -07003015 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3016 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017#endif
3018 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3019 break;
3020 }
3021
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003022 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023 }
3024 }
3025 }
3026
3027 injectionState->release();
3028 } // release lock
3029
3030#if DEBUG_INJECTION
3031 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tane4fc0102019-09-11 13:16:25 -07003032 "injectorPid=%d, injectorUid=%d",
3033 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034#endif
3035
3036 return injectionResult;
3037}
3038
3039bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tane4fc0102019-09-11 13:16:25 -07003040 return injectorUid == 0 ||
3041 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042}
3043
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003044void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045 InjectionState* injectionState = entry->injectionState;
3046 if (injectionState) {
3047#if DEBUG_INJECTION
3048 ALOGD("Setting input event injection result to %d. "
Garfield Tane4fc0102019-09-11 13:16:25 -07003049 "injectorPid=%d, injectorUid=%d",
3050 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051#endif
3052
Garfield Tane4fc0102019-09-11 13:16:25 -07003053 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054 // Log the outcome since the injector did not wait for the injection result.
3055 switch (injectionResult) {
Garfield Tane4fc0102019-09-11 13:16:25 -07003056 case INPUT_EVENT_INJECTION_SUCCEEDED:
3057 ALOGV("Asynchronous input event injection succeeded.");
3058 break;
3059 case INPUT_EVENT_INJECTION_FAILED:
3060 ALOGW("Asynchronous input event injection failed.");
3061 break;
3062 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3063 ALOGW("Asynchronous input event injection permission denied.");
3064 break;
3065 case INPUT_EVENT_INJECTION_TIMED_OUT:
3066 ALOGW("Asynchronous input event injection timed out.");
3067 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068 }
3069 }
3070
3071 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003072 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073 }
3074}
3075
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003076void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077 InjectionState* injectionState = entry->injectionState;
3078 if (injectionState) {
3079 injectionState->pendingForegroundDispatches += 1;
3080 }
3081}
3082
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003083void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 InjectionState* injectionState = entry->injectionState;
3085 if (injectionState) {
3086 injectionState->pendingForegroundDispatches -= 1;
3087
3088 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003089 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090 }
3091 }
3092}
3093
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003094std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3095 int32_t displayId) const {
3096 std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>::const_iterator it =
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003097 mWindowHandlesByDisplay.find(displayId);
Garfield Tane4fc0102019-09-11 13:16:25 -07003098 if (it != mWindowHandlesByDisplay.end()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003099 return it->second;
3100 }
3101
3102 // Return an empty one if nothing found.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003103 return std::vector<sp<InputWindowHandle>>();
Arthur Hungb92218b2018-08-14 12:00:21 +08003104}
3105
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003107 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003108 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003109 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3110 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003111 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003112 return windowHandle;
3113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114 }
3115 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003116 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117}
3118
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003119bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003120 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003121 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3122 for (const sp<InputWindowHandle>& handle : windowHandles) {
3123 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003124 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003125 ALOGE("Found window %s in display %" PRId32
Garfield Tane4fc0102019-09-11 13:16:25 -07003126 ", but it should belong to display %" PRId32,
3127 windowHandle->getName().c_str(), it.first,
3128 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003129 }
3130 return true;
3131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 }
3133 }
3134 return false;
3135}
3136
Robert Carr5c8a0262018-10-03 16:30:44 -07003137sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3138 size_t count = mInputChannelsByToken.count(token);
3139 if (count == 0) {
3140 return nullptr;
3141 }
3142 return mInputChannelsByToken.at(token);
3143}
3144
Arthur Hungb92218b2018-08-14 12:00:21 +08003145/**
3146 * Called from InputManagerService, update window handle list by displayId that can receive input.
3147 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3148 * If set an empty list, remove all handles from the specific display.
3149 * For focused handle, check if need to change and send a cancel event to previous one.
3150 * For removed handle, check if need to send a cancel event if already in touch.
3151 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003152void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
Garfield Tane4fc0102019-09-11 13:16:25 -07003153 int32_t displayId,
3154 const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003156 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157#endif
3158 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003159 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160
Arthur Hungb92218b2018-08-14 12:00:21 +08003161 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003162 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3163 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164
Tiger Huang721e26f2018-07-24 22:26:19 +08003165 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003167
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003168 if (inputWindowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003169 // Remove all handles on a display if there are no windows left.
3170 mWindowHandlesByDisplay.erase(displayId);
3171 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003172 // Since we compare the pointer of input window handles across window updates, we need
3173 // to make sure the handle object for the same window stays unchanged across updates.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003174 const std::vector<sp<InputWindowHandle>>& oldHandles =
3175 mWindowHandlesByDisplay[displayId];
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003176 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003177 for (const sp<InputWindowHandle>& handle : oldHandles) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003178 oldHandlesByTokens[handle->getToken()] = handle;
3179 }
3180
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003181 std::vector<sp<InputWindowHandle>> newHandles;
3182 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
Siarhei Vishniakou3a179dc2019-01-30 09:50:04 -08003183 if (!handle->updateInfo()) {
3184 // handle no longer valid
3185 continue;
3186 }
3187 const InputWindowInfo* info = handle->getInfo();
3188
3189 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3190 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3191 const bool noInputChannel =
3192 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3193 const bool canReceiveInput =
3194 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3195 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3196 if (canReceiveInput && !noInputChannel) {
3197 ALOGE("Window handle %s has no registered input channel",
3198 handle->getName().c_str());
3199 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003200 continue;
3201 }
3202
Siarhei Vishniakou3a179dc2019-01-30 09:50:04 -08003203 if (info->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003204 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Siarhei Vishniakou3a179dc2019-01-30 09:50:04 -08003205 handle->getName().c_str(), displayId, info->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003206 continue;
3207 }
3208
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003209 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3210 const sp<InputWindowHandle> oldHandle =
3211 oldHandlesByTokens.at(handle->getToken());
3212 oldHandle->updateFrom(handle);
3213 newHandles.push_back(oldHandle);
3214 } else {
3215 newHandles.push_back(handle);
3216 }
3217 }
3218
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003219 for (const sp<InputWindowHandle>& windowHandle : newHandles) {
Arthur Hung7ab76b12019-01-09 19:17:20 +08003220 // Set newFocusedWindowHandle to the top most focused window instead of the last one
Garfield Tane4fc0102019-09-11 13:16:25 -07003221 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3222 windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003223 newFocusedWindowHandle = windowHandle;
3224 }
3225 if (windowHandle == mLastHoverWindowHandle) {
3226 foundHoveredWindow = true;
3227 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003228 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003229
3230 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003231 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232 }
3233
3234 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003235 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236 }
3237
Tiger Huang721e26f2018-07-24 22:26:19 +08003238 sp<InputWindowHandle> oldFocusedWindowHandle =
3239 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3240
3241 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3242 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003244 ALOGD("Focus left window: %s in display %" PRId32,
Garfield Tane4fc0102019-09-11 13:16:25 -07003245 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246#endif
Garfield Tane4fc0102019-09-11 13:16:25 -07003247 sp<InputChannel> focusedInputChannel =
3248 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003249 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Garfield Tane4fc0102019-09-11 13:16:25 -07003251 "focus left window");
3252 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003254 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003256 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003258 ALOGD("Focus entered window: %s in display %" PRId32,
Garfield Tane4fc0102019-09-11 13:16:25 -07003259 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003260#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003261 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262 }
Robert Carrf759f162018-11-13 12:57:11 -08003263
3264 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003265 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267 }
3268
Arthur Hungb92218b2018-08-14 12:00:21 +08003269 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3270 if (stateIndex >= 0) {
3271 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Garfield Tane4fc0102019-09-11 13:16:25 -07003272 for (size_t i = 0; i < state.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003273 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003274 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003276 ALOGD("Touched window was removed: %s in display %" PRId32,
Garfield Tane4fc0102019-09-11 13:16:25 -07003277 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003279 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003280 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003281 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003282 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tane4fc0102019-09-11 13:16:25 -07003283 "touched window was removed");
3284 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3285 options);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003286 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003287 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003288 } else {
Garfield Tane4fc0102019-09-11 13:16:25 -07003289 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 }
3292 }
3293
3294 // Release information for windows that are no longer present.
3295 // This ensures that unused input channels are released promptly.
3296 // Otherwise, they might stick around until the window handle is destroyed
3297 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003298 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003299 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003301 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003303 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304 }
3305 }
3306 } // release lock
3307
3308 // Wake up poll loop since it may need to make new input dispatching choices.
3309 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003310
3311 if (setInputWindowsListener) {
3312 setInputWindowsListener->onSetInputWindowsFinished();
3313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314}
3315
3316void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003317 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003319 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320#endif
3321 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003322 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323
Tiger Huang721e26f2018-07-24 22:26:19 +08003324 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3325 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003326 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003327 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3328 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003331 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003333 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003335 oldFocusedApplicationHandle.clear();
3336 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 }
3338
3339#if DEBUG_FOCUS
Garfield Tane4fc0102019-09-11 13:16:25 -07003340 // logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341#endif
3342 } // release lock
3343
3344 // Wake up poll loop since it may need to make new input dispatching choices.
3345 mLooper->wake();
3346}
3347
Tiger Huang721e26f2018-07-24 22:26:19 +08003348/**
3349 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3350 * the display not specified.
3351 *
3352 * We track any unreleased events for each window. If a window loses the ability to receive the
3353 * released event, we will send a cancel event to it. So when the focused display is changed, we
3354 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3355 * display. The display-specified events won't be affected.
3356 */
3357void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3358#if DEBUG_FOCUS
3359 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3360#endif
3361 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003362 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003363
3364 if (mFocusedDisplayId != displayId) {
3365 sp<InputWindowHandle> oldFocusedWindowHandle =
3366 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3367 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003368 sp<InputChannel> inputChannel =
Garfield Tane4fc0102019-09-11 13:16:25 -07003369 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003370 if (inputChannel != nullptr) {
Garfield Tane4fc0102019-09-11 13:16:25 -07003371 CancelationOptions
3372 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3373 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003374 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003375 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3376 }
3377 }
3378 mFocusedDisplayId = displayId;
3379
3380 // Sanity check
3381 sp<InputWindowHandle> newFocusedWindowHandle =
3382 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003383 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003384
Tiger Huang721e26f2018-07-24 22:26:19 +08003385 if (newFocusedWindowHandle == nullptr) {
3386 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3387 if (!mFocusedWindowHandlesByDisplay.empty()) {
3388 ALOGE("But another display has a focused window:");
3389 for (auto& it : mFocusedWindowHandlesByDisplay) {
3390 const int32_t displayId = it.first;
3391 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tane4fc0102019-09-11 13:16:25 -07003392 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3393 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003394 }
3395 }
3396 }
3397 }
3398
3399#if DEBUG_FOCUS
3400 logDispatchStateLocked();
3401#endif
3402 } // release lock
3403
3404 // Wake up poll loop since it may need to make new input dispatching choices.
3405 mLooper->wake();
3406}
3407
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3409#if DEBUG_FOCUS
3410 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3411#endif
3412
3413 bool changed;
3414 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003415 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416
3417 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3418 if (mDispatchFrozen && !frozen) {
3419 resetANRTimeoutsLocked();
3420 }
3421
3422 if (mDispatchEnabled && !enabled) {
3423 resetAndDropEverythingLocked("dispatcher is being disabled");
3424 }
3425
3426 mDispatchEnabled = enabled;
3427 mDispatchFrozen = frozen;
3428 changed = true;
3429 } else {
3430 changed = false;
3431 }
3432
3433#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003434 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435#endif
3436 } // release lock
3437
3438 if (changed) {
3439 // Wake up poll loop since it may need to make new input dispatching choices.
3440 mLooper->wake();
3441 }
3442}
3443
3444void InputDispatcher::setInputFilterEnabled(bool enabled) {
3445#if DEBUG_FOCUS
3446 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3447#endif
3448
3449 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003450 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451
3452 if (mInputFilterEnabled == enabled) {
3453 return;
3454 }
3455
3456 mInputFilterEnabled = enabled;
3457 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3458 } // release lock
3459
3460 // Wake up poll loop since there might be work to do to drop everything.
3461 mLooper->wake();
3462}
3463
chaviwfbe5d9c2018-12-26 12:23:37 -08003464bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3465 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003467 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003469 return true;
3470 }
3471
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003473 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474
chaviwfbe5d9c2018-12-26 12:23:37 -08003475 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3476 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003477 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003478 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479 return false;
3480 }
chaviw4f2dd402018-12-26 15:30:27 -08003481#if DEBUG_FOCUS
3482 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Garfield Tane4fc0102019-09-11 13:16:25 -07003483 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
chaviw4f2dd402018-12-26 15:30:27 -08003484#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3486#if DEBUG_FOCUS
3487 ALOGD("Cannot transfer focus because windows are on different displays.");
3488#endif
3489 return false;
3490 }
3491
3492 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003493 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3494 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3495 for (size_t i = 0; i < state.windows.size(); i++) {
3496 const TouchedWindow& touchedWindow = state.windows[i];
3497 if (touchedWindow.windowHandle == fromWindowHandle) {
3498 int32_t oldTargetFlags = touchedWindow.targetFlags;
3499 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003501 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502
Garfield Tane4fc0102019-09-11 13:16:25 -07003503 int32_t newTargetFlags = oldTargetFlags &
3504 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3505 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003506 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507
Jeff Brownf086ddb2014-02-11 14:28:48 -08003508 found = true;
3509 goto Found;
3510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 }
3512 }
Garfield Tane4fc0102019-09-11 13:16:25 -07003513 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514
Garfield Tane4fc0102019-09-11 13:16:25 -07003515 if (!found) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516#if DEBUG_FOCUS
3517 ALOGD("Focus transfer failed because from window did not have focus.");
3518#endif
3519 return false;
3520 }
3521
chaviwfbe5d9c2018-12-26 12:23:37 -08003522 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3523 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3525 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3526 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3527 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3528 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3529
3530 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Garfield Tane4fc0102019-09-11 13:16:25 -07003531 CancelationOptions
3532 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3533 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3535 }
3536
3537#if DEBUG_FOCUS
3538 logDispatchStateLocked();
3539#endif
3540 } // release lock
3541
3542 // Wake up poll loop since it may need to make new input dispatching choices.
3543 mLooper->wake();
3544 return true;
3545}
3546
3547void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3548#if DEBUG_FOCUS
3549 ALOGD("Resetting and dropping all events (%s).", reason);
3550#endif
3551
3552 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3553 synthesizeCancelationEventsForAllConnectionsLocked(options);
3554
3555 resetKeyRepeatLocked();
3556 releasePendingEventLocked();
3557 drainInboundQueueLocked();
3558 resetANRTimeoutsLocked();
3559
Jeff Brownf086ddb2014-02-11 14:28:48 -08003560 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003562 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563}
3564
3565void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003566 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 dumpDispatchStateLocked(dump);
3568
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003569 std::istringstream stream(dump);
3570 std::string line;
3571
3572 while (std::getline(stream, line, '\n')) {
3573 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574 }
3575}
3576
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003577void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003578 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3579 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3580 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003581 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582
Tiger Huang721e26f2018-07-24 22:26:19 +08003583 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3584 dump += StringPrintf(INDENT "FocusedApplications:\n");
3585 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3586 const int32_t displayId = it.first;
3587 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tane4fc0102019-09-11 13:16:25 -07003588 dump += StringPrintf(INDENT2 "displayId=%" PRId32
3589 ", name='%s', dispatchingTimeout=%0.3fms\n",
3590 displayId, applicationHandle->getName().c_str(),
3591 applicationHandle->getDispatchingTimeout(
3592 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3593 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08003594 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003596 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003598
3599 if (!mFocusedWindowHandlesByDisplay.empty()) {
3600 dump += StringPrintf(INDENT "FocusedWindows:\n");
3601 for (auto& it : mFocusedWindowHandlesByDisplay) {
3602 const int32_t displayId = it.first;
3603 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tane4fc0102019-09-11 13:16:25 -07003604 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3605 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003606 }
3607 } else {
3608 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610
Jeff Brownf086ddb2014-02-11 14:28:48 -08003611 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003612 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003613 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3614 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003615 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003616 state.displayId, toString(state.down), toString(state.split),
3617 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003618 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003619 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003620 for (size_t i = 0; i < state.windows.size(); i++) {
3621 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tane4fc0102019-09-11 13:16:25 -07003622 dump += StringPrintf(INDENT4
3623 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3624 i, touchedWindow.windowHandle->getName().c_str(),
3625 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003626 }
3627 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003628 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003629 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003630 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003631 dump += INDENT3 "Portal windows:\n";
3632 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003633 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tane4fc0102019-09-11 13:16:25 -07003634 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3635 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003636 }
3637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 }
3639 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003640 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 }
3642
Arthur Hungb92218b2018-08-14 12:00:21 +08003643 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07003644 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003645 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003646 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003647 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003648 dump += INDENT2 "Windows:\n";
3649 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003650 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003651 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652
Arthur Hungb92218b2018-08-14 12:00:21 +08003653 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07003654 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
3655 "hasWallpaper=%s, "
3656 "visible=%s, canReceiveKeys=%s, flags=0x%08x, "
3657 "type=0x%08x, layer=%d, "
3658 "frame=[%d,%d][%d,%d], globalScale=%f, "
3659 "windowScale=(%f,%f), "
3660 "touchableRegion=",
3661 i, windowInfo->name.c_str(), windowInfo->displayId,
3662 windowInfo->portalToDisplayId,
3663 toString(windowInfo->paused),
3664 toString(windowInfo->hasFocus),
3665 toString(windowInfo->hasWallpaper),
3666 toString(windowInfo->visible),
3667 toString(windowInfo->canReceiveKeys),
3668 windowInfo->layoutParamsFlags,
3669 windowInfo->layoutParamsType, windowInfo->layer,
3670 windowInfo->frameLeft, windowInfo->frameTop,
3671 windowInfo->frameRight, windowInfo->frameBottom,
3672 windowInfo->globalScaleFactor, windowInfo->windowXScale,
3673 windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003674 dumpRegion(dump, windowInfo->touchableRegion);
3675 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3676 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003677 windowInfo->ownerPid, windowInfo->ownerUid,
3678 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08003679 }
3680 } else {
3681 dump += INDENT2 "Windows: <none>\n";
3682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 }
3684 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003685 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686 }
3687
Michael Wright3dd60e22019-03-27 22:06:44 +00003688 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tane4fc0102019-09-11 13:16:25 -07003689 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003690 const std::vector<Monitor>& monitors = it.second;
3691 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3692 dumpMonitors(dump, monitors);
Garfield Tane4fc0102019-09-11 13:16:25 -07003693 }
3694 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003695 const std::vector<Monitor>& monitors = it.second;
3696 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3697 dumpMonitors(dump, monitors);
Garfield Tane4fc0102019-09-11 13:16:25 -07003698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003700 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 }
3702
3703 nsecs_t currentTime = now();
3704
3705 // Dump recently dispatched or dropped events from oldest to newest.
3706 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003707 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003709 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 entry->appendDescription(dump);
Garfield Tane4fc0102019-09-11 13:16:25 -07003711 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 }
3713 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003714 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 }
3716
3717 // Dump event currently being dispatched.
3718 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003719 dump += INDENT "PendingEvent:\n";
3720 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003722 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003723 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003725 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726 }
3727
3728 // Dump inbound events from oldest to newest.
3729 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003730 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003732 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 entry->appendDescription(dump);
Garfield Tane4fc0102019-09-11 13:16:25 -07003734 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735 }
3736 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003737 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738 }
3739
Michael Wright78f24442014-08-06 15:55:28 -07003740 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003741 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003742 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3743 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3744 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tane4fc0102019-09-11 13:16:25 -07003745 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3746 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07003747 }
3748 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003749 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003750 }
3751
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003753 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3755 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003756 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Garfield Tane4fc0102019-09-11 13:16:25 -07003757 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3758 i, connection->getInputChannelName().c_str(),
3759 connection->getWindowName().c_str(), connection->getStatusLabel(),
3760 toString(connection->monitor),
3761 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762
3763 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003764 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003765 connection->outboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
Garfield Tane4fc0102019-09-11 13:16:25 -07003767 entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768 dump.append(INDENT4);
3769 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003770 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003771 entry->targetFlags, entry->resolvedAction,
3772 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 }
3774 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003775 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 }
3777
3778 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003779 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003780 connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 for (DispatchEntry* entry = connection->waitQueue.head; entry;
Garfield Tane4fc0102019-09-11 13:16:25 -07003782 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003783 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003785 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07003786 "age=%0.1fms, wait=%0.1fms\n",
3787 entry->targetFlags, entry->resolvedAction,
3788 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3789 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 }
3791 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003792 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 }
3794 }
3795 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003796 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 }
3798
3799 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003800 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003801 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003803 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 }
3805
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003806 dump += INDENT "Configuration:\n";
Garfield Tane4fc0102019-09-11 13:16:25 -07003807 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003808 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tane4fc0102019-09-11 13:16:25 -07003809 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810}
3811
Michael Wright3dd60e22019-03-27 22:06:44 +00003812void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3813 const size_t numMonitors = monitors.size();
3814 for (size_t i = 0; i < numMonitors; i++) {
3815 const Monitor& monitor = monitors[i];
3816 const sp<InputChannel>& channel = monitor.inputChannel;
3817 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3818 dump += "\n";
3819 }
3820}
3821
3822status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
Garfield Tane4fc0102019-09-11 13:16:25 -07003823 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003825 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
Garfield Tane4fc0102019-09-11 13:16:25 -07003826 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827#endif
3828
3829 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003830 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831
3832 if (getConnectionIndexLocked(inputChannel) >= 0) {
3833 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tane4fc0102019-09-11 13:16:25 -07003834 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 return BAD_VALUE;
3836 }
3837
Michael Wright3dd60e22019-03-27 22:06:44 +00003838 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839
3840 int fd = inputChannel->getFd();
3841 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003842 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3845 } // release lock
3846
3847 // Wake the looper because some connections have changed.
3848 mLooper->wake();
3849 return OK;
3850}
3851
Michael Wright3dd60e22019-03-27 22:06:44 +00003852status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tane4fc0102019-09-11 13:16:25 -07003853 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003854 { // acquire lock
3855 std::scoped_lock _l(mLock);
3856
3857 if (displayId < 0) {
3858 ALOGW("Attempted to register input monitor without a specified display.");
3859 return BAD_VALUE;
3860 }
3861
3862 if (inputChannel->getToken() == nullptr) {
3863 ALOGW("Attempted to register input monitor without an identifying token.");
3864 return BAD_VALUE;
3865 }
3866
3867 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3868
3869 const int fd = inputChannel->getFd();
3870 mConnectionsByFd.add(fd, connection);
3871 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
3872
Garfield Tane4fc0102019-09-11 13:16:25 -07003873 auto& monitorsByDisplay =
3874 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00003875 monitorsByDisplay[displayId].emplace_back(inputChannel);
3876
3877 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00003878 }
3879 // Wake the looper because some connections have changed.
3880 mLooper->wake();
3881 return OK;
3882}
3883
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3885#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003886 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887#endif
3888
3889 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003890 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891
3892 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3893 if (status) {
3894 return status;
3895 }
3896 } // release lock
3897
3898 // Wake the poll loop because removing the connection may have changed the current
3899 // synchronization state.
3900 mLooper->wake();
3901 return OK;
3902}
3903
3904status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tane4fc0102019-09-11 13:16:25 -07003905 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3907 if (connectionIndex < 0) {
3908 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tane4fc0102019-09-11 13:16:25 -07003909 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 return BAD_VALUE;
3911 }
3912
3913 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3914 mConnectionsByFd.removeItemsAt(connectionIndex);
3915
Robert Carr5c8a0262018-10-03 16:30:44 -07003916 mInputChannelsByToken.erase(inputChannel->getToken());
3917
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918 if (connection->monitor) {
3919 removeMonitorChannelLocked(inputChannel);
3920 }
3921
3922 mLooper->removeFd(inputChannel->getFd());
3923
3924 nsecs_t currentTime = now();
3925 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3926
3927 connection->status = Connection::STATUS_ZOMBIE;
3928 return OK;
3929}
3930
3931void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003932 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
3933 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
3934}
3935
Garfield Tane4fc0102019-09-11 13:16:25 -07003936void InputDispatcher::removeMonitorChannelLocked(
3937 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00003938 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tane4fc0102019-09-11 13:16:25 -07003939 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003940 std::vector<Monitor>& monitors = it->second;
3941 const size_t numMonitors = monitors.size();
3942 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tane4fc0102019-09-11 13:16:25 -07003943 if (monitors[i].inputChannel == inputChannel) {
3944 monitors.erase(monitors.begin() + i);
3945 break;
3946 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003947 }
Michael Wright3dd60e22019-03-27 22:06:44 +00003948 if (monitors.empty()) {
3949 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003950 } else {
3951 ++it;
3952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 }
3954}
3955
Michael Wright3dd60e22019-03-27 22:06:44 +00003956status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
3957 { // acquire lock
3958 std::scoped_lock _l(mLock);
3959 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
3960
3961 if (!foundDisplayId) {
3962 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
3963 return BAD_VALUE;
3964 }
3965 int32_t displayId = foundDisplayId.value();
3966
3967 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3968 if (stateIndex < 0) {
3969 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
3970 return BAD_VALUE;
3971 }
3972
3973 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
3974 std::optional<int32_t> foundDeviceId;
3975 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
3976 if (touchedMonitor.monitor.inputChannel->getToken() == token) {
3977 foundDeviceId = state.deviceId;
3978 }
3979 }
3980 if (!foundDeviceId || !state.down) {
3981 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tane4fc0102019-09-11 13:16:25 -07003982 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003983 return BAD_VALUE;
3984 }
3985 int32_t deviceId = foundDeviceId.value();
3986
3987 // Send cancel events to all the input channels we're stealing from.
3988 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tane4fc0102019-09-11 13:16:25 -07003989 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00003990 options.deviceId = deviceId;
3991 options.displayId = displayId;
3992 for (const TouchedWindow& window : state.windows) {
3993 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
3994 synthesizeCancelationEventsForInputChannelLocked(channel, options);
3995 }
3996 // Then clear the current touch state so we stop dispatching to them as well.
3997 state.filterNonMonitors();
3998 }
3999 return OK;
4000}
4001
Michael Wright3dd60e22019-03-27 22:06:44 +00004002std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4003 const sp<IBinder>& token) {
4004 for (const auto& it : mGestureMonitorsByDisplay) {
4005 const std::vector<Monitor>& monitors = it.second;
4006 for (const Monitor& monitor : monitors) {
4007 if (monitor.inputChannel->getToken() == token) {
4008 return it.first;
4009 }
4010 }
4011 }
4012 return std::nullopt;
4013}
4014
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07004016 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08004017 return -1;
4018 }
4019
Robert Carr4e670e52018-08-15 13:26:12 -07004020 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
4021 sp<Connection> connection = mConnectionsByFd.valueAt(i);
4022 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
4023 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024 }
4025 }
Robert Carr4e670e52018-08-15 13:26:12 -07004026
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027 return -1;
4028}
4029
Garfield Tane4fc0102019-09-11 13:16:25 -07004030void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4031 const sp<Connection>& connection, uint32_t seq,
4032 bool handled) {
4033 CommandEntry* commandEntry =
4034 postCommandLocked(&InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035 commandEntry->connection = connection;
4036 commandEntry->eventTime = currentTime;
4037 commandEntry->seq = seq;
4038 commandEntry->handled = handled;
4039}
4040
Garfield Tane4fc0102019-09-11 13:16:25 -07004041void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4042 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tane4fc0102019-09-11 13:16:25 -07004044 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045
Garfield Tane4fc0102019-09-11 13:16:25 -07004046 CommandEntry* commandEntry =
4047 postCommandLocked(&InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048 commandEntry->connection = connection;
4049}
4050
chaviw0c06c6e2019-01-09 13:27:07 -08004051void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tane4fc0102019-09-11 13:16:25 -07004052 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004053 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4054 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Garfield Tane4fc0102019-09-11 13:16:25 -07004055 CommandEntry* commandEntry =
4056 postCommandLocked(&InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004057 commandEntry->oldToken = oldToken;
4058 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004059}
4060
Garfield Tane4fc0102019-09-11 13:16:25 -07004061void InputDispatcher::onANRLocked(nsecs_t currentTime,
4062 const sp<InputApplicationHandle>& applicationHandle,
4063 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4064 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4066 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4067 ALOGI("Application is not responding: %s. "
Garfield Tane4fc0102019-09-11 13:16:25 -07004068 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4069 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4070 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071
4072 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004073 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 struct tm tm;
4075 localtime_r(&t, &tm);
4076 char timestr[64];
4077 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4078 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004079 mLastANRState += INDENT "ANR:\n";
4080 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tane4fc0102019-09-11 13:16:25 -07004081 mLastANRState +=
4082 StringPrintf(INDENT2 "Window: %s\n",
4083 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004084 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4085 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4086 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 dumpDispatchStateLocked(mLastANRState);
4088
Garfield Tane4fc0102019-09-11 13:16:25 -07004089 CommandEntry* commandEntry =
4090 postCommandLocked(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tane4fc0102019-09-11 13:16:25 -07004092 commandEntry->inputChannel =
4093 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094 commandEntry->reason = reason;
4095}
4096
Garfield Tane4fc0102019-09-11 13:16:25 -07004097void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 mLock.unlock();
4099
4100 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4101
4102 mLock.lock();
4103}
4104
Garfield Tane4fc0102019-09-11 13:16:25 -07004105void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 sp<Connection> connection = commandEntry->connection;
4107
4108 if (connection->status != Connection::STATUS_ZOMBIE) {
4109 mLock.unlock();
4110
Robert Carr803535b2018-08-02 16:38:15 -07004111 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112
4113 mLock.lock();
4114 }
4115}
4116
Garfield Tane4fc0102019-09-11 13:16:25 -07004117void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004118 sp<IBinder> oldToken = commandEntry->oldToken;
4119 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004120 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004121 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004122 mLock.lock();
4123}
4124
Garfield Tane4fc0102019-09-11 13:16:25 -07004125void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 mLock.unlock();
4127
Garfield Tane4fc0102019-09-11 13:16:25 -07004128 nsecs_t newTimeout =
4129 mPolicy->notifyANR(commandEntry->inputApplicationHandle,
4130 commandEntry->inputChannel ? commandEntry->inputChannel->getToken()
4131 : nullptr,
4132 commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133
4134 mLock.lock();
4135
Garfield Tane4fc0102019-09-11 13:16:25 -07004136 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137}
4138
4139void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4140 CommandEntry* commandEntry) {
4141 KeyEntry* entry = commandEntry->keyEntry;
4142
4143 KeyEvent event;
4144 initializeKeyEvent(&event, entry);
4145
4146 mLock.unlock();
4147
Michael Wright2b3c3302018-03-02 17:19:13 +00004148 android::base::Timer t;
Garfield Tane4fc0102019-09-11 13:16:25 -07004149 sp<IBinder> token = commandEntry->inputChannel != nullptr
4150 ? commandEntry->inputChannel->getToken()
4151 : nullptr;
4152 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004153 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4154 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tane4fc0102019-09-11 13:16:25 -07004155 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157
4158 mLock.lock();
4159
4160 if (delay < 0) {
4161 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4162 } else if (!delay) {
4163 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4164 } else {
4165 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4166 entry->interceptKeyWakeupTime = now() + delay;
4167 }
4168 entry->release();
4169}
4170
chaviwfd6d3512019-03-25 13:23:49 -07004171void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4172 mLock.unlock();
4173 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4174 mLock.lock();
4175}
4176
Garfield Tane4fc0102019-09-11 13:16:25 -07004177void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 sp<Connection> connection = commandEntry->connection;
4179 nsecs_t finishTime = commandEntry->eventTime;
4180 uint32_t seq = commandEntry->seq;
4181 bool handled = commandEntry->handled;
4182
4183 // Handle post-event policy actions.
4184 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
4185 if (dispatchEntry) {
4186 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4187 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004188 std::string msg =
4189 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Garfield Tane4fc0102019-09-11 13:16:25 -07004190 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004192 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 }
4194
4195 bool restartEvent;
4196 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4197 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
Garfield Tane4fc0102019-09-11 13:16:25 -07004198 restartEvent =
4199 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4201 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
Garfield Tane4fc0102019-09-11 13:16:25 -07004202 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry,
4203 motionEntry, handled);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 } else {
4205 restartEvent = false;
4206 }
4207
4208 // Dequeue the event and start the next cycle.
4209 // Note that because the lock might have been released, it is possible that the
4210 // contents of the wait queue to have been drained, so we need to double-check
4211 // a few things.
4212 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4213 connection->waitQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004214 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4216 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004217 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 } else {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08004219 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 }
4221 }
4222
4223 // Start the next dispatch cycle for this connection.
4224 startDispatchCycleLocked(now(), connection);
4225 }
4226}
4227
4228bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tane4fc0102019-09-11 13:16:25 -07004229 DispatchEntry* dispatchEntry,
4230 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004231 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004232 if (!handled) {
4233 // Report the key as unhandled, since the fallback was not handled.
4234 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4235 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004236 return false;
4237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004239 // Get the fallback key state.
4240 // Clear it out after dispatching the UP.
4241 int32_t originalKeyCode = keyEntry->keyCode;
4242 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4243 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4244 connection->inputState.removeFallbackKey(originalKeyCode);
4245 }
4246
4247 if (handled || !dispatchEntry->hasForegroundTarget()) {
4248 // If the application handles the original key for which we previously
4249 // generated a fallback or if the window is not a foreground window,
4250 // then cancel the associated fallback key, if any.
4251 if (fallbackKeyCode != -1) {
4252 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004254 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tane4fc0102019-09-11 13:16:25 -07004255 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4256 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4257 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258#endif
4259 KeyEvent event;
4260 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004261 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262
4263 mLock.unlock();
4264
Garfield Tane4fc0102019-09-11 13:16:25 -07004265 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(), &event,
4266 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267
4268 mLock.lock();
4269
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004270 // Cancel the fallback key.
4271 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004273 "application handled the original non-fallback key "
4274 "or is no longer a foreground target, "
4275 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 options.keyCode = fallbackKeyCode;
4277 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004279 connection->inputState.removeFallbackKey(originalKeyCode);
4280 }
4281 } else {
4282 // If the application did not handle a non-fallback key, first check
4283 // that we are in a good state to perform unhandled key event processing
4284 // Then ask the policy what to do with it.
Garfield Tane4fc0102019-09-11 13:16:25 -07004285 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004286 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004288 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tane4fc0102019-09-11 13:16:25 -07004289 "since this is not an initial down. "
4290 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4291 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004293 return false;
4294 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004296 // Dispatch the unhandled key to the policy.
4297#if DEBUG_OUTBOUND_EVENT_DETAILS
4298 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tane4fc0102019-09-11 13:16:25 -07004299 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4300 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004301#endif
4302 KeyEvent event;
4303 initializeKeyEvent(&event, keyEntry);
4304
4305 mLock.unlock();
4306
Garfield Tane4fc0102019-09-11 13:16:25 -07004307 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(), &event,
4308 keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004309
4310 mLock.lock();
4311
4312 if (connection->status != Connection::STATUS_NORMAL) {
4313 connection->inputState.removeFallbackKey(originalKeyCode);
4314 return false;
4315 }
4316
4317 // Latch the fallback keycode for this key on an initial down.
4318 // The fallback keycode cannot change at any other point in the lifecycle.
4319 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004321 fallbackKeyCode = event.getKeyCode();
4322 } else {
4323 fallbackKeyCode = AKEYCODE_UNKNOWN;
4324 }
4325 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4326 }
4327
4328 ALOG_ASSERT(fallbackKeyCode != -1);
4329
4330 // Cancel the fallback key if the policy decides not to send it anymore.
4331 // We will continue to dispatch the key to the policy but we will no
4332 // longer dispatch a fallback key to the application.
Garfield Tane4fc0102019-09-11 13:16:25 -07004333 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4334 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004335#if DEBUG_OUTBOUND_EVENT_DETAILS
4336 if (fallback) {
4337 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tane4fc0102019-09-11 13:16:25 -07004338 "as a fallback for %d, but on the DOWN it had requested "
4339 "to send %d instead. Fallback canceled.",
4340 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004341 } else {
4342 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tane4fc0102019-09-11 13:16:25 -07004343 "but on the DOWN it had requested to send %d. "
4344 "Fallback canceled.",
4345 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004346 }
4347#endif
4348
4349 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4350 "canceling fallback, policy no longer desires it");
4351 options.keyCode = fallbackKeyCode;
4352 synthesizeCancelationEventsForConnectionLocked(connection, options);
4353
4354 fallback = false;
4355 fallbackKeyCode = AKEYCODE_UNKNOWN;
4356 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tane4fc0102019-09-11 13:16:25 -07004357 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004358 }
4359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360
4361#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004362 {
4363 std::string msg;
4364 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4365 connection->inputState.getFallbackKeys();
4366 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tane4fc0102019-09-11 13:16:25 -07004367 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004369 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tane4fc0102019-09-11 13:16:25 -07004370 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004371 }
4372#endif
4373
4374 if (fallback) {
4375 // Restart the dispatch cycle using the fallback key.
4376 keyEntry->eventTime = event.getEventTime();
4377 keyEntry->deviceId = event.getDeviceId();
4378 keyEntry->source = event.getSource();
4379 keyEntry->displayId = event.getDisplayId();
4380 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4381 keyEntry->keyCode = fallbackKeyCode;
4382 keyEntry->scanCode = event.getScanCode();
4383 keyEntry->metaState = event.getMetaState();
4384 keyEntry->repeatCount = event.getRepeatCount();
4385 keyEntry->downTime = event.getDownTime();
4386 keyEntry->syntheticRepeat = false;
4387
4388#if DEBUG_OUTBOUND_EVENT_DETAILS
4389 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tane4fc0102019-09-11 13:16:25 -07004390 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4391 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004392#endif
4393 return true; // restart the event
4394 } else {
4395#if DEBUG_OUTBOUND_EVENT_DETAILS
4396 ALOGD("Unhandled key event: No fallback key.");
4397#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004398
4399 // Report the key as unhandled, since there is no fallback key.
4400 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 }
4402 }
4403 return false;
4404}
4405
4406bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tane4fc0102019-09-11 13:16:25 -07004407 DispatchEntry* dispatchEntry,
4408 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409 return false;
4410}
4411
4412void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4413 mLock.unlock();
4414
4415 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4416
4417 mLock.lock();
4418}
4419
4420void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004421 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Garfield Tane4fc0102019-09-11 13:16:25 -07004422 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4423 entry->downTime, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424}
4425
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004426void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Garfield Tane4fc0102019-09-11 13:16:25 -07004427 int32_t injectionResult,
4428 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 // TODO Write some statistics about how long we spend waiting.
4430}
4431
4432void InputDispatcher::traceInboundQueueLengthLocked() {
4433 if (ATRACE_ENABLED()) {
4434 ATRACE_INT("iq", mInboundQueue.count());
4435 }
4436}
4437
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004438void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439 if (ATRACE_ENABLED()) {
4440 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004441 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004442 ATRACE_INT(counterName, connection->outboundQueue.count());
4443 }
4444}
4445
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004446void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447 if (ATRACE_ENABLED()) {
4448 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004449 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 ATRACE_INT(counterName, connection->waitQueue.count());
4451 }
4452}
4453
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004454void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004455 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004457 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458 dumpDispatchStateLocked(dump);
4459
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004460 if (!mLastANRState.empty()) {
4461 dump += "\nInput Dispatcher State at time of last ANR:\n";
4462 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 }
4464}
4465
4466void InputDispatcher::monitor() {
4467 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004468 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004470 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471}
4472
Garfield Tan73007b62019-08-29 17:28:41 -07004473} // namespace android::inputdispatcher