blob: ee8c344a9636550796635fa0a13d692de74e08bf [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.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
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 Tane84e6f92019-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>
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -050053#include <statslog.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080055#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056#include <unistd.h>
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -070057#include <queue>
58#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070059
Michael Wright2b3c3302018-03-02 17:19:13 +000060#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070062#include <binder/Binder.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070063#include <log/log.h>
64#include <powermanager/PowerManager.h>
65#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080066
67#define INDENT " "
68#define INDENT2 " "
69#define INDENT3 " "
70#define INDENT4 " "
71
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080072using android::base::StringPrintf;
73
Garfield Tane84e6f92019-08-29 17:28:41 -070074namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
76// Default input dispatching timeout if there is no focused application or paused window
77// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000078constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Amount of time to allow for all pending events to be processed when an app switch
81// key is on the way. This is used to preempt input dispatch and drop input events
82// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000083constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow for an event to be dispatched (measured since its eventTime)
86// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000087constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080088
89// Amount of time to allow touch events to be streamed out to a connection before requiring
90// that the first event be finished. This value extends the ANR timeout by the specified
91// amount. For example, if streaming is allowed to get ahead by one second relative to the
92// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000093constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
95// 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 +000096constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
97
98// Log a warning when an interception call takes longer than this to process.
99constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100
101// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000102constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104static inline nsecs_t now() {
105 return systemTime(SYSTEM_TIME_MONOTONIC);
106}
107
108static inline const char* toString(bool value) {
109 return value ? "true" : "false";
110}
111
112static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700113 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
114 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115}
116
117static bool isValidKeyAction(int32_t action) {
118 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700119 case AKEY_EVENT_ACTION_DOWN:
120 case AKEY_EVENT_ACTION_UP:
121 return true;
122 default:
123 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800124 }
125}
126
127static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700128 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800129 ALOGE("Key event has invalid action code 0x%x", action);
130 return false;
131 }
132 return true;
133}
134
Michael Wright7b159c92015-05-14 14:48:03 +0100135static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700137 case AMOTION_EVENT_ACTION_DOWN:
138 case AMOTION_EVENT_ACTION_UP:
139 case AMOTION_EVENT_ACTION_CANCEL:
140 case AMOTION_EVENT_ACTION_MOVE:
141 case AMOTION_EVENT_ACTION_OUTSIDE:
142 case AMOTION_EVENT_ACTION_HOVER_ENTER:
143 case AMOTION_EVENT_ACTION_HOVER_MOVE:
144 case AMOTION_EVENT_ACTION_HOVER_EXIT:
145 case AMOTION_EVENT_ACTION_SCROLL:
146 return true;
147 case AMOTION_EVENT_ACTION_POINTER_DOWN:
148 case AMOTION_EVENT_ACTION_POINTER_UP: {
149 int32_t index = getMotionEventActionPointerIndex(action);
150 return index >= 0 && index < pointerCount;
151 }
152 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
153 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
154 return actionButton != 0;
155 default:
156 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800157 }
158}
159
Michael Wright7b159c92015-05-14 14:48:03 +0100160static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 const PointerProperties* pointerProperties) {
162 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800163 ALOGE("Motion event has invalid action code 0x%x", action);
164 return false;
165 }
166 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000167 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700168 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800169 return false;
170 }
171 BitSet32 pointerIdBits;
172 for (size_t i = 0; i < pointerCount; i++) {
173 int32_t id = pointerProperties[i].id;
174 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700175 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
176 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 return false;
178 }
179 if (pointerIdBits.hasBit(id)) {
180 ALOGE("Motion event has duplicate pointer id %d", id);
181 return false;
182 }
183 pointerIdBits.markBit(id);
184 }
185 return true;
186}
187
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800188static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800190 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 return;
192 }
193
194 bool first = true;
195 Region::const_iterator cur = region.begin();
196 Region::const_iterator const tail = region.end();
197 while (cur != tail) {
198 if (first) {
199 first = false;
200 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800201 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800203 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 cur++;
205 }
206}
207
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700208/**
209 * Find the entry in std::unordered_map by key, and return it.
210 * If the entry is not found, return a default constructed entry.
211 *
212 * Useful when the entries are vectors, since an empty vector will be returned
213 * if the entry is not found.
214 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
215 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700216template <typename K, typename V>
217static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700218 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700219 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800220}
221
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700222/**
223 * Find the entry in std::unordered_map by value, and remove it.
224 * If more than one entry has the same value, then all matching
225 * key-value pairs will be removed.
226 *
227 * Return true if at least one value has been removed.
228 */
229template <typename K, typename V>
230static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
231 bool removed = false;
232 for (auto it = map.begin(); it != map.end();) {
233 if (it->second == value) {
234 it = map.erase(it);
235 removed = true;
236 } else {
237 it++;
238 }
239 }
240 return removed;
241}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242
243// --- InputDispatcher ---
244
Garfield Tan00f511d2019-06-12 16:55:40 -0700245InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
246 : mPolicy(policy),
247 mPendingEvent(nullptr),
248 mLastDropReason(DROP_REASON_NOT_DROPPED),
249 mAppSwitchSawKeyDown(false),
250 mAppSwitchDueTime(LONG_LONG_MAX),
251 mNextUnblockedEvent(nullptr),
252 mDispatchEnabled(false),
253 mDispatchFrozen(false),
254 mInputFilterEnabled(false),
255 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
256 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800258 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259
Yi Kong9b14ac62018-07-17 13:48:38 -0700260 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261
262 policy->getDispatcherConfiguration(&mConfig);
263}
264
265InputDispatcher::~InputDispatcher() {
266 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800267 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268
269 resetKeyRepeatLocked();
270 releasePendingEventLocked();
271 drainInboundQueueLocked();
272 }
273
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700274 while (!mConnectionsByFd.empty()) {
275 sp<Connection> connection = mConnectionsByFd.begin()->second;
276 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800277 }
278}
279
280void InputDispatcher::dispatchOnce() {
281 nsecs_t nextWakeupTime = LONG_LONG_MAX;
282 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800283 std::scoped_lock _l(mLock);
284 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800285
286 // Run a dispatch loop if there are no pending commands.
287 // The dispatch loop might enqueue commands to run afterwards.
288 if (!haveCommandsLocked()) {
289 dispatchOnceInnerLocked(&nextWakeupTime);
290 }
291
292 // Run all pending commands if there are any.
293 // If any commands were run then force the next poll to wake up immediately.
294 if (runCommandsLockedInterruptible()) {
295 nextWakeupTime = LONG_LONG_MIN;
296 }
297 } // release lock
298
299 // Wait for callback or timeout or wake. (make sure we round up, not down)
300 nsecs_t currentTime = now();
301 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
302 mLooper->pollOnce(timeoutMillis);
303}
304
305void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
306 nsecs_t currentTime = now();
307
Jeff Browndc5992e2014-04-11 01:27:26 -0700308 // Reset the key repeat timer whenever normal dispatch is suspended while the
309 // device is in a non-interactive state. This is to ensure that we abort a key
310 // repeat if the device is just coming out of sleep.
311 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800312 resetKeyRepeatLocked();
313 }
314
315 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
316 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100317 if (DEBUG_FOCUS) {
318 ALOGD("Dispatch frozen. Waiting some more.");
319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800320 return;
321 }
322
323 // Optimize latency of app switches.
324 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
325 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
326 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
327 if (mAppSwitchDueTime < *nextWakeupTime) {
328 *nextWakeupTime = mAppSwitchDueTime;
329 }
330
331 // Ready to start a new event.
332 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700333 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700334 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800335 if (isAppSwitchDue) {
336 // The inbound queue is empty so the app switch key we were waiting
337 // for will never arrive. Stop waiting for it.
338 resetPendingAppSwitchLocked(false);
339 isAppSwitchDue = false;
340 }
341
342 // Synthesize a key repeat if appropriate.
343 if (mKeyRepeatState.lastKeyEntry) {
344 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
345 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
346 } else {
347 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
348 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
349 }
350 }
351 }
352
353 // Nothing to do if there is no pending event.
354 if (!mPendingEvent) {
355 return;
356 }
357 } else {
358 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700359 mPendingEvent = mInboundQueue.front();
360 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800361 traceInboundQueueLengthLocked();
362 }
363
364 // Poke user activity for this event.
365 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
366 pokeUserActivityLocked(mPendingEvent);
367 }
368
369 // Get ready to dispatch the event.
370 resetANRTimeoutsLocked();
371 }
372
373 // Now we have an event to dispatch.
374 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700375 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800376 bool done = false;
377 DropReason dropReason = DROP_REASON_NOT_DROPPED;
378 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
379 dropReason = DROP_REASON_POLICY;
380 } else if (!mDispatchEnabled) {
381 dropReason = DROP_REASON_DISABLED;
382 }
383
384 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700385 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800386 }
387
388 switch (mPendingEvent->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700389 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
390 ConfigurationChangedEntry* typedEntry =
391 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
392 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
393 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
394 break;
395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800396
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700397 case EventEntry::TYPE_DEVICE_RESET: {
398 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
399 done = dispatchDeviceResetLocked(currentTime, typedEntry);
400 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
401 break;
402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700404 case EventEntry::TYPE_KEY: {
405 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
406 if (isAppSwitchDue) {
407 if (isAppSwitchKeyEvent(typedEntry)) {
408 resetPendingAppSwitchLocked(true);
409 isAppSwitchDue = false;
410 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
411 dropReason = DROP_REASON_APP_SWITCH;
412 }
413 }
414 if (dropReason == DROP_REASON_NOT_DROPPED && isStaleEvent(currentTime, typedEntry)) {
415 dropReason = DROP_REASON_STALE;
416 }
417 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
418 dropReason = DROP_REASON_BLOCKED;
419 }
420 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
421 break;
422 }
423
424 case EventEntry::TYPE_MOTION: {
425 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
426 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800427 dropReason = DROP_REASON_APP_SWITCH;
428 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700429 if (dropReason == DROP_REASON_NOT_DROPPED && isStaleEvent(currentTime, typedEntry)) {
430 dropReason = DROP_REASON_STALE;
431 }
432 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
433 dropReason = DROP_REASON_BLOCKED;
434 }
435 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
436 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700439 default:
440 ALOG_ASSERT(false);
441 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800442 }
443
444 if (done) {
445 if (dropReason != DROP_REASON_NOT_DROPPED) {
446 dropInboundEventLocked(mPendingEvent, dropReason);
447 }
Michael Wright3a981722015-06-10 15:26:13 +0100448 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449
450 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700451 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452 }
453}
454
455bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700456 bool needWake = mInboundQueue.empty();
457 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458 traceInboundQueueLengthLocked();
459
460 switch (entry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700461 case EventEntry::TYPE_KEY: {
462 // Optimize app switch latency.
463 // If the application takes too long to catch up then we drop all events preceding
464 // the app switch key.
465 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
466 if (isAppSwitchKeyEvent(keyEntry)) {
467 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
468 mAppSwitchSawKeyDown = true;
469 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
470 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800471#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700472 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800473#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700474 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
475 mAppSwitchSawKeyDown = false;
476 needWake = true;
477 }
478 }
479 }
480 break;
481 }
482
483 case EventEntry::TYPE_MOTION: {
484 // Optimize case where the current application is unresponsive and the user
485 // decides to touch a window in a different application.
486 // If the application takes too long to catch up then we drop all events preceding
487 // the touch into the other window.
488 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
489 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
490 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
491 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
492 mInputTargetWaitApplicationToken != nullptr) {
493 int32_t displayId = motionEntry->displayId;
494 int32_t x =
495 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
496 int32_t y =
497 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
498 sp<InputWindowHandle> touchedWindowHandle =
499 findTouchedWindowAtLocked(displayId, x, y);
500 if (touchedWindowHandle != nullptr &&
501 touchedWindowHandle->getApplicationToken() !=
502 mInputTargetWaitApplicationToken) {
503 // User touched a different application than the one we are waiting on.
504 // Flag the event, and start pruning the input queue.
505 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 needWake = true;
507 }
508 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700509 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 }
512
513 return needWake;
514}
515
516void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
517 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700518 mRecentQueue.push_back(entry);
519 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
520 mRecentQueue.front()->release();
521 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 }
523}
524
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700525sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
526 int32_t y, bool addOutsideTargets,
527 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800529 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
530 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531 const InputWindowInfo* windowInfo = windowHandle->getInfo();
532 if (windowInfo->displayId == displayId) {
533 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534
535 if (windowInfo->visible) {
536 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700537 bool isTouchModal = (flags &
538 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
539 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800541 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700542 if (portalToDisplayId != ADISPLAY_ID_NONE &&
543 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800544 if (addPortalWindows) {
545 // For the monitoring channels of the display.
546 mTempTouchState.addPortalWindow(windowHandle);
547 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700548 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
549 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551 // Found window.
552 return windowHandle;
553 }
554 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800555
556 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700557 mTempTouchState.addOrUpdateWindow(windowHandle,
558 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
559 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800560 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 }
563 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700564 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565}
566
Garfield Tane84e6f92019-08-29 17:28:41 -0700567std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000568 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
569 std::vector<TouchedMonitor> touchedMonitors;
570
571 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
572 addGestureMonitors(monitors, touchedMonitors);
573 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
574 const InputWindowInfo* windowInfo = portalWindow->getInfo();
575 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700576 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
577 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000578 }
579 return touchedMonitors;
580}
581
582void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700583 std::vector<TouchedMonitor>& outTouchedMonitors,
584 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000585 if (monitors.empty()) {
586 return;
587 }
588 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
589 for (const Monitor& monitor : monitors) {
590 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
591 }
592}
593
Michael Wrightd02c5b62014-02-10 15:10:22 -0800594void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
595 const char* reason;
596 switch (dropReason) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700597 case DROP_REASON_POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700599 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700601 reason = "inbound event was dropped because the policy consumed it";
602 break;
603 case DROP_REASON_DISABLED:
604 if (mLastDropReason != DROP_REASON_DISABLED) {
605 ALOGI("Dropped event because input dispatch is disabled.");
606 }
607 reason = "inbound event was dropped because input dispatch is disabled";
608 break;
609 case DROP_REASON_APP_SWITCH:
610 ALOGI("Dropped event because of pending overdue app switch.");
611 reason = "inbound event was dropped because of pending overdue app switch";
612 break;
613 case DROP_REASON_BLOCKED:
614 ALOGI("Dropped event because the current application is not responding and the user "
615 "has started interacting with a different application.");
616 reason = "inbound event was dropped because the current application is not responding "
617 "and the user has started interacting with a different application";
618 break;
619 case DROP_REASON_STALE:
620 ALOGI("Dropped event because it is stale.");
621 reason = "inbound event was dropped because it is stale";
622 break;
623 default:
624 ALOG_ASSERT(false);
625 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 }
627
628 switch (entry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700629 case EventEntry::TYPE_KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
631 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700632 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700634 case EventEntry::TYPE_MOTION: {
635 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
636 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
637 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
638 synthesizeCancelationEventsForAllConnectionsLocked(options);
639 } else {
640 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
641 synthesizeCancelationEventsForAllConnectionsLocked(options);
642 }
643 break;
644 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645 }
646}
647
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800648static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700649 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
650 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651}
652
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800653bool InputDispatcher::isAppSwitchKeyEvent(KeyEntry* keyEntry) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700654 return !(keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry->keyCode) &&
655 (keyEntry->policyFlags & POLICY_FLAG_TRUSTED) &&
656 (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800657}
658
659bool InputDispatcher::isAppSwitchPendingLocked() {
660 return mAppSwitchDueTime != LONG_LONG_MAX;
661}
662
663void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
664 mAppSwitchDueTime = LONG_LONG_MAX;
665
666#if DEBUG_APP_SWITCH
667 if (handled) {
668 ALOGD("App switch has arrived.");
669 } else {
670 ALOGD("App switch was abandoned.");
671 }
672#endif
673}
674
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800675bool InputDispatcher::isStaleEvent(nsecs_t currentTime, EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
677}
678
679bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700680 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681}
682
683bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700684 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685 return false;
686 }
687
688 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700689 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700690 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700692 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693
694 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700695 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696 return true;
697}
698
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700699void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
700 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701}
702
703void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700704 while (!mInboundQueue.empty()) {
705 EventEntry* entry = mInboundQueue.front();
706 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 releaseInboundEventLocked(entry);
708 }
709 traceInboundQueueLengthLocked();
710}
711
712void InputDispatcher::releasePendingEventLocked() {
713 if (mPendingEvent) {
714 resetANRTimeoutsLocked();
715 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700716 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717 }
718}
719
720void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
721 InjectionState* injectionState = entry->injectionState;
722 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
723#if DEBUG_DISPATCH_CYCLE
724 ALOGD("Injected inbound event was dropped.");
725#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800726 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727 }
728 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700729 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 }
731 addRecentEventLocked(entry);
732 entry->release();
733}
734
735void InputDispatcher::resetKeyRepeatLocked() {
736 if (mKeyRepeatState.lastKeyEntry) {
737 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700738 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739 }
740}
741
Garfield Tane84e6f92019-08-29 17:28:41 -0700742KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800743 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
744
745 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700746 uint32_t policyFlags = entry->policyFlags &
747 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 if (entry->refCount == 1) {
749 entry->recycle();
750 entry->eventTime = currentTime;
751 entry->policyFlags = policyFlags;
752 entry->repeatCount += 1;
753 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700754 KeyEntry* newEntry =
755 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId,
756 entry->source, entry->displayId, policyFlags, entry->action,
757 entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
758 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759
760 mKeyRepeatState.lastKeyEntry = newEntry;
761 entry->release();
762
763 entry = newEntry;
764 }
765 entry->syntheticRepeat = true;
766
767 // Increment reference count since we keep a reference to the event in
768 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
769 entry->refCount += 1;
770
771 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
772 return entry;
773}
774
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700775bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
776 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700778 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779#endif
780
781 // Reset key repeating in case a keyboard device was added or removed or something.
782 resetKeyRepeatLocked();
783
784 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700785 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
786 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700788 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789 return true;
790}
791
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700792bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700794 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700795 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796#endif
797
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700798 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 options.deviceId = entry->deviceId;
800 synthesizeCancelationEventsForAllConnectionsLocked(options);
801 return true;
802}
803
804bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700807 if (!entry->dispatchInProgress) {
808 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
809 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
810 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
811 if (mKeyRepeatState.lastKeyEntry &&
812 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 // We have seen two identical key downs in a row which indicates that the device
814 // driver is automatically generating key repeats itself. We take note of the
815 // repeat here, but we disable our own next key repeat timer since it is clear that
816 // we will not need to synthesize key repeats ourselves.
817 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
818 resetKeyRepeatLocked();
819 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
820 } else {
821 // Not a repeat. Save key down state in case we do see a repeat later.
822 resetKeyRepeatLocked();
823 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
824 }
825 mKeyRepeatState.lastKeyEntry = entry;
826 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700827 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800828 resetKeyRepeatLocked();
829 }
830
831 if (entry->repeatCount == 1) {
832 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
833 } else {
834 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
835 }
836
837 entry->dispatchInProgress = true;
838
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800839 logOutboundKeyDetails("dispatchKey - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840 }
841
842 // Handle case where the policy asked us to try again later last time.
843 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
844 if (currentTime < entry->interceptKeyWakeupTime) {
845 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
846 *nextWakeupTime = entry->interceptKeyWakeupTime;
847 }
848 return false; // wait until next wakeup
849 }
850 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
851 entry->interceptKeyWakeupTime = 0;
852 }
853
854 // Give the policy a chance to intercept the key.
855 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
856 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700857 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -0700858 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800859 sp<InputWindowHandle> focusedWindowHandle =
860 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
861 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863 }
864 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700865 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 entry->refCount += 1;
867 return false; // wait for the command to run
868 } else {
869 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
870 }
871 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
872 if (*dropReason == DROP_REASON_NOT_DROPPED) {
873 *dropReason = DROP_REASON_POLICY;
874 }
875 }
876
877 // Clean up if dropping the event.
878 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 setInjectionResult(entry,
880 *dropReason == DROP_REASON_POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
881 : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800882 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 return true;
884 }
885
886 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800887 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 int32_t injectionResult =
889 findFocusedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
891 return false;
892 }
893
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800894 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
896 return true;
897 }
898
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800899 // Add monitor channels from event's or focused display.
Michael Wright3dd60e22019-03-27 22:06:44 +0000900 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901
902 // Dispatch the key.
903 dispatchEventLocked(currentTime, entry, inputTargets);
904 return true;
905}
906
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800907void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100909 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700910 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
911 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
912 prefix, entry->eventTime, entry->deviceId, entry->source, entry->displayId,
913 entry->policyFlags, entry->action, entry->flags, entry->keyCode, entry->scanCode,
914 entry->metaState, entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800915#endif
916}
917
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700918bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
919 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000920 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700922 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 entry->dispatchInProgress = true;
924
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800925 logOutboundMotionDetails("dispatchMotion - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 }
927
928 // Clean up if dropping the event.
929 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700930 setInjectionResult(entry,
931 *dropReason == DROP_REASON_POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
932 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 return true;
934 }
935
936 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
937
938 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800939 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940
941 bool conflictingPointerActions = false;
942 int32_t injectionResult;
943 if (isPointerEvent) {
944 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700945 injectionResult =
946 findTouchedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime,
947 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948 } else {
949 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700950 injectionResult =
951 findFocusedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 }
953 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
954 return false;
955 }
956
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800957 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100959 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700960 CancelationOptions::Mode mode(isPointerEvent
961 ? CancelationOptions::CANCEL_POINTER_EVENTS
962 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100963 CancelationOptions options(mode, "input event injection failed");
964 synthesizeCancelationEventsForMonitorsLocked(options);
965 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 return true;
967 }
968
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800969 // Add monitor channels from event's or focused display.
Michael Wright3dd60e22019-03-27 22:06:44 +0000970 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800972 if (isPointerEvent) {
973 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
974 if (stateIndex >= 0) {
975 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800976 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800977 // The event has gone through these portal windows, so we add monitoring targets of
978 // the corresponding displays as well.
979 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800980 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +0000981 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700982 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800983 }
984 }
985 }
986 }
987
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988 // Dispatch the motion.
989 if (conflictingPointerActions) {
990 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700991 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 synthesizeCancelationEventsForAllConnectionsLocked(options);
993 }
994 dispatchEventLocked(currentTime, entry, inputTargets);
995 return true;
996}
997
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800998void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001000 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001001 ", policyFlags=0x%x, "
1002 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1003 "metaState=0x%x, buttonState=0x%x,"
1004 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1005 prefix, entry->eventTime, entry->deviceId, entry->source, entry->displayId,
1006 entry->policyFlags, entry->action, entry->actionButton, entry->flags, entry->metaState,
1007 entry->buttonState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
1008 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009
1010 for (uint32_t i = 0; i < entry->pointerCount; i++) {
1011 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001012 "x=%f, y=%f, pressure=%f, size=%f, "
1013 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1014 "orientation=%f",
1015 i, entry->pointerProperties[i].id, entry->pointerProperties[i].toolType,
1016 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1017 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1018 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1019 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1020 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1021 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1022 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1023 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1024 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 }
1026#endif
1027}
1028
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001029void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1030 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001031 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032#if DEBUG_DISPATCH_CYCLE
1033 ALOGD("dispatchEventToCurrentInputTargets");
1034#endif
1035
1036 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1037
1038 pokeUserActivityLocked(eventEntry);
1039
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001040 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001041 sp<Connection> connection = getConnectionLocked(inputTarget.inputChannel);
1042 if (connection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1044 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001045 if (DEBUG_FOCUS) {
1046 ALOGD("Dropping event delivery to target with channel '%s' because it "
1047 "is no longer registered with the input dispatcher.",
1048 inputTarget.inputChannel->getName().c_str());
1049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 }
1051 }
1052}
1053
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001054int32_t InputDispatcher::handleTargetsNotReadyLocked(
1055 nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001057 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001058 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001060 if (DEBUG_FOCUS) {
1061 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1064 mInputTargetWaitStartTime = currentTime;
1065 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1066 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001067 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 }
1069 } else {
1070 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001071 if (DEBUG_FOCUS) {
1072 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
1073 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001076 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001078 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001079 timeout =
1080 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081 } else {
1082 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1083 }
1084
1085 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1086 mInputTargetWaitStartTime = currentTime;
1087 mInputTargetWaitTimeoutTime = currentTime + timeout;
1088 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001089 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090
Yi Kong9b14ac62018-07-17 13:48:38 -07001091 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001092 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093 }
Robert Carr740167f2018-10-11 19:03:41 -07001094 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1095 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096 }
1097 }
1098 }
1099
1100 if (mInputTargetWaitTimeoutExpired) {
1101 return INPUT_EVENT_INJECTION_TIMED_OUT;
1102 }
1103
1104 if (currentTime >= mInputTargetWaitTimeoutTime) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 onANRLocked(currentTime, applicationHandle, windowHandle, entry->eventTime,
1106 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107
1108 // Force poll loop to wake up immediately on next iteration once we get the
1109 // ANR response back from the policy.
1110 *nextWakeupTime = LONG_LONG_MIN;
1111 return INPUT_EVENT_INJECTION_PENDING;
1112 } else {
1113 // Force poll loop to wake up when timeout is due.
1114 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1115 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1116 }
1117 return INPUT_EVENT_INJECTION_PENDING;
1118 }
1119}
1120
Robert Carr803535b2018-08-02 16:38:15 -07001121void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1122 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1123 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1124 state.removeWindowByToken(token);
1125 }
1126}
1127
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
1129 nsecs_t newTimeout, const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 if (newTimeout > 0) {
1131 // Extend the timeout.
1132 mInputTargetWaitTimeoutTime = now() + newTimeout;
1133 } else {
1134 // Give up.
1135 mInputTargetWaitTimeoutExpired = true;
1136
1137 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001138 sp<Connection> connection = getConnectionLocked(inputChannel);
1139 if (connection != nullptr) {
1140 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001142 if (token != nullptr) {
1143 removeWindowByTokenLocked(token);
1144 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001146 if (connection->status == Connection::STATUS_NORMAL) {
1147 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1148 "application not responding");
1149 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150 }
1151 }
1152 }
1153}
1154
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001155nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1157 return currentTime - mInputTargetWaitStartTime;
1158 }
1159 return 0;
1160}
1161
1162void InputDispatcher::resetANRTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001163 if (DEBUG_FOCUS) {
1164 ALOGD("Resetting ANR timeouts.");
1165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166
1167 // Reset input target wait timeout.
1168 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001169 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170}
1171
Tiger Huang721e26f2018-07-24 22:26:19 +08001172/**
1173 * Get the display id that the given event should go to. If this event specifies a valid display id,
1174 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1175 * Focused display is the display that the user most recently interacted with.
1176 */
1177int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1178 int32_t displayId;
1179 switch (entry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001180 case EventEntry::TYPE_KEY: {
1181 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1182 displayId = typedEntry->displayId;
1183 break;
1184 }
1185 case EventEntry::TYPE_MOTION: {
1186 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1187 displayId = typedEntry->displayId;
1188 break;
1189 }
1190 default: {
1191 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1192 return ADISPLAY_ID_NONE;
1193 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001194 }
1195 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1196}
1197
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001199 const EventEntry* entry,
1200 std::vector<InputTarget>& inputTargets,
1201 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001203 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204
Tiger Huang721e26f2018-07-24 22:26:19 +08001205 int32_t displayId = getTargetDisplayId(entry);
1206 sp<InputWindowHandle> focusedWindowHandle =
1207 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1208 sp<InputApplicationHandle> focusedApplicationHandle =
1209 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1210
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 // If there is no currently focused window and no focused application
1212 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001213 if (focusedWindowHandle == nullptr) {
1214 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001215 injectionResult =
1216 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1217 nullptr, nextWakeupTime,
1218 "Waiting because no window has focus but there is "
1219 "a focused application that may eventually add a "
1220 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 goto Unresponsive;
1222 }
1223
Arthur Hung3b413f22018-10-26 18:05:34 +08001224 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001225 "%" PRId32 ".",
1226 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1228 goto Failed;
1229 }
1230
1231 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001232 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1234 goto Failed;
1235 }
1236
Jeff Brownffb49772014-10-10 19:01:34 -07001237 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001238 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001239 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001240 injectionResult =
1241 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1242 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 goto Unresponsive;
1244 }
1245
1246 // Success! Output targets.
1247 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001248 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001249 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1250 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251
1252 // Done.
1253Failed:
1254Unresponsive:
1255 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001256 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001257 if (DEBUG_FOCUS) {
1258 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1259 "timeSpentWaitingForApplication=%0.1fms",
1260 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 return injectionResult;
1263}
1264
1265int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001266 const MotionEntry* entry,
1267 std::vector<InputTarget>& inputTargets,
1268 nsecs_t* nextWakeupTime,
1269 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001270 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 enum InjectionPermission {
1272 INJECTION_PERMISSION_UNKNOWN,
1273 INJECTION_PERMISSION_GRANTED,
1274 INJECTION_PERMISSION_DENIED
1275 };
1276
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 // For security reasons, we defer updating the touch state until we are sure that
1278 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 int32_t displayId = entry->displayId;
1280 int32_t action = entry->action;
1281 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1282
1283 // Update the touch state as needed based on the properties of the touch event.
1284 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1285 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1286 sp<InputWindowHandle> newHoverWindowHandle;
1287
Jeff Brownf086ddb2014-02-11 14:28:48 -08001288 // Copy current touch state into mTempTouchState.
1289 // This state is always reset at the end of this function, so if we don't find state
1290 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001291 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001292 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1293 if (oldStateIndex >= 0) {
1294 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1295 mTempTouchState.copyFrom(*oldState);
1296 }
1297
1298 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001299 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
1300 (mTempTouchState.deviceId != entry->deviceId ||
1301 mTempTouchState.source != entry->source || mTempTouchState.displayId != displayId);
1302 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1303 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1304 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1305 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1306 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Garfield Tan00f511d2019-06-12 16:55:40 -07001307 const bool isFromMouse = entry->source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 bool wrongDevice = false;
1309 if (newGesture) {
1310 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001311 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001312 if (DEBUG_FOCUS) {
1313 ALOGD("Dropping event because a pointer for a different device is already down "
1314 "in display %" PRId32,
1315 displayId);
1316 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001317 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1319 switchedDevice = false;
1320 wrongDevice = true;
1321 goto Failed;
1322 }
1323 mTempTouchState.reset();
1324 mTempTouchState.down = down;
1325 mTempTouchState.deviceId = entry->deviceId;
1326 mTempTouchState.source = entry->source;
1327 mTempTouchState.displayId = displayId;
1328 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001329 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001330 if (DEBUG_FOCUS) {
1331 ALOGI("Dropping move event because a pointer for a different device is already active "
1332 "in display %" PRId32,
1333 displayId);
1334 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001335 // TODO: test multiple simultaneous input streams.
1336 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1337 switchedDevice = false;
1338 wrongDevice = true;
1339 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 }
1341
1342 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1343 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1344
Garfield Tan00f511d2019-06-12 16:55:40 -07001345 int32_t x;
1346 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001348 // Always dispatch mouse events to cursor position.
1349 if (isFromMouse) {
1350 x = int32_t(entry->xCursorPosition);
1351 y = int32_t(entry->yCursorPosition);
1352 } else {
1353 x = int32_t(entry->pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1354 y = int32_t(entry->pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
1355 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001356 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001357 sp<InputWindowHandle> newTouchedWindowHandle =
1358 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1359 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001360
1361 std::vector<TouchedMonitor> newGestureMonitors = isDown
1362 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1363 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001366 if (newTouchedWindowHandle != nullptr &&
1367 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001368 // New window supports splitting, but we should never split mouse events.
1369 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 } else if (isSplit) {
1371 // New window does not support splitting but we have already split events.
1372 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001373 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374 }
1375
1376 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001377 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 // Try to assign the pointer to the first foreground window we find, if there is one.
1379 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001380 }
1381
1382 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1383 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001384 "(%d, %d) in display %" PRId32 ".",
1385 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001386 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1387 goto Failed;
1388 }
1389
1390 if (newTouchedWindowHandle != nullptr) {
1391 // Set target flags.
1392 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1393 if (isSplit) {
1394 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001396 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1397 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1398 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1399 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1400 }
1401
1402 // Update hover state.
1403 if (isHoverAction) {
1404 newHoverWindowHandle = newTouchedWindowHandle;
1405 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1406 newHoverWindowHandle = mLastHoverWindowHandle;
1407 }
1408
1409 // Update the temporary touch state.
1410 BitSet32 pointerIds;
1411 if (isSplit) {
1412 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1413 pointerIds.markBit(pointerId);
1414 }
1415 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416 }
1417
Michael Wright3dd60e22019-03-27 22:06:44 +00001418 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 } else {
1420 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1421
1422 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001423 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001424 if (DEBUG_FOCUS) {
1425 ALOGD("Dropping event because the pointer is not down or we previously "
1426 "dropped the pointer down event in display %" PRId32,
1427 displayId);
1428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1430 goto Failed;
1431 }
1432
1433 // Check whether touches should slip outside of the current foreground window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001434 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry->pointerCount == 1 &&
1435 mTempTouchState.isSlippery()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1437 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1438
1439 sp<InputWindowHandle> oldTouchedWindowHandle =
1440 mTempTouchState.getFirstForegroundWindowHandle();
1441 sp<InputWindowHandle> newTouchedWindowHandle =
1442 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001443 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1444 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001445 if (DEBUG_FOCUS) {
1446 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1447 oldTouchedWindowHandle->getName().c_str(),
1448 newTouchedWindowHandle->getName().c_str(), displayId);
1449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450 // Make a slippery exit from the old window.
1451 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001452 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1453 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454
1455 // Make a slippery entrance into the new window.
1456 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1457 isSplit = true;
1458 }
1459
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001460 int32_t targetFlags =
1461 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 if (isSplit) {
1463 targetFlags |= InputTarget::FLAG_SPLIT;
1464 }
1465 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1466 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1467 }
1468
1469 BitSet32 pointerIds;
1470 if (isSplit) {
1471 pointerIds.markBit(entry->pointerProperties[0].id);
1472 }
1473 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1474 }
1475 }
1476 }
1477
1478 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1479 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001480 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481#if DEBUG_HOVER
1482 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001483 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484#endif
1485 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001486 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1487 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 }
1489
1490 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001491 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492#if DEBUG_HOVER
1493 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001494 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495#endif
1496 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001497 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1498 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 }
1500 }
1501
1502 // Check permission to inject into all touched foreground windows and ensure there
1503 // is at least one touched foreground window.
1504 {
1505 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001506 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1508 haveForegroundWindow = true;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001509 if (!checkInjectionPermission(touchedWindow.windowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1511 injectionPermission = INJECTION_PERMISSION_DENIED;
1512 goto Failed;
1513 }
1514 }
1515 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001516 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1517 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001518 if (DEBUG_FOCUS) {
1519 ALOGD("Dropping event because there is no touched foreground window in display "
1520 "%" PRId32 " or gesture monitor to receive it.",
1521 displayId);
1522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1524 goto Failed;
1525 }
1526
1527 // Permission granted to injection into all touched foreground windows.
1528 injectionPermission = INJECTION_PERMISSION_GRANTED;
1529 }
1530
1531 // Check whether windows listening for outside touches are owned by the same UID. If it is
1532 // set the policy flag that we will not reveal coordinate information to this window.
1533 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1534 sp<InputWindowHandle> foregroundWindowHandle =
1535 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001536 if (foregroundWindowHandle) {
1537 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1538 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1539 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1540 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1541 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1542 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001543 InputTarget::FLAG_ZERO_COORDS,
1544 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 }
1547 }
1548 }
1549 }
1550
1551 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001552 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001554 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001555 std::string reason =
1556 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1557 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001558 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001559 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1560 touchedWindow.windowHandle,
1561 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 goto Unresponsive;
1563 }
1564 }
1565 }
1566
1567 // If this is the first pointer going down and the touched window has a wallpaper
1568 // then also add the touched wallpaper windows so they are locked in for the duration
1569 // of the touch gesture.
1570 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1571 // engine only supports touch events. We would need to add a mechanism similar
1572 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1573 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1574 sp<InputWindowHandle> foregroundWindowHandle =
1575 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001576 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001577 const std::vector<sp<InputWindowHandle>> windowHandles =
1578 getWindowHandlesLocked(displayId);
1579 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001581 if (info->displayId == displayId &&
1582 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1583 mTempTouchState
1584 .addOrUpdateWindow(windowHandle,
1585 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1586 InputTarget::
1587 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1588 InputTarget::FLAG_DISPATCH_AS_IS,
1589 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 }
1591 }
1592 }
1593 }
1594
1595 // Success! Output targets.
1596 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1597
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001598 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001600 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601 }
1602
Michael Wright3dd60e22019-03-27 22:06:44 +00001603 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1604 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001605 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001606 }
1607
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 // Drop the outside or hover touch windows since we will not care about them
1609 // in the next iteration.
1610 mTempTouchState.filterNonAsIsTouchWindows();
1611
1612Failed:
1613 // Check injection permission once and for all.
1614 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001615 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 injectionPermission = INJECTION_PERMISSION_GRANTED;
1617 } else {
1618 injectionPermission = INJECTION_PERMISSION_DENIED;
1619 }
1620 }
1621
1622 // Update final pieces of touch state if the injector had permission.
1623 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1624 if (!wrongDevice) {
1625 if (switchedDevice) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001626 if (DEBUG_FOCUS) {
1627 ALOGD("Conflicting pointer actions: Switched to a different device.");
1628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 *outConflictingPointerActions = true;
1630 }
1631
1632 if (isHoverAction) {
1633 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001634 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001635 if (DEBUG_FOCUS) {
1636 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1637 "down.");
1638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 *outConflictingPointerActions = true;
1640 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001641 mTempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001642 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1643 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001644 mTempTouchState.deviceId = entry->deviceId;
1645 mTempTouchState.source = entry->source;
1646 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001648 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1649 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001651 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1653 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001654 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001655 if (DEBUG_FOCUS) {
1656 ALOGD("Conflicting pointer actions: Down received while already down.");
1657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 *outConflictingPointerActions = true;
1659 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1661 // One pointer went up.
1662 if (isSplit) {
1663 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1664 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1665
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001666 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001667 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1669 touchedWindow.pointerIds.clearBit(pointerId);
1670 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001671 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 continue;
1673 }
1674 }
1675 i += 1;
1676 }
1677 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001678 }
1679
1680 // Save changes unless the action was scroll in which case the temporary touch
1681 // state was only valid for this one action.
1682 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1683 if (mTempTouchState.displayId >= 0) {
1684 if (oldStateIndex >= 0) {
1685 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1686 } else {
1687 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1688 }
1689 } else if (oldStateIndex >= 0) {
1690 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692 }
1693
1694 // Update hover state.
1695 mLastHoverWindowHandle = newHoverWindowHandle;
1696 }
1697 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001698 if (DEBUG_FOCUS) {
1699 ALOGD("Not updating touch focus because injection was denied.");
1700 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701 }
1702
1703Unresponsive:
1704 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1705 mTempTouchState.reset();
1706
1707 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001708 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001709 if (DEBUG_FOCUS) {
1710 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1711 "timeSpentWaitingForApplication=%0.1fms",
1712 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 return injectionResult;
1715}
1716
1717void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001718 int32_t targetFlags, BitSet32 pointerIds,
1719 std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001720 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1721 if (inputChannel == nullptr) {
1722 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1723 return;
1724 }
1725
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001727 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001728 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 target.flags = targetFlags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001730 target.xOffset = -windowInfo->frameLeft;
1731 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001732 target.globalScaleFactor = windowInfo->globalScaleFactor;
1733 target.windowXScale = windowInfo->windowXScale;
1734 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001736 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737}
1738
Michael Wright3dd60e22019-03-27 22:06:44 +00001739void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001740 int32_t displayId, float xOffset,
1741 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001742 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1743 mGlobalMonitorsByDisplay.find(displayId);
1744
1745 if (it != mGlobalMonitorsByDisplay.end()) {
1746 const std::vector<Monitor>& monitors = it->second;
1747 for (const Monitor& monitor : monitors) {
1748 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 }
1751}
1752
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001753void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1754 float yOffset,
1755 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001756 InputTarget target;
1757 target.inputChannel = monitor.inputChannel;
1758 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1759 target.xOffset = xOffset;
1760 target.yOffset = yOffset;
1761 target.pointerIds.clear();
1762 target.globalScaleFactor = 1.0f;
1763 inputTargets.push_back(target);
1764}
1765
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001767 const InjectionState* injectionState) {
1768 if (injectionState &&
1769 (windowHandle == nullptr ||
1770 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1771 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001772 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001774 "owned by uid %d",
1775 injectionState->injectorPid, injectionState->injectorUid,
1776 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 } else {
1778 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001779 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 }
1781 return false;
1782 }
1783 return true;
1784}
1785
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001786bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1787 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001789 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1790 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 if (otherHandle == windowHandle) {
1792 break;
1793 }
1794
1795 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001796 if (otherInfo->displayId == displayId && otherInfo->visible &&
1797 !otherInfo->isTrustedOverlay() && otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 return true;
1799 }
1800 }
1801 return false;
1802}
1803
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001804bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1805 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001806 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001807 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001808 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001809 if (otherHandle == windowHandle) {
1810 break;
1811 }
1812
1813 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001814 if (otherInfo->displayId == displayId && otherInfo->visible &&
1815 !otherInfo->isTrustedOverlay() && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001816 return true;
1817 }
1818 }
1819 return false;
1820}
1821
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001822std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
1823 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
1824 const EventEntry* eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07001825 // If the window is paused then keep waiting.
1826 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001827 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001828 }
1829
1830 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001831 sp<Connection> connection =
1832 getConnectionLocked(getInputChannelLocked(windowHandle->getToken()));
1833 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001834 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001835 "registered with the input dispatcher. The window may be in the "
1836 "process of being removed.",
1837 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001838 }
1839
1840 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07001841 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001842 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001843 "The window may be in the process of being removed.",
1844 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07001845 }
1846
1847 // If the connection is backed up then keep waiting.
1848 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001849 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001850 "Outbound queue length: %zu. Wait queue length: %zu.",
1851 targetType, connection->outboundQueue.size(),
1852 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07001853 }
1854
1855 // Ensure that the dispatch queues aren't too far backed up for this event.
1856 if (eventEntry->type == EventEntry::TYPE_KEY) {
1857 // If the event is a key event, then we must wait for all previous events to
1858 // complete before delivering it because previous events may have the
1859 // side-effect of transferring focus to a different window and we want to
1860 // ensure that the following keys are sent to the new window.
1861 //
1862 // Suppose the user touches a button in a window then immediately presses "A".
1863 // If the button causes a pop-up window to appear then we want to ensure that
1864 // the "A" key is delivered to the new pop-up window. This is because users
1865 // often anticipate pending UI changes when typing on a keyboard.
1866 // To obtain this behavior, we must serialize key events with respect to all
1867 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001868 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001869 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001870 "finished processing all of the input events that were previously "
1871 "delivered to it. Outbound queue length: %zu. Wait queue length: "
1872 "%zu.",
1873 targetType, connection->outboundQueue.size(),
1874 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 }
Jeff Brownffb49772014-10-10 19:01:34 -07001876 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 // Touch events can always be sent to a window immediately because the user intended
1878 // to touch whatever was visible at the time. Even if focus changes or a new
1879 // window appears moments later, the touch event was meant to be delivered to
1880 // whatever window happened to be on screen at the time.
1881 //
1882 // Generic motion events, such as trackball or joystick events are a little trickier.
1883 // Like key events, generic motion events are delivered to the focused window.
1884 // Unlike key events, generic motion events don't tend to transfer focus to other
1885 // windows and it is not important for them to be serialized. So we prefer to deliver
1886 // generic motion events as soon as possible to improve efficiency and reduce lag
1887 // through batching.
1888 //
1889 // The one case where we pause input event delivery is when the wait queue is piling
1890 // up with lots of events because the application is not responding.
1891 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001892 if (!connection->waitQueue.empty() &&
1893 currentTime >=
1894 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001895 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001896 "finished processing certain input events that were delivered to "
1897 "it over "
1898 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
1899 "%0.1fms.",
1900 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1901 connection->waitQueue.size(),
1902 (currentTime - connection->waitQueue.front()->deliveryTime) *
1903 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 }
1905 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001906 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907}
1908
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001909std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 const sp<InputApplicationHandle>& applicationHandle,
1911 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001912 if (applicationHandle != nullptr) {
1913 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001914 std::string label(applicationHandle->getName());
1915 label += " - ";
1916 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 return label;
1918 } else {
1919 return applicationHandle->getName();
1920 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001921 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922 return windowHandle->getName();
1923 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001924 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 }
1926}
1927
1928void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001929 int32_t displayId = getTargetDisplayId(eventEntry);
1930 sp<InputWindowHandle> focusedWindowHandle =
1931 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1932 if (focusedWindowHandle != nullptr) {
1933 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1935#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001936 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937#endif
1938 return;
1939 }
1940 }
1941
1942 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1943 switch (eventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001944 case EventEntry::TYPE_MOTION: {
1945 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1946 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1947 return;
1948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001950 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1951 eventType = USER_ACTIVITY_EVENT_TOUCH;
1952 }
1953 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001955 case EventEntry::TYPE_KEY: {
1956 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1957 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1958 return;
1959 }
1960 eventType = USER_ACTIVITY_EVENT_BUTTON;
1961 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963 }
1964
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001965 std::unique_ptr<CommandEntry> commandEntry =
1966 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 commandEntry->eventTime = eventEntry->eventTime;
1968 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001969 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970}
1971
1972void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001973 const sp<Connection>& connection,
1974 EventEntry* eventEntry,
1975 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001976 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001977 std::string message =
1978 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
1979 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00001980 ATRACE_NAME(message.c_str());
1981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982#if DEBUG_DISPATCH_CYCLE
1983 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001984 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1985 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
1986 connection->getInputChannelName().c_str(), inputTarget->flags, inputTarget->xOffset,
1987 inputTarget->yOffset, inputTarget->globalScaleFactor, inputTarget->windowXScale,
1988 inputTarget->windowYScale, inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989#endif
1990
1991 // Skip this event if the connection status is not normal.
1992 // We don't want to enqueue additional outbound events if the connection is broken.
1993 if (connection->status != Connection::STATUS_NORMAL) {
1994#if DEBUG_DISPATCH_CYCLE
1995 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001996 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997#endif
1998 return;
1999 }
2000
2001 // Split a motion event if needed.
2002 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
2003 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
2004
2005 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
2006 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002007 MotionEntry* splitMotionEntry =
2008 splitMotionEvent(originalMotionEntry, inputTarget->pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 if (!splitMotionEntry) {
2010 return; // split event was dropped
2011 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002012 if (DEBUG_FOCUS) {
2013 ALOGD("channel '%s' ~ Split motion event.",
2014 connection->getInputChannelName().c_str());
2015 logOutboundMotionDetails(" ", splitMotionEntry);
2016 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002017 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 splitMotionEntry->release();
2019 return;
2020 }
2021 }
2022
2023 // Not splitting. Enqueue dispatch entries for the event as is.
2024 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2025}
2026
2027void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002028 const sp<Connection>& connection,
2029 EventEntry* eventEntry,
2030 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002031 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002032 std::string message =
2033 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32
2034 ")",
2035 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002036 ATRACE_NAME(message.c_str());
2037 }
2038
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002039 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040
2041 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002042 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002043 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002044 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002045 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002046 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002047 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002048 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002049 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002050 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002051 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002052 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002053 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054
2055 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002056 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 startDispatchCycleLocked(currentTime, connection);
2058 }
2059}
2060
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002061void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2062 EventEntry* eventEntry,
2063 const InputTarget* inputTarget,
2064 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002065 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002066 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2067 connection->getInputChannelName().c_str(),
2068 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002069 ATRACE_NAME(message.c_str());
2070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 int32_t inputTargetFlags = inputTarget->flags;
2072 if (!(inputTargetFlags & dispatchMode)) {
2073 return;
2074 }
2075 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2076
2077 // This is a new event.
2078 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002079 DispatchEntry* dispatchEntry =
2080 new DispatchEntry(eventEntry, // increments ref
2081 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
2082 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2083 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084
2085 // Apply target flags and update the connection's input state.
2086 switch (eventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002087 case EventEntry::TYPE_KEY: {
2088 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2089 dispatchEntry->resolvedAction = keyEntry->action;
2090 dispatchEntry->resolvedFlags = keyEntry->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002092 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2093 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002095 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2096 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002098 delete dispatchEntry;
2099 return; // skip the inconsistent event
2100 }
2101 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002104 case EventEntry::TYPE_MOTION: {
2105 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2106 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2107 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2108 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2109 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2110 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2111 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2112 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2113 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2114 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2115 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2116 } else {
2117 dispatchEntry->resolvedAction = motionEntry->action;
2118 }
2119 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
2120 !connection->inputState.isHovering(motionEntry->deviceId, motionEntry->source,
2121 motionEntry->displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002123 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2124 "event",
2125 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002127 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2128 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002130 dispatchEntry->resolvedFlags = motionEntry->flags;
2131 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2132 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2133 }
2134 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2135 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002138 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2139 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002141 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2142 "event",
2143 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002145 delete dispatchEntry;
2146 return; // skip the inconsistent event
2147 }
2148
2149 dispatchPointerDownOutsideFocus(motionEntry->source, dispatchEntry->resolvedAction,
2150 inputTarget->inputChannel->getToken());
2151
2152 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 }
2155
2156 // Remember that we are waiting for this dispatch to complete.
2157 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002158 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 }
2160
2161 // Enqueue the dispatch entry.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002162 connection->outboundQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002163 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002164}
2165
chaviwfd6d3512019-03-25 13:23:49 -07002166void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002167 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002168 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002169 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2170 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002171 return;
2172 }
2173
2174 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2175 if (inputWindowHandle == nullptr) {
2176 return;
2177 }
2178
chaviw8c9cf542019-03-25 13:02:48 -07002179 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002180 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002181
2182 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2183
2184 if (!hasFocusChanged) {
2185 return;
2186 }
2187
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002188 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2189 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002190 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002191 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192}
2193
2194void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002195 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002196 if (ATRACE_ENABLED()) {
2197 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002198 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002199 ATRACE_NAME(message.c_str());
2200 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002202 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203#endif
2204
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002205 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2206 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 dispatchEntry->deliveryTime = currentTime;
2208
2209 // Publish the event.
2210 status_t status;
2211 EventEntry* eventEntry = dispatchEntry->eventEntry;
2212 switch (eventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002213 case EventEntry::TYPE_KEY: {
2214 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002216 // Publish the key event.
2217 status = connection->inputPublisher
2218 .publishKeyEvent(dispatchEntry->seq, keyEntry->deviceId,
2219 keyEntry->source, keyEntry->displayId,
2220 dispatchEntry->resolvedAction,
2221 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2222 keyEntry->scanCode, keyEntry->metaState,
2223 keyEntry->repeatCount, keyEntry->downTime,
2224 keyEntry->eventTime);
2225 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 }
2227
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002228 case EventEntry::TYPE_MOTION: {
2229 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002231 PointerCoords scaledCoords[MAX_POINTERS];
2232 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2233
2234 // Set the X and Y offset depending on the input source.
2235 float xOffset, yOffset;
2236 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2237 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2238 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2239 float wxs = dispatchEntry->windowXScale;
2240 float wys = dispatchEntry->windowYScale;
2241 xOffset = dispatchEntry->xOffset * wxs;
2242 yOffset = dispatchEntry->yOffset * wys;
2243 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
2244 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2245 scaledCoords[i] = motionEntry->pointerCoords[i];
2246 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
2247 }
2248 usingCoords = scaledCoords;
2249 }
2250 } else {
2251 xOffset = 0.0f;
2252 yOffset = 0.0f;
2253
2254 // We don't want the dispatch target to know.
2255 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2256 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2257 scaledCoords[i].clear();
2258 }
2259 usingCoords = scaledCoords;
2260 }
2261 }
2262
2263 // Publish the motion event.
2264 status = connection->inputPublisher
2265 .publishMotionEvent(dispatchEntry->seq, motionEntry->deviceId,
2266 motionEntry->source, motionEntry->displayId,
2267 dispatchEntry->resolvedAction,
2268 motionEntry->actionButton,
2269 dispatchEntry->resolvedFlags,
2270 motionEntry->edgeFlags, motionEntry->metaState,
2271 motionEntry->buttonState,
2272 motionEntry->classification, xOffset, yOffset,
2273 motionEntry->xPrecision,
2274 motionEntry->yPrecision,
2275 motionEntry->xCursorPosition,
2276 motionEntry->yCursorPosition,
2277 motionEntry->downTime, motionEntry->eventTime,
2278 motionEntry->pointerCount,
2279 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002280 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002281 break;
2282 }
2283
2284 default:
2285 ALOG_ASSERT(false);
2286 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 }
2288
2289 // Check the result.
2290 if (status) {
2291 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002292 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002294 "This is unexpected because the wait queue is empty, so the pipe "
2295 "should be empty and we shouldn't have any problems writing an "
2296 "event to it, status=%d",
2297 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2299 } else {
2300 // Pipe is full and we are waiting for the app to finish process some events
2301 // before sending more events to it.
2302#if DEBUG_DISPATCH_CYCLE
2303 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002304 "waiting for the application to catch up",
2305 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306#endif
2307 connection->inputPublisherBlocked = true;
2308 }
2309 } else {
2310 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002311 "status=%d",
2312 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2314 }
2315 return;
2316 }
2317
2318 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002319 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2320 connection->outboundQueue.end(),
2321 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002322 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002323 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002324 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 }
2326}
2327
2328void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002329 const sp<Connection>& connection, uint32_t seq,
2330 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331#if DEBUG_DISPATCH_CYCLE
2332 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002333 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334#endif
2335
2336 connection->inputPublisherBlocked = false;
2337
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002338 if (connection->status == Connection::STATUS_BROKEN ||
2339 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 return;
2341 }
2342
2343 // Notify other system components and prepare to start the next dispatch cycle.
2344 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2345}
2346
2347void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002348 const sp<Connection>& connection,
2349 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350#if DEBUG_DISPATCH_CYCLE
2351 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002352 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353#endif
2354
2355 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002356 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002357 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002358 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002359 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002360
2361 // The connection appears to be unrecoverably broken.
2362 // Ignore already broken or zombie connections.
2363 if (connection->status == Connection::STATUS_NORMAL) {
2364 connection->status = Connection::STATUS_BROKEN;
2365
2366 if (notify) {
2367 // Notify other system components.
2368 onDispatchCycleBrokenLocked(currentTime, connection);
2369 }
2370 }
2371}
2372
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002373void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2374 while (!queue.empty()) {
2375 DispatchEntry* dispatchEntry = queue.front();
2376 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002377 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 }
2379}
2380
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002381void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002383 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384 }
2385 delete dispatchEntry;
2386}
2387
2388int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2389 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2390
2391 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002392 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002394 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002396 "fd=%d, events=0x%x",
2397 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 return 0; // remove the callback
2399 }
2400
2401 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002402 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2404 if (!(events & ALOOPER_EVENT_INPUT)) {
2405 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002406 "events=0x%x",
2407 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 return 1;
2409 }
2410
2411 nsecs_t currentTime = now();
2412 bool gotOne = false;
2413 status_t status;
2414 for (;;) {
2415 uint32_t seq;
2416 bool handled;
2417 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2418 if (status) {
2419 break;
2420 }
2421 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2422 gotOne = true;
2423 }
2424 if (gotOne) {
2425 d->runCommandsLockedInterruptible();
2426 if (status == WOULD_BLOCK) {
2427 return 1;
2428 }
2429 }
2430
2431 notify = status != DEAD_OBJECT || !connection->monitor;
2432 if (notify) {
2433 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002434 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435 }
2436 } else {
2437 // Monitor channels are never explicitly unregistered.
2438 // We do it automatically when the remote endpoint is closed so don't warn
2439 // about them.
2440 notify = !connection->monitor;
2441 if (notify) {
2442 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002443 "events=0x%x",
2444 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445 }
2446 }
2447
2448 // Unregister the channel.
2449 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2450 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002451 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452}
2453
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002454void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002456 for (const auto& pair : mConnectionsByFd) {
2457 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 }
2459}
2460
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002461void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002462 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002463 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2464 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2465}
2466
2467void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2468 const CancelationOptions& options,
2469 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2470 for (const auto& it : monitorsByDisplay) {
2471 const std::vector<Monitor>& monitors = it.second;
2472 for (const Monitor& monitor : monitors) {
2473 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002474 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002475 }
2476}
2477
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2479 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002480 sp<Connection> connection = getConnectionLocked(channel);
2481 if (connection == nullptr) {
2482 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002484
2485 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486}
2487
2488void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2489 const sp<Connection>& connection, const CancelationOptions& options) {
2490 if (connection->status == Connection::STATUS_BROKEN) {
2491 return;
2492 }
2493
2494 nsecs_t currentTime = now();
2495
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002496 std::vector<EventEntry*> cancelationEvents;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002497 connection->inputState.synthesizeCancelationEvents(currentTime, cancelationEvents, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002499 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002501 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002502 "with reality: %s, mode=%d.",
2503 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2504 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505#endif
2506 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002507 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508 switch (cancelationEventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002509 case EventEntry::TYPE_KEY:
2510 logOutboundKeyDetails("cancel - ",
2511 static_cast<KeyEntry*>(cancelationEventEntry));
2512 break;
2513 case EventEntry::TYPE_MOTION:
2514 logOutboundMotionDetails("cancel - ",
2515 static_cast<MotionEntry*>(cancelationEventEntry));
2516 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517 }
2518
2519 InputTarget target;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002520 sp<InputWindowHandle> windowHandle =
2521 getWindowHandleLocked(connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002522 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2524 target.xOffset = -windowInfo->frameLeft;
2525 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002526 target.globalScaleFactor = windowInfo->globalScaleFactor;
2527 target.windowXScale = windowInfo->windowXScale;
2528 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529 } else {
2530 target.xOffset = 0;
2531 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002532 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533 }
2534 target.inputChannel = connection->inputChannel;
2535 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2536
chaviw8c9cf542019-03-25 13:02:48 -07002537 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002538 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539
2540 cancelationEventEntry->release();
2541 }
2542
2543 startDispatchCycleLocked(currentTime, connection);
2544 }
2545}
2546
Garfield Tane84e6f92019-08-29 17:28:41 -07002547MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry,
2548 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 ALOG_ASSERT(pointerIds.value != 0);
2550
2551 uint32_t splitPointerIndexMap[MAX_POINTERS];
2552 PointerProperties splitPointerProperties[MAX_POINTERS];
2553 PointerCoords splitPointerCoords[MAX_POINTERS];
2554
2555 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2556 uint32_t splitPointerCount = 0;
2557
2558 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002559 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002560 const PointerProperties& pointerProperties =
2561 originalMotionEntry->pointerProperties[originalPointerIndex];
2562 uint32_t pointerId = uint32_t(pointerProperties.id);
2563 if (pointerIds.hasBit(pointerId)) {
2564 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2565 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2566 splitPointerCoords[splitPointerCount].copyFrom(
2567 originalMotionEntry->pointerCoords[originalPointerIndex]);
2568 splitPointerCount += 1;
2569 }
2570 }
2571
2572 if (splitPointerCount != pointerIds.count()) {
2573 // This is bad. We are missing some of the pointers that we expected to deliver.
2574 // Most likely this indicates that we received an ACTION_MOVE events that has
2575 // different pointer ids than we expected based on the previous ACTION_DOWN
2576 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2577 // in this way.
2578 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002579 "we expected there to be %d pointers. This probably means we received "
2580 "a broken sequence of pointer ids from the input device.",
2581 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002582 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 }
2584
2585 int32_t action = originalMotionEntry->action;
2586 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002587 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2588 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2590 const PointerProperties& pointerProperties =
2591 originalMotionEntry->pointerProperties[originalPointerIndex];
2592 uint32_t pointerId = uint32_t(pointerProperties.id);
2593 if (pointerIds.hasBit(pointerId)) {
2594 if (pointerIds.count() == 1) {
2595 // The first/last pointer went down/up.
2596 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002597 ? AMOTION_EVENT_ACTION_DOWN
2598 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 } else {
2600 // A secondary pointer went down/up.
2601 uint32_t splitPointerIndex = 0;
2602 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2603 splitPointerIndex += 1;
2604 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002605 action = maskedAction |
2606 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 }
2608 } else {
2609 // An unrelated pointer changed.
2610 action = AMOTION_EVENT_ACTION_MOVE;
2611 }
2612 }
2613
Garfield Tan00f511d2019-06-12 16:55:40 -07002614 MotionEntry* splitMotionEntry =
2615 new MotionEntry(originalMotionEntry->sequenceNum, originalMotionEntry->eventTime,
2616 originalMotionEntry->deviceId, originalMotionEntry->source,
2617 originalMotionEntry->displayId, originalMotionEntry->policyFlags,
2618 action, originalMotionEntry->actionButton, originalMotionEntry->flags,
2619 originalMotionEntry->metaState, originalMotionEntry->buttonState,
2620 originalMotionEntry->classification, originalMotionEntry->edgeFlags,
2621 originalMotionEntry->xPrecision, originalMotionEntry->yPrecision,
2622 originalMotionEntry->xCursorPosition,
2623 originalMotionEntry->yCursorPosition, originalMotionEntry->downTime,
2624 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625
2626 if (originalMotionEntry->injectionState) {
2627 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2628 splitMotionEntry->injectionState->refCount += 1;
2629 }
2630
2631 return splitMotionEntry;
2632}
2633
2634void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2635#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002636 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637#endif
2638
2639 bool needWake;
2640 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002641 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642
Prabir Pradhan42611e02018-11-27 14:04:02 -08002643 ConfigurationChangedEntry* newEntry =
2644 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645 needWake = enqueueInboundEventLocked(newEntry);
2646 } // release lock
2647
2648 if (needWake) {
2649 mLooper->wake();
2650 }
2651}
2652
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002653/**
2654 * If one of the meta shortcuts is detected, process them here:
2655 * Meta + Backspace -> generate BACK
2656 * Meta + Enter -> generate HOME
2657 * This will potentially overwrite keyCode and metaState.
2658 */
2659void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002660 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002661 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2662 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2663 if (keyCode == AKEYCODE_DEL) {
2664 newKeyCode = AKEYCODE_BACK;
2665 } else if (keyCode == AKEYCODE_ENTER) {
2666 newKeyCode = AKEYCODE_HOME;
2667 }
2668 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002669 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002670 struct KeyReplacement replacement = {keyCode, deviceId};
2671 mReplacedKeys.add(replacement, newKeyCode);
2672 keyCode = newKeyCode;
2673 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2674 }
2675 } else if (action == AKEY_EVENT_ACTION_UP) {
2676 // In order to maintain a consistent stream of up and down events, check to see if the key
2677 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2678 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002679 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002680 struct KeyReplacement replacement = {keyCode, deviceId};
2681 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2682 if (index >= 0) {
2683 keyCode = mReplacedKeys.valueAt(index);
2684 mReplacedKeys.removeItemsAt(index);
2685 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2686 }
2687 }
2688}
2689
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2691#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002692 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2693 "policyFlags=0x%x, action=0x%x, "
2694 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2695 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2696 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2697 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698#endif
2699 if (!validateKeyEvent(args->action)) {
2700 return;
2701 }
2702
2703 uint32_t policyFlags = args->policyFlags;
2704 int32_t flags = args->flags;
2705 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002706 // InputDispatcher tracks and generates key repeats on behalf of
2707 // whatever notifies it, so repeatCount should always be set to 0
2708 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2710 policyFlags |= POLICY_FLAG_VIRTUAL;
2711 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713 if (policyFlags & POLICY_FLAG_FUNCTION) {
2714 metaState |= AMETA_FUNCTION_ON;
2715 }
2716
2717 policyFlags |= POLICY_FLAG_TRUSTED;
2718
Michael Wright78f24442014-08-06 15:55:28 -07002719 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002720 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002721
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722 KeyEvent event;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002723 event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2724 args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725
Michael Wright2b3c3302018-03-02 17:19:13 +00002726 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002728 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2729 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002730 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733 bool needWake;
2734 { // acquire lock
2735 mLock.lock();
2736
2737 if (shouldSendKeyToInputFilterLocked(args)) {
2738 mLock.unlock();
2739
2740 policyFlags |= POLICY_FLAG_FILTERED;
2741 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2742 return; // event was consumed by the filter
2743 }
2744
2745 mLock.lock();
2746 }
2747
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002748 KeyEntry* newEntry =
2749 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2750 args->displayId, policyFlags, args->action, flags, keyCode,
2751 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752
2753 needWake = enqueueInboundEventLocked(newEntry);
2754 mLock.unlock();
2755 } // release lock
2756
2757 if (needWake) {
2758 mLooper->wake();
2759 }
2760}
2761
2762bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2763 return mInputFilterEnabled;
2764}
2765
2766void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2767#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002768 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan00f511d2019-06-12 16:55:40 -07002769 ", policyFlags=0x%x, "
2770 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
2771 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07002772 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan00f511d2019-06-12 16:55:40 -07002773 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2774 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Jaewan Kim372fbe42019-10-02 10:58:46 +09002775 args->edgeFlags, args->xPrecision, args->yPrecision, args->xCursorPosition,
Garfield Tan00f511d2019-06-12 16:55:40 -07002776 args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 for (uint32_t i = 0; i < args->pointerCount; i++) {
2778 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002779 "x=%f, y=%f, pressure=%f, size=%f, "
2780 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2781 "orientation=%f",
2782 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2783 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2784 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2785 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2786 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2787 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2788 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2789 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2790 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2791 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792 }
2793#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002794 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2795 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 return;
2797 }
2798
2799 uint32_t policyFlags = args->policyFlags;
2800 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002801
2802 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002803 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002804 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2805 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002806 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808
2809 bool needWake;
2810 { // acquire lock
2811 mLock.lock();
2812
2813 if (shouldSendMotionToInputFilterLocked(args)) {
2814 mLock.unlock();
2815
2816 MotionEvent event;
Garfield Tan00f511d2019-06-12 16:55:40 -07002817 event.initialize(args->deviceId, args->source, args->displayId, args->action,
2818 args->actionButton, args->flags, args->edgeFlags, args->metaState,
2819 args->buttonState, args->classification, 0, 0, args->xPrecision,
2820 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2821 args->downTime, args->eventTime, args->pointerCount,
2822 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823
2824 policyFlags |= POLICY_FLAG_FILTERED;
2825 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2826 return; // event was consumed by the filter
2827 }
2828
2829 mLock.lock();
2830 }
2831
2832 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07002833 MotionEntry* newEntry =
2834 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2835 args->displayId, policyFlags, args->action, args->actionButton,
2836 args->flags, args->metaState, args->buttonState,
2837 args->classification, args->edgeFlags, args->xPrecision,
2838 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2839 args->downTime, args->pointerCount, args->pointerProperties,
2840 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002841
2842 needWake = enqueueInboundEventLocked(newEntry);
2843 mLock.unlock();
2844 } // release lock
2845
2846 if (needWake) {
2847 mLooper->wake();
2848 }
2849}
2850
2851bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002852 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853}
2854
2855void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2856#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002857 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002858 "switchMask=0x%08x",
2859 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860#endif
2861
2862 uint32_t policyFlags = args->policyFlags;
2863 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002864 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865}
2866
2867void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2868#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002869 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
2870 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871#endif
2872
2873 bool needWake;
2874 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002875 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876
Prabir Pradhan42611e02018-11-27 14:04:02 -08002877 DeviceResetEntry* newEntry =
2878 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002879 needWake = enqueueInboundEventLocked(newEntry);
2880 } // release lock
2881
2882 if (needWake) {
2883 mLooper->wake();
2884 }
2885}
2886
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002887int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
2888 int32_t injectorUid, int32_t syncMode,
2889 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890#if DEBUG_INBOUND_EVENT_DETAILS
2891 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002892 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2893 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894#endif
2895
2896 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2897
2898 policyFlags |= POLICY_FLAG_INJECTED;
2899 if (hasInjectionPermission(injectorPid, injectorUid)) {
2900 policyFlags |= POLICY_FLAG_TRUSTED;
2901 }
2902
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07002903 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002905 case AINPUT_EVENT_TYPE_KEY: {
2906 KeyEvent keyEvent;
2907 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2908 int32_t action = keyEvent.getAction();
2909 if (!validateKeyEvent(action)) {
2910 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 int32_t flags = keyEvent.getFlags();
2914 int32_t keyCode = keyEvent.getKeyCode();
2915 int32_t metaState = keyEvent.getMetaState();
2916 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2917 /*byref*/ keyCode, /*byref*/ metaState);
2918 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
2919 keyEvent.getDisplayId(), action, flags, keyCode,
2920 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
2921 keyEvent.getDownTime(), keyEvent.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002923 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2924 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00002925 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002926
2927 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2928 android::base::Timer t;
2929 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
2930 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2931 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2932 std::to_string(t.duration().count()).c_str());
2933 }
2934 }
2935
2936 mLock.lock();
2937 KeyEntry* injectedEntry =
2938 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
2939 keyEvent.getDeviceId(), keyEvent.getSource(),
2940 keyEvent.getDisplayId(), policyFlags, action, flags,
2941 keyEvent.getKeyCode(), keyEvent.getScanCode(),
2942 keyEvent.getMetaState(), keyEvent.getRepeatCount(),
2943 keyEvent.getDownTime());
2944 injectedEntries.push(injectedEntry);
2945 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946 }
2947
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 case AINPUT_EVENT_TYPE_MOTION: {
2949 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2950 int32_t action = motionEvent->getAction();
2951 size_t pointerCount = motionEvent->getPointerCount();
2952 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2953 int32_t actionButton = motionEvent->getActionButton();
2954 int32_t displayId = motionEvent->getDisplayId();
2955 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
2956 return INPUT_EVENT_INJECTION_FAILED;
2957 }
2958
2959 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2960 nsecs_t eventTime = motionEvent->getEventTime();
2961 android::base::Timer t;
2962 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
2963 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2964 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2965 std::to_string(t.duration().count()).c_str());
2966 }
2967 }
2968
2969 mLock.lock();
2970 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2971 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2972 MotionEntry* injectedEntry =
Garfield Tan00f511d2019-06-12 16:55:40 -07002973 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2974 motionEvent->getDeviceId(), motionEvent->getSource(),
2975 motionEvent->getDisplayId(), policyFlags, action, actionButton,
2976 motionEvent->getFlags(), motionEvent->getMetaState(),
2977 motionEvent->getButtonState(), motionEvent->getClassification(),
2978 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
2979 motionEvent->getYPrecision(),
2980 motionEvent->getRawXCursorPosition(),
2981 motionEvent->getRawYCursorPosition(),
2982 motionEvent->getDownTime(), uint32_t(pointerCount),
2983 pointerProperties, samplePointerCoords,
2984 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002985 injectedEntries.push(injectedEntry);
2986 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2987 sampleEventTimes += 1;
2988 samplePointerCoords += pointerCount;
2989 MotionEntry* nextInjectedEntry =
2990 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2991 motionEvent->getDeviceId(), motionEvent->getSource(),
2992 motionEvent->getDisplayId(), policyFlags, action,
2993 actionButton, motionEvent->getFlags(),
2994 motionEvent->getMetaState(), motionEvent->getButtonState(),
2995 motionEvent->getClassification(),
2996 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
2997 motionEvent->getYPrecision(),
2998 motionEvent->getRawXCursorPosition(),
2999 motionEvent->getRawYCursorPosition(),
3000 motionEvent->getDownTime(), uint32_t(pointerCount),
3001 pointerProperties, samplePointerCoords,
3002 motionEvent->getXOffset(), motionEvent->getYOffset());
3003 injectedEntries.push(nextInjectedEntry);
3004 }
3005 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003008 default:
3009 ALOGW("Cannot inject event of type %d", event->getType());
3010 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011 }
3012
3013 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3014 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3015 injectionState->injectionIsAsync = true;
3016 }
3017
3018 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003019 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003020
3021 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003022 while (!injectedEntries.empty()) {
3023 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3024 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025 }
3026
3027 mLock.unlock();
3028
3029 if (needWake) {
3030 mLooper->wake();
3031 }
3032
3033 int32_t injectionResult;
3034 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003035 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036
3037 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3038 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3039 } else {
3040 for (;;) {
3041 injectionResult = injectionState->injectionResult;
3042 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3043 break;
3044 }
3045
3046 nsecs_t remainingTimeout = endTime - now();
3047 if (remainingTimeout <= 0) {
3048#if DEBUG_INJECTION
3049 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003050 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051#endif
3052 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3053 break;
3054 }
3055
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003056 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057 }
3058
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003059 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3060 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003061 while (injectionState->pendingForegroundDispatches != 0) {
3062#if DEBUG_INJECTION
3063 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003064 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003065#endif
3066 nsecs_t remainingTimeout = endTime - now();
3067 if (remainingTimeout <= 0) {
3068#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003069 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3070 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071#endif
3072 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3073 break;
3074 }
3075
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003076 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077 }
3078 }
3079 }
3080
3081 injectionState->release();
3082 } // release lock
3083
3084#if DEBUG_INJECTION
3085 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 "injectorPid=%d, injectorUid=%d",
3087 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088#endif
3089
3090 return injectionResult;
3091}
3092
3093bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003094 return injectorUid == 0 ||
3095 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096}
3097
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003098void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099 InjectionState* injectionState = entry->injectionState;
3100 if (injectionState) {
3101#if DEBUG_INJECTION
3102 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003103 "injectorPid=%d, injectorUid=%d",
3104 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105#endif
3106
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003107 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108 // Log the outcome since the injector did not wait for the injection result.
3109 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003110 case INPUT_EVENT_INJECTION_SUCCEEDED:
3111 ALOGV("Asynchronous input event injection succeeded.");
3112 break;
3113 case INPUT_EVENT_INJECTION_FAILED:
3114 ALOGW("Asynchronous input event injection failed.");
3115 break;
3116 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3117 ALOGW("Asynchronous input event injection permission denied.");
3118 break;
3119 case INPUT_EVENT_INJECTION_TIMED_OUT:
3120 ALOGW("Asynchronous input event injection timed out.");
3121 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122 }
3123 }
3124
3125 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003126 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127 }
3128}
3129
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003130void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131 InjectionState* injectionState = entry->injectionState;
3132 if (injectionState) {
3133 injectionState->pendingForegroundDispatches += 1;
3134 }
3135}
3136
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003137void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 InjectionState* injectionState = entry->injectionState;
3139 if (injectionState) {
3140 injectionState->pendingForegroundDispatches -= 1;
3141
3142 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003143 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003144 }
3145 }
3146}
3147
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003148std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3149 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003150 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003151}
3152
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003154 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003155 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003156 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3157 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003158 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003159 return windowHandle;
3160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 }
3162 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003163 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164}
3165
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003166bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003167 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003168 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3169 for (const sp<InputWindowHandle>& handle : windowHandles) {
3170 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003171 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003172 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003173 ", but it should belong to display %" PRId32,
3174 windowHandle->getName().c_str(), it.first,
3175 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003176 }
3177 return true;
3178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 }
3180 }
3181 return false;
3182}
3183
Robert Carr5c8a0262018-10-03 16:30:44 -07003184sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3185 size_t count = mInputChannelsByToken.count(token);
3186 if (count == 0) {
3187 return nullptr;
3188 }
3189 return mInputChannelsByToken.at(token);
3190}
3191
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003192void InputDispatcher::updateWindowHandlesForDisplayLocked(
3193 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3194 if (inputWindowHandles.empty()) {
3195 // Remove all handles on a display if there are no windows left.
3196 mWindowHandlesByDisplay.erase(displayId);
3197 return;
3198 }
3199
3200 // Since we compare the pointer of input window handles across window updates, we need
3201 // to make sure the handle object for the same window stays unchanged across updates.
3202 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
3203 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3204 for (const sp<InputWindowHandle>& handle : oldHandles) {
3205 oldHandlesByTokens[handle->getToken()] = handle;
3206 }
3207
3208 std::vector<sp<InputWindowHandle>> newHandles;
3209 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3210 if (!handle->updateInfo()) {
3211 // handle no longer valid
3212 continue;
3213 }
3214
3215 const InputWindowInfo* info = handle->getInfo();
3216 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3217 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3218 const bool noInputChannel =
3219 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3220 const bool canReceiveInput =
3221 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3222 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3223 if (canReceiveInput && !noInputChannel) {
3224 ALOGE("Window handle %s has no registered input channel",
3225 handle->getName().c_str());
3226 }
3227 continue;
3228 }
3229
3230 if (info->displayId != displayId) {
3231 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3232 handle->getName().c_str(), displayId, info->displayId);
3233 continue;
3234 }
3235
3236 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3237 const sp<InputWindowHandle> oldHandle = oldHandlesByTokens.at(handle->getToken());
3238 oldHandle->updateFrom(handle);
3239 newHandles.push_back(oldHandle);
3240 } else {
3241 newHandles.push_back(handle);
3242 }
3243 }
3244
3245 // Insert or replace
3246 mWindowHandlesByDisplay[displayId] = newHandles;
3247}
3248
Arthur Hungb92218b2018-08-14 12:00:21 +08003249/**
3250 * Called from InputManagerService, update window handle list by displayId that can receive input.
3251 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3252 * If set an empty list, remove all handles from the specific display.
3253 * For focused handle, check if need to change and send a cancel event to previous one.
3254 * For removed handle, check if need to send a cancel event if already in touch.
3255 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003256void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003257 int32_t displayId,
3258 const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003259 if (DEBUG_FOCUS) {
3260 std::string windowList;
3261 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3262 windowList += iwh->getName() + " ";
3263 }
3264 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003267 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268
Arthur Hungb92218b2018-08-14 12:00:21 +08003269 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003270 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3271 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003273 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
3274
Tiger Huang721e26f2018-07-24 22:26:19 +08003275 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276 bool foundHoveredWindow = false;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003277 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3278 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3279 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3280 windowHandle->getInfo()->visible) {
3281 newFocusedWindowHandle = windowHandle;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003282 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003283 if (windowHandle == mLastHoverWindowHandle) {
3284 foundHoveredWindow = true;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003285 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286 }
3287
3288 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003289 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 }
3291
Tiger Huang721e26f2018-07-24 22:26:19 +08003292 sp<InputWindowHandle> oldFocusedWindowHandle =
3293 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3294
3295 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3296 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003297 if (DEBUG_FOCUS) {
3298 ALOGD("Focus left window: %s in display %" PRId32,
3299 oldFocusedWindowHandle->getName().c_str(), displayId);
3300 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 sp<InputChannel> focusedInputChannel =
3302 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003303 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003305 "focus left window");
3306 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003308 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003310 if (newFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003311 if (DEBUG_FOCUS) {
3312 ALOGD("Focus entered window: %s in display %" PRId32,
3313 newFocusedWindowHandle->getName().c_str(), displayId);
3314 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003315 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316 }
Robert Carrf759f162018-11-13 12:57:11 -08003317
3318 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003319 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321 }
3322
Arthur Hungb92218b2018-08-14 12:00:21 +08003323 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3324 if (stateIndex >= 0) {
3325 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003326 for (size_t i = 0; i < state.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003327 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003328 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003329 if (DEBUG_FOCUS) {
3330 ALOGD("Touched window was removed: %s in display %" PRId32,
3331 touchedWindow.windowHandle->getName().c_str(), displayId);
3332 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003333 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003334 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003335 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003336 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 "touched window was removed");
3338 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3339 options);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003340 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003341 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003342 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003343 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345 }
3346 }
3347
3348 // Release information for windows that are no longer present.
3349 // This ensures that unused input channels are released promptly.
3350 // Otherwise, they might stick around until the window handle is destroyed
3351 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003352 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003353 if (!hasWindowHandleLocked(oldWindowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003354 if (DEBUG_FOCUS) {
3355 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
3356 }
Arthur Hung3b413f22018-10-26 18:05:34 +08003357 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358 }
3359 }
3360 } // release lock
3361
3362 // Wake up poll loop since it may need to make new input dispatching choices.
3363 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003364
3365 if (setInputWindowsListener) {
3366 setInputWindowsListener->onSetInputWindowsFinished();
3367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368}
3369
3370void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003371 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003372 if (DEBUG_FOCUS) {
3373 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3374 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003377 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378
Tiger Huang721e26f2018-07-24 22:26:19 +08003379 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3380 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003381 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003382 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3383 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003386 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003388 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003390 oldFocusedApplicationHandle.clear();
3391 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393 } // release lock
3394
3395 // Wake up poll loop since it may need to make new input dispatching choices.
3396 mLooper->wake();
3397}
3398
Tiger Huang721e26f2018-07-24 22:26:19 +08003399/**
3400 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3401 * the display not specified.
3402 *
3403 * We track any unreleased events for each window. If a window loses the ability to receive the
3404 * released event, we will send a cancel event to it. So when the focused display is changed, we
3405 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3406 * display. The display-specified events won't be affected.
3407 */
3408void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003409 if (DEBUG_FOCUS) {
3410 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3411 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003412 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003413 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003414
3415 if (mFocusedDisplayId != displayId) {
3416 sp<InputWindowHandle> oldFocusedWindowHandle =
3417 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3418 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003419 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003420 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003421 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003422 CancelationOptions
3423 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3424 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003425 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003426 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3427 }
3428 }
3429 mFocusedDisplayId = displayId;
3430
3431 // Sanity check
3432 sp<InputWindowHandle> newFocusedWindowHandle =
3433 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003434 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003435
Tiger Huang721e26f2018-07-24 22:26:19 +08003436 if (newFocusedWindowHandle == nullptr) {
3437 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3438 if (!mFocusedWindowHandlesByDisplay.empty()) {
3439 ALOGE("But another display has a focused window:");
3440 for (auto& it : mFocusedWindowHandlesByDisplay) {
3441 const int32_t displayId = it.first;
3442 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003443 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3444 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003445 }
3446 }
3447 }
3448 }
3449
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003450 if (DEBUG_FOCUS) {
3451 logDispatchStateLocked();
3452 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003453 } // release lock
3454
3455 // Wake up poll loop since it may need to make new input dispatching choices.
3456 mLooper->wake();
3457}
3458
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003460 if (DEBUG_FOCUS) {
3461 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463
3464 bool changed;
3465 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003466 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467
3468 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3469 if (mDispatchFrozen && !frozen) {
3470 resetANRTimeoutsLocked();
3471 }
3472
3473 if (mDispatchEnabled && !enabled) {
3474 resetAndDropEverythingLocked("dispatcher is being disabled");
3475 }
3476
3477 mDispatchEnabled = enabled;
3478 mDispatchFrozen = frozen;
3479 changed = true;
3480 } else {
3481 changed = false;
3482 }
3483
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003484 if (DEBUG_FOCUS) {
3485 logDispatchStateLocked();
3486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487 } // release lock
3488
3489 if (changed) {
3490 // Wake up poll loop since it may need to make new input dispatching choices.
3491 mLooper->wake();
3492 }
3493}
3494
3495void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003496 if (DEBUG_FOCUS) {
3497 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499
3500 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003501 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502
3503 if (mInputFilterEnabled == enabled) {
3504 return;
3505 }
3506
3507 mInputFilterEnabled = enabled;
3508 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3509 } // release lock
3510
3511 // Wake up poll loop since there might be work to do to drop everything.
3512 mLooper->wake();
3513}
3514
chaviwfbe5d9c2018-12-26 12:23:37 -08003515bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3516 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003517 if (DEBUG_FOCUS) {
3518 ALOGD("Trivial transfer to same window.");
3519 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003520 return true;
3521 }
3522
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003524 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525
chaviwfbe5d9c2018-12-26 12:23:37 -08003526 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3527 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003528 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003529 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530 return false;
3531 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003532 if (DEBUG_FOCUS) {
3533 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3534 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3535 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003537 if (DEBUG_FOCUS) {
3538 ALOGD("Cannot transfer focus because windows are on different displays.");
3539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 return false;
3541 }
3542
3543 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003544 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3545 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3546 for (size_t i = 0; i < state.windows.size(); i++) {
3547 const TouchedWindow& touchedWindow = state.windows[i];
3548 if (touchedWindow.windowHandle == fromWindowHandle) {
3549 int32_t oldTargetFlags = touchedWindow.targetFlags;
3550 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003552 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003554 int32_t newTargetFlags = oldTargetFlags &
3555 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3556 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003557 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558
Jeff Brownf086ddb2014-02-11 14:28:48 -08003559 found = true;
3560 goto Found;
3561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562 }
3563 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003564 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003566 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003567 if (DEBUG_FOCUS) {
3568 ALOGD("Focus transfer failed because from window did not have focus.");
3569 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570 return false;
3571 }
3572
chaviwfbe5d9c2018-12-26 12:23:37 -08003573 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3574 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003575 sp<Connection> fromConnection = getConnectionLocked(fromChannel);
3576 sp<Connection> toConnection = getConnectionLocked(toChannel);
3577 if (fromConnection != nullptr && toConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003579 CancelationOptions
3580 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3581 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3583 }
3584
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003585 if (DEBUG_FOCUS) {
3586 logDispatchStateLocked();
3587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 } // release lock
3589
3590 // Wake up poll loop since it may need to make new input dispatching choices.
3591 mLooper->wake();
3592 return true;
3593}
3594
3595void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003596 if (DEBUG_FOCUS) {
3597 ALOGD("Resetting and dropping all events (%s).", reason);
3598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599
3600 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3601 synthesizeCancelationEventsForAllConnectionsLocked(options);
3602
3603 resetKeyRepeatLocked();
3604 releasePendingEventLocked();
3605 drainInboundQueueLocked();
3606 resetANRTimeoutsLocked();
3607
Jeff Brownf086ddb2014-02-11 14:28:48 -08003608 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003610 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611}
3612
3613void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003614 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 dumpDispatchStateLocked(dump);
3616
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003617 std::istringstream stream(dump);
3618 std::string line;
3619
3620 while (std::getline(stream, line, '\n')) {
3621 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 }
3623}
3624
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003625void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003626 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3627 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3628 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003629 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630
Tiger Huang721e26f2018-07-24 22:26:19 +08003631 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3632 dump += StringPrintf(INDENT "FocusedApplications:\n");
3633 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3634 const int32_t displayId = it.first;
3635 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003636 dump += StringPrintf(INDENT2 "displayId=%" PRId32
3637 ", name='%s', dispatchingTimeout=%0.3fms\n",
3638 displayId, applicationHandle->getName().c_str(),
3639 applicationHandle->getDispatchingTimeout(
3640 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3641 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08003642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003644 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003646
3647 if (!mFocusedWindowHandlesByDisplay.empty()) {
3648 dump += StringPrintf(INDENT "FocusedWindows:\n");
3649 for (auto& it : mFocusedWindowHandlesByDisplay) {
3650 const int32_t displayId = it.first;
3651 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003652 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3653 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003654 }
3655 } else {
3656 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658
Jeff Brownf086ddb2014-02-11 14:28:48 -08003659 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003660 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003661 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3662 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003663 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003664 state.displayId, toString(state.down), toString(state.split),
3665 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003666 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003667 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003668 for (size_t i = 0; i < state.windows.size(); i++) {
3669 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003670 dump += StringPrintf(INDENT4
3671 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3672 i, touchedWindow.windowHandle->getName().c_str(),
3673 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003674 }
3675 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003676 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003677 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003678 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003679 dump += INDENT3 "Portal windows:\n";
3680 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003681 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003682 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3683 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003684 }
3685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686 }
3687 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003688 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 }
3690
Arthur Hungb92218b2018-08-14 12:00:21 +08003691 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003692 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003693 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003694 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003695 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003696 dump += INDENT2 "Windows:\n";
3697 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003698 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003699 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700
Arthur Hungb92218b2018-08-14 12:00:21 +08003701 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003702 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
3703 "hasWallpaper=%s, "
3704 "visible=%s, canReceiveKeys=%s, flags=0x%08x, "
3705 "type=0x%08x, layer=%d, "
3706 "frame=[%d,%d][%d,%d], globalScale=%f, "
3707 "windowScale=(%f,%f), "
3708 "touchableRegion=",
3709 i, windowInfo->name.c_str(), windowInfo->displayId,
3710 windowInfo->portalToDisplayId,
3711 toString(windowInfo->paused),
3712 toString(windowInfo->hasFocus),
3713 toString(windowInfo->hasWallpaper),
3714 toString(windowInfo->visible),
3715 toString(windowInfo->canReceiveKeys),
3716 windowInfo->layoutParamsFlags,
3717 windowInfo->layoutParamsType, windowInfo->layer,
3718 windowInfo->frameLeft, windowInfo->frameTop,
3719 windowInfo->frameRight, windowInfo->frameBottom,
3720 windowInfo->globalScaleFactor, windowInfo->windowXScale,
3721 windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003722 dumpRegion(dump, windowInfo->touchableRegion);
3723 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3724 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003725 windowInfo->ownerPid, windowInfo->ownerUid,
3726 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08003727 }
3728 } else {
3729 dump += INDENT2 "Windows: <none>\n";
3730 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 }
3732 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003733 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 }
3735
Michael Wright3dd60e22019-03-27 22:06:44 +00003736 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003737 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003738 const std::vector<Monitor>& monitors = it.second;
3739 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3740 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003741 }
3742 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003743 const std::vector<Monitor>& monitors = it.second;
3744 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3745 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003746 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003748 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749 }
3750
3751 nsecs_t currentTime = now();
3752
3753 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003754 if (!mRecentQueue.empty()) {
3755 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
3756 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003757 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003759 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 }
3761 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003762 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763 }
3764
3765 // Dump event currently being dispatched.
3766 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003767 dump += INDENT "PendingEvent:\n";
3768 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003770 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003771 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003773 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 }
3775
3776 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003777 if (!mInboundQueue.empty()) {
3778 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
3779 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003780 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003782 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 }
3784 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003785 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 }
3787
Michael Wright78f24442014-08-06 15:55:28 -07003788 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003789 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003790 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3791 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3792 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003793 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3794 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07003795 }
3796 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003797 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003798 }
3799
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003800 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003801 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003802 for (const auto& pair : mConnectionsByFd) {
3803 const sp<Connection>& connection = pair.second;
3804 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
3805 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3806 pair.first, connection->getInputChannelName().c_str(),
3807 connection->getWindowName().c_str(), connection->getStatusLabel(),
3808 toString(connection->monitor),
3809 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003811 if (!connection->outboundQueue.empty()) {
3812 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
3813 connection->outboundQueue.size());
3814 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 dump.append(INDENT4);
3816 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003817 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003818 entry->targetFlags, entry->resolvedAction,
3819 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 }
3821 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003822 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 }
3824
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003825 if (!connection->waitQueue.empty()) {
3826 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
3827 connection->waitQueue.size());
3828 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003829 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003831 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003832 "age=%0.1fms, wait=%0.1fms\n",
3833 entry->targetFlags, entry->resolvedAction,
3834 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3835 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836 }
3837 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003838 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 }
3840 }
3841 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003842 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843 }
3844
3845 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003846 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003847 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003849 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 }
3851
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003852 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003853 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003854 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003855 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856}
3857
Michael Wright3dd60e22019-03-27 22:06:44 +00003858void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3859 const size_t numMonitors = monitors.size();
3860 for (size_t i = 0; i < numMonitors; i++) {
3861 const Monitor& monitor = monitors[i];
3862 const sp<InputChannel>& channel = monitor.inputChannel;
3863 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3864 dump += "\n";
3865 }
3866}
3867
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003868status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003870 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871#endif
3872
3873 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003874 std::scoped_lock _l(mLock);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003875 sp<Connection> existingConnection = getConnectionLocked(inputChannel);
3876 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003878 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 return BAD_VALUE;
3880 }
3881
Michael Wright3dd60e22019-03-27 22:06:44 +00003882 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883
3884 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003885 mConnectionsByFd[fd] = connection;
Robert Carr5c8a0262018-10-03 16:30:44 -07003886 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3889 } // release lock
3890
3891 // Wake the looper because some connections have changed.
3892 mLooper->wake();
3893 return OK;
3894}
3895
Michael Wright3dd60e22019-03-27 22:06:44 +00003896status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003897 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003898 { // acquire lock
3899 std::scoped_lock _l(mLock);
3900
3901 if (displayId < 0) {
3902 ALOGW("Attempted to register input monitor without a specified display.");
3903 return BAD_VALUE;
3904 }
3905
3906 if (inputChannel->getToken() == nullptr) {
3907 ALOGW("Attempted to register input monitor without an identifying token.");
3908 return BAD_VALUE;
3909 }
3910
3911 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3912
3913 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003914 mConnectionsByFd[fd] = connection;
Michael Wright3dd60e22019-03-27 22:06:44 +00003915 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
3916
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003917 auto& monitorsByDisplay =
3918 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00003919 monitorsByDisplay[displayId].emplace_back(inputChannel);
3920
3921 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00003922 }
3923 // Wake the looper because some connections have changed.
3924 mLooper->wake();
3925 return OK;
3926}
3927
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3929#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003930 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931#endif
3932
3933 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003934 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935
3936 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3937 if (status) {
3938 return status;
3939 }
3940 } // release lock
3941
3942 // Wake the poll loop because removing the connection may have changed the current
3943 // synchronization state.
3944 mLooper->wake();
3945 return OK;
3946}
3947
3948status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003949 bool notify) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003950 sp<Connection> connection = getConnectionLocked(inputChannel);
3951 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003953 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 return BAD_VALUE;
3955 }
3956
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003957 const bool removed = removeByValue(mConnectionsByFd, connection);
3958 ALOG_ASSERT(removed);
Robert Carr5c8a0262018-10-03 16:30:44 -07003959 mInputChannelsByToken.erase(inputChannel->getToken());
3960
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 if (connection->monitor) {
3962 removeMonitorChannelLocked(inputChannel);
3963 }
3964
3965 mLooper->removeFd(inputChannel->getFd());
3966
3967 nsecs_t currentTime = now();
3968 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3969
3970 connection->status = Connection::STATUS_ZOMBIE;
3971 return OK;
3972}
3973
3974void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003975 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
3976 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
3977}
3978
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003979void InputDispatcher::removeMonitorChannelLocked(
3980 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00003981 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003982 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003983 std::vector<Monitor>& monitors = it->second;
3984 const size_t numMonitors = monitors.size();
3985 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003986 if (monitors[i].inputChannel == inputChannel) {
3987 monitors.erase(monitors.begin() + i);
3988 break;
3989 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003990 }
Michael Wright3dd60e22019-03-27 22:06:44 +00003991 if (monitors.empty()) {
3992 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003993 } else {
3994 ++it;
3995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 }
3997}
3998
Michael Wright3dd60e22019-03-27 22:06:44 +00003999status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4000 { // acquire lock
4001 std::scoped_lock _l(mLock);
4002 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4003
4004 if (!foundDisplayId) {
4005 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4006 return BAD_VALUE;
4007 }
4008 int32_t displayId = foundDisplayId.value();
4009
4010 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4011 if (stateIndex < 0) {
4012 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4013 return BAD_VALUE;
4014 }
4015
4016 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4017 std::optional<int32_t> foundDeviceId;
4018 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
4019 if (touchedMonitor.monitor.inputChannel->getToken() == token) {
4020 foundDeviceId = state.deviceId;
4021 }
4022 }
4023 if (!foundDeviceId || !state.down) {
4024 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004025 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004026 return BAD_VALUE;
4027 }
4028 int32_t deviceId = foundDeviceId.value();
4029
4030 // Send cancel events to all the input channels we're stealing from.
4031 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004032 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004033 options.deviceId = deviceId;
4034 options.displayId = displayId;
4035 for (const TouchedWindow& window : state.windows) {
4036 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
4037 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4038 }
4039 // Then clear the current touch state so we stop dispatching to them as well.
4040 state.filterNonMonitors();
4041 }
4042 return OK;
4043}
4044
Michael Wright3dd60e22019-03-27 22:06:44 +00004045std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4046 const sp<IBinder>& token) {
4047 for (const auto& it : mGestureMonitorsByDisplay) {
4048 const std::vector<Monitor>& monitors = it.second;
4049 for (const Monitor& monitor : monitors) {
4050 if (monitor.inputChannel->getToken() == token) {
4051 return it.first;
4052 }
4053 }
4054 }
4055 return std::nullopt;
4056}
4057
Garfield Tane84e6f92019-08-29 17:28:41 -07004058sp<Connection> InputDispatcher::getConnectionLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07004059 if (inputChannel == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004060 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004061 }
4062
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004063 for (const auto& pair : mConnectionsByFd) {
4064 sp<Connection> connection = pair.second;
Robert Carr4e670e52018-08-15 13:26:12 -07004065 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004066 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067 }
4068 }
Robert Carr4e670e52018-08-15 13:26:12 -07004069
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004070 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071}
4072
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004073void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4074 const sp<Connection>& connection, uint32_t seq,
4075 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004076 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4077 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078 commandEntry->connection = connection;
4079 commandEntry->eventTime = currentTime;
4080 commandEntry->seq = seq;
4081 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004082 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083}
4084
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004085void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4086 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004088 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004090 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4091 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004093 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094}
4095
chaviw0c06c6e2019-01-09 13:27:07 -08004096void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004097 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004098 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4099 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004100 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4101 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004102 commandEntry->oldToken = oldToken;
4103 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004104 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004105}
4106
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004107void InputDispatcher::onANRLocked(nsecs_t currentTime,
4108 const sp<InputApplicationHandle>& applicationHandle,
4109 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4110 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4112 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4113 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004114 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4115 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4116 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117
4118 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004119 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 struct tm tm;
4121 localtime_r(&t, &tm);
4122 char timestr[64];
4123 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4124 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004125 mLastANRState += INDENT "ANR:\n";
4126 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004127 mLastANRState +=
4128 StringPrintf(INDENT2 "Window: %s\n",
4129 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004130 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4131 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4132 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 dumpDispatchStateLocked(mLastANRState);
4134
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004135 std::unique_ptr<CommandEntry> commandEntry =
4136 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004138 commandEntry->inputChannel =
4139 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004141 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142}
4143
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004144void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145 mLock.unlock();
4146
4147 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4148
4149 mLock.lock();
4150}
4151
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004152void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 sp<Connection> connection = commandEntry->connection;
4154
4155 if (connection->status != Connection::STATUS_ZOMBIE) {
4156 mLock.unlock();
4157
Robert Carr803535b2018-08-02 16:38:15 -07004158 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159
4160 mLock.lock();
4161 }
4162}
4163
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004164void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004165 sp<IBinder> oldToken = commandEntry->oldToken;
4166 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004167 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004168 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004169 mLock.lock();
4170}
4171
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004172void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 mLock.unlock();
4174
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004175 nsecs_t newTimeout =
4176 mPolicy->notifyANR(commandEntry->inputApplicationHandle,
4177 commandEntry->inputChannel ? commandEntry->inputChannel->getToken()
4178 : nullptr,
4179 commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180
4181 mLock.lock();
4182
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004183 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184}
4185
4186void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4187 CommandEntry* commandEntry) {
4188 KeyEntry* entry = commandEntry->keyEntry;
4189
4190 KeyEvent event;
4191 initializeKeyEvent(&event, entry);
4192
4193 mLock.unlock();
4194
Michael Wright2b3c3302018-03-02 17:19:13 +00004195 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 sp<IBinder> token = commandEntry->inputChannel != nullptr
4197 ? commandEntry->inputChannel->getToken()
4198 : nullptr;
4199 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004200 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4201 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204
4205 mLock.lock();
4206
4207 if (delay < 0) {
4208 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4209 } else if (!delay) {
4210 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4211 } else {
4212 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4213 entry->interceptKeyWakeupTime = now() + delay;
4214 }
4215 entry->release();
4216}
4217
chaviwfd6d3512019-03-25 13:23:49 -07004218void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4219 mLock.unlock();
4220 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4221 mLock.lock();
4222}
4223
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004226 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004228 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229
4230 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004231 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004232 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004233 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004235 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004236
4237 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4238 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4239 std::string msg =
4240 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4241 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4242 dispatchEntry->eventEntry->appendDescription(msg);
4243 ALOGI("%s", msg.c_str());
4244 }
4245
4246 bool restartEvent;
4247 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4248 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4249 restartEvent =
4250 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
4251 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4252 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4253 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4254 handled);
4255 } else {
4256 restartEvent = false;
4257 }
4258
4259 // Dequeue the event and start the next cycle.
4260 // Note that because the lock might have been released, it is possible that the
4261 // contents of the wait queue to have been drained, so we need to double-check
4262 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004263 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4264 if (dispatchEntryIt != connection->waitQueue.end()) {
4265 dispatchEntry = *dispatchEntryIt;
4266 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004267 traceWaitQueueLength(connection);
4268 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004269 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004270 traceOutboundQueueLength(connection);
4271 } else {
4272 releaseDispatchEntry(dispatchEntry);
4273 }
4274 }
4275
4276 // Start the next dispatch cycle for this connection.
4277 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278}
4279
4280bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004281 DispatchEntry* dispatchEntry,
4282 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004283 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004284 if (!handled) {
4285 // Report the key as unhandled, since the fallback was not handled.
4286 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4287 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004288 return false;
4289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004291 // Get the fallback key state.
4292 // Clear it out after dispatching the UP.
4293 int32_t originalKeyCode = keyEntry->keyCode;
4294 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4295 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4296 connection->inputState.removeFallbackKey(originalKeyCode);
4297 }
4298
4299 if (handled || !dispatchEntry->hasForegroundTarget()) {
4300 // If the application handles the original key for which we previously
4301 // generated a fallback or if the window is not a foreground window,
4302 // then cancel the associated fallback key, if any.
4303 if (fallbackKeyCode != -1) {
4304 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004306 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004307 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4308 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4309 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310#endif
4311 KeyEvent event;
4312 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004313 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314
4315 mLock.unlock();
4316
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004317 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(), &event,
4318 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319
4320 mLock.lock();
4321
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004322 // Cancel the fallback key.
4323 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004325 "application handled the original non-fallback key "
4326 "or is no longer a foreground target, "
4327 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 options.keyCode = fallbackKeyCode;
4329 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004331 connection->inputState.removeFallbackKey(originalKeyCode);
4332 }
4333 } else {
4334 // If the application did not handle a non-fallback key, first check
4335 // that we are in a good state to perform unhandled key event processing
4336 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004337 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004338 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004340 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004341 "since this is not an initial down. "
4342 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4343 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004345 return false;
4346 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004348 // Dispatch the unhandled key to the policy.
4349#if DEBUG_OUTBOUND_EVENT_DETAILS
4350 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004351 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4352 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004353#endif
4354 KeyEvent event;
4355 initializeKeyEvent(&event, keyEntry);
4356
4357 mLock.unlock();
4358
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004359 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(), &event,
4360 keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004361
4362 mLock.lock();
4363
4364 if (connection->status != Connection::STATUS_NORMAL) {
4365 connection->inputState.removeFallbackKey(originalKeyCode);
4366 return false;
4367 }
4368
4369 // Latch the fallback keycode for this key on an initial down.
4370 // The fallback keycode cannot change at any other point in the lifecycle.
4371 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004373 fallbackKeyCode = event.getKeyCode();
4374 } else {
4375 fallbackKeyCode = AKEYCODE_UNKNOWN;
4376 }
4377 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4378 }
4379
4380 ALOG_ASSERT(fallbackKeyCode != -1);
4381
4382 // Cancel the fallback key if the policy decides not to send it anymore.
4383 // We will continue to dispatch the key to the policy but we will no
4384 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004385 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4386 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004387#if DEBUG_OUTBOUND_EVENT_DETAILS
4388 if (fallback) {
4389 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004390 "as a fallback for %d, but on the DOWN it had requested "
4391 "to send %d instead. Fallback canceled.",
4392 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004393 } else {
4394 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004395 "but on the DOWN it had requested to send %d. "
4396 "Fallback canceled.",
4397 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004398 }
4399#endif
4400
4401 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4402 "canceling fallback, policy no longer desires it");
4403 options.keyCode = fallbackKeyCode;
4404 synthesizeCancelationEventsForConnectionLocked(connection, options);
4405
4406 fallback = false;
4407 fallbackKeyCode = AKEYCODE_UNKNOWN;
4408 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004409 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004410 }
4411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412
4413#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004414 {
4415 std::string msg;
4416 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4417 connection->inputState.getFallbackKeys();
4418 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004419 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004421 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004422 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004423 }
4424#endif
4425
4426 if (fallback) {
4427 // Restart the dispatch cycle using the fallback key.
4428 keyEntry->eventTime = event.getEventTime();
4429 keyEntry->deviceId = event.getDeviceId();
4430 keyEntry->source = event.getSource();
4431 keyEntry->displayId = event.getDisplayId();
4432 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4433 keyEntry->keyCode = fallbackKeyCode;
4434 keyEntry->scanCode = event.getScanCode();
4435 keyEntry->metaState = event.getMetaState();
4436 keyEntry->repeatCount = event.getRepeatCount();
4437 keyEntry->downTime = event.getDownTime();
4438 keyEntry->syntheticRepeat = false;
4439
4440#if DEBUG_OUTBOUND_EVENT_DETAILS
4441 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004442 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4443 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004444#endif
4445 return true; // restart the event
4446 } else {
4447#if DEBUG_OUTBOUND_EVENT_DETAILS
4448 ALOGD("Unhandled key event: No fallback key.");
4449#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004450
4451 // Report the key as unhandled, since there is no fallback key.
4452 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453 }
4454 }
4455 return false;
4456}
4457
4458bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004459 DispatchEntry* dispatchEntry,
4460 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461 return false;
4462}
4463
4464void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4465 mLock.unlock();
4466
4467 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4468
4469 mLock.lock();
4470}
4471
4472void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004473 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004474 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4475 entry->downTime, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476}
4477
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004478void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004479 int32_t injectionResult,
4480 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481 // TODO Write some statistics about how long we spend waiting.
4482}
4483
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004484/**
4485 * Report the touch event latency to the statsd server.
4486 * Input events are reported for statistics if:
4487 * - This is a touchscreen event
4488 * - InputFilter is not enabled
4489 * - Event is not injected or synthesized
4490 *
4491 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4492 * from getting aggregated with the "old" data.
4493 */
4494void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4495 REQUIRES(mLock) {
4496 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4497 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4498 if (!reportForStatistics) {
4499 return;
4500 }
4501
4502 if (mTouchStatistics.shouldReport()) {
4503 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4504 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4505 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4506 mTouchStatistics.reset();
4507 }
4508 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4509 mTouchStatistics.addValue(latencyMicros);
4510}
4511
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512void InputDispatcher::traceInboundQueueLengthLocked() {
4513 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004514 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515 }
4516}
4517
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004518void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 if (ATRACE_ENABLED()) {
4520 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004521 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004522 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 }
4524}
4525
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004526void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527 if (ATRACE_ENABLED()) {
4528 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004529 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004530 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531 }
4532}
4533
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004534void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004535 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004537 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 dumpDispatchStateLocked(dump);
4539
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004540 if (!mLastANRState.empty()) {
4541 dump += "\nInput Dispatcher State at time of last ANR:\n";
4542 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 }
4544}
4545
4546void InputDispatcher::monitor() {
4547 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004548 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004550 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551}
4552
Garfield Tane84e6f92019-08-29 17:28:41 -07004553} // namespace android::inputdispatcher