blob: 9c0e08e29783820974e2b8f5910e59a10b3177cf [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
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
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),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700248 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tan00f511d2019-06-12 16:55:40 -0700249 mAppSwitchSawKeyDown(false),
250 mAppSwitchDueTime(LONG_LONG_MAX),
251 mNextUnblockedEvent(nullptr),
252 mDispatchEnabled(false),
253 mDispatchFrozen(false),
254 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800255 // mInTouchMode will be initialized by the WindowManager to the default device config.
256 // To avoid leaking stack in case that call never comes, and for tests,
257 // initialize it here anyways.
258 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700259 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
260 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800262 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800263
Yi Kong9b14ac62018-07-17 13:48:38 -0700264 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800265
266 policy->getDispatcherConfiguration(&mConfig);
267}
268
269InputDispatcher::~InputDispatcher() {
270 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800271 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272
273 resetKeyRepeatLocked();
274 releasePendingEventLocked();
275 drainInboundQueueLocked();
276 }
277
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700278 while (!mConnectionsByFd.empty()) {
279 sp<Connection> connection = mConnectionsByFd.begin()->second;
280 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800281 }
282}
283
284void InputDispatcher::dispatchOnce() {
285 nsecs_t nextWakeupTime = LONG_LONG_MAX;
286 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800287 std::scoped_lock _l(mLock);
288 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800289
290 // Run a dispatch loop if there are no pending commands.
291 // The dispatch loop might enqueue commands to run afterwards.
292 if (!haveCommandsLocked()) {
293 dispatchOnceInnerLocked(&nextWakeupTime);
294 }
295
296 // Run all pending commands if there are any.
297 // If any commands were run then force the next poll to wake up immediately.
298 if (runCommandsLockedInterruptible()) {
299 nextWakeupTime = LONG_LONG_MIN;
300 }
301 } // release lock
302
303 // Wait for callback or timeout or wake. (make sure we round up, not down)
304 nsecs_t currentTime = now();
305 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
306 mLooper->pollOnce(timeoutMillis);
307}
308
309void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
310 nsecs_t currentTime = now();
311
Jeff Browndc5992e2014-04-11 01:27:26 -0700312 // Reset the key repeat timer whenever normal dispatch is suspended while the
313 // device is in a non-interactive state. This is to ensure that we abort a key
314 // repeat if the device is just coming out of sleep.
315 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800316 resetKeyRepeatLocked();
317 }
318
319 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
320 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100321 if (DEBUG_FOCUS) {
322 ALOGD("Dispatch frozen. Waiting some more.");
323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800324 return;
325 }
326
327 // Optimize latency of app switches.
328 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
329 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
330 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
331 if (mAppSwitchDueTime < *nextWakeupTime) {
332 *nextWakeupTime = mAppSwitchDueTime;
333 }
334
335 // Ready to start a new event.
336 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700337 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700338 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800339 if (isAppSwitchDue) {
340 // The inbound queue is empty so the app switch key we were waiting
341 // for will never arrive. Stop waiting for it.
342 resetPendingAppSwitchLocked(false);
343 isAppSwitchDue = false;
344 }
345
346 // Synthesize a key repeat if appropriate.
347 if (mKeyRepeatState.lastKeyEntry) {
348 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
349 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
350 } else {
351 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
352 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
353 }
354 }
355 }
356
357 // Nothing to do if there is no pending event.
358 if (!mPendingEvent) {
359 return;
360 }
361 } else {
362 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700363 mPendingEvent = mInboundQueue.front();
364 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800365 traceInboundQueueLengthLocked();
366 }
367
368 // Poke user activity for this event.
369 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700370 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800371 }
372
373 // Get ready to dispatch the event.
374 resetANRTimeoutsLocked();
375 }
376
377 // Now we have an event to dispatch.
378 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700379 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800380 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700381 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800382 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700383 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800384 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700385 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800386 }
387
388 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700389 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800390 }
391
392 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700393 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700394 ConfigurationChangedEntry* typedEntry =
395 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
396 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700397 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700398 break;
399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800400
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700401 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700402 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
403 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700404 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700405 break;
406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800407
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700408 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700409 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
410 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700411 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700412 resetPendingAppSwitchLocked(true);
413 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700414 } else if (dropReason == DropReason::NOT_DROPPED) {
415 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700416 }
417 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700418 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700419 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700420 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700421 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
422 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700423 }
424 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
425 break;
426 }
427
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700428 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700429 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700430 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
431 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800432 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700433 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700434 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700435 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700436 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
437 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700438 }
439 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
440 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800442 }
443
444 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700445 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700446 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800447 }
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) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700461 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700462 // 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.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700465 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700466 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700467 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700468 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700469 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700470 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
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700474 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700475 mAppSwitchSawKeyDown = false;
476 needWake = true;
477 }
478 }
479 }
480 break;
481 }
482
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700483 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700484 // 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 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700511 case EventEntry::Type::CONFIGURATION_CHANGED:
512 case EventEntry::Type::DEVICE_RESET: {
513 // nothing to do
514 break;
515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516 }
517
518 return needWake;
519}
520
521void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
522 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700523 mRecentQueue.push_back(entry);
524 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
525 mRecentQueue.front()->release();
526 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 }
528}
529
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700530sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
531 int32_t y, bool addOutsideTargets,
532 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800534 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
535 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800536 const InputWindowInfo* windowInfo = windowHandle->getInfo();
537 if (windowInfo->displayId == displayId) {
538 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539
540 if (windowInfo->visible) {
541 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700542 bool isTouchModal = (flags &
543 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
544 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800546 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700547 if (portalToDisplayId != ADISPLAY_ID_NONE &&
548 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800549 if (addPortalWindows) {
550 // For the monitoring channels of the display.
551 mTempTouchState.addPortalWindow(windowHandle);
552 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700553 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
554 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800555 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 // Found window.
557 return windowHandle;
558 }
559 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800560
561 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700562 mTempTouchState.addOrUpdateWindow(windowHandle,
563 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
564 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 }
568 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700569 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570}
571
Garfield Tane84e6f92019-08-29 17:28:41 -0700572std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000573 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
574 std::vector<TouchedMonitor> touchedMonitors;
575
576 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
577 addGestureMonitors(monitors, touchedMonitors);
578 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
579 const InputWindowInfo* windowInfo = portalWindow->getInfo();
580 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700581 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
582 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000583 }
584 return touchedMonitors;
585}
586
587void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700588 std::vector<TouchedMonitor>& outTouchedMonitors,
589 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000590 if (monitors.empty()) {
591 return;
592 }
593 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
594 for (const Monitor& monitor : monitors) {
595 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
596 }
597}
598
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700599void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600 const char* reason;
601 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700602 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700604 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700606 reason = "inbound event was dropped because the policy consumed it";
607 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700608 case DropReason::DISABLED:
609 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700610 ALOGI("Dropped event because input dispatch is disabled.");
611 }
612 reason = "inbound event was dropped because input dispatch is disabled";
613 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700614 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700615 ALOGI("Dropped event because of pending overdue app switch.");
616 reason = "inbound event was dropped because of pending overdue app switch";
617 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700618 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700619 ALOGI("Dropped event because the current application is not responding and the user "
620 "has started interacting with a different application.");
621 reason = "inbound event was dropped because the current application is not responding "
622 "and the user has started interacting with a different application";
623 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700624 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700625 ALOGI("Dropped event because it is stale.");
626 reason = "inbound event was dropped because it is stale";
627 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700628 case DropReason::NOT_DROPPED: {
629 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700630 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700631 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 }
633
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700634 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700635 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800636 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
637 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700638 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700640 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700641 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
642 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700643 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
644 synthesizeCancelationEventsForAllConnectionsLocked(options);
645 } else {
646 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
647 synthesizeCancelationEventsForAllConnectionsLocked(options);
648 }
649 break;
650 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700651 case EventEntry::Type::CONFIGURATION_CHANGED:
652 case EventEntry::Type::DEVICE_RESET: {
653 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
654 break;
655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656 }
657}
658
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800659static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700660 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
661 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800662}
663
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700664bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
665 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
666 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
667 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668}
669
670bool InputDispatcher::isAppSwitchPendingLocked() {
671 return mAppSwitchDueTime != LONG_LONG_MAX;
672}
673
674void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
675 mAppSwitchDueTime = LONG_LONG_MAX;
676
677#if DEBUG_APP_SWITCH
678 if (handled) {
679 ALOGD("App switch has arrived.");
680 } else {
681 ALOGD("App switch was abandoned.");
682 }
683#endif
684}
685
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700686bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
687 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688}
689
690bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700691 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692}
693
694bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700695 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696 return false;
697 }
698
699 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700700 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700701 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700703 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704
705 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700706 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 return true;
708}
709
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700710void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
711 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712}
713
714void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700715 while (!mInboundQueue.empty()) {
716 EventEntry* entry = mInboundQueue.front();
717 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 releaseInboundEventLocked(entry);
719 }
720 traceInboundQueueLengthLocked();
721}
722
723void InputDispatcher::releasePendingEventLocked() {
724 if (mPendingEvent) {
725 resetANRTimeoutsLocked();
726 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700727 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728 }
729}
730
731void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
732 InjectionState* injectionState = entry->injectionState;
733 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
734#if DEBUG_DISPATCH_CYCLE
735 ALOGD("Injected inbound event was dropped.");
736#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800737 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 }
739 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700740 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741 }
742 addRecentEventLocked(entry);
743 entry->release();
744}
745
746void InputDispatcher::resetKeyRepeatLocked() {
747 if (mKeyRepeatState.lastKeyEntry) {
748 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700749 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 }
751}
752
Garfield Tane84e6f92019-08-29 17:28:41 -0700753KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
755
756 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700757 uint32_t policyFlags = entry->policyFlags &
758 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 if (entry->refCount == 1) {
760 entry->recycle();
761 entry->eventTime = currentTime;
762 entry->policyFlags = policyFlags;
763 entry->repeatCount += 1;
764 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700765 KeyEntry* newEntry =
766 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId,
767 entry->source, entry->displayId, policyFlags, entry->action,
768 entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
769 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770
771 mKeyRepeatState.lastKeyEntry = newEntry;
772 entry->release();
773
774 entry = newEntry;
775 }
776 entry->syntheticRepeat = true;
777
778 // Increment reference count since we keep a reference to the event in
779 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
780 entry->refCount += 1;
781
782 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
783 return entry;
784}
785
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700786bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
787 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700789 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790#endif
791
792 // Reset key repeating in case a keyboard device was added or removed or something.
793 resetKeyRepeatLocked();
794
795 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700796 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
797 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700799 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800 return true;
801}
802
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700803bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700805 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700806 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807#endif
808
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 options.deviceId = entry->deviceId;
811 synthesizeCancelationEventsForAllConnectionsLocked(options);
812 return true;
813}
814
815bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700816 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800817 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700818 if (!entry->dispatchInProgress) {
819 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
820 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
821 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
822 if (mKeyRepeatState.lastKeyEntry &&
823 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 // We have seen two identical key downs in a row which indicates that the device
825 // driver is automatically generating key repeats itself. We take note of the
826 // repeat here, but we disable our own next key repeat timer since it is clear that
827 // we will not need to synthesize key repeats ourselves.
828 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
829 resetKeyRepeatLocked();
830 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
831 } else {
832 // Not a repeat. Save key down state in case we do see a repeat later.
833 resetKeyRepeatLocked();
834 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
835 }
836 mKeyRepeatState.lastKeyEntry = entry;
837 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700838 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 resetKeyRepeatLocked();
840 }
841
842 if (entry->repeatCount == 1) {
843 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
844 } else {
845 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
846 }
847
848 entry->dispatchInProgress = true;
849
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700850 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 }
852
853 // Handle case where the policy asked us to try again later last time.
854 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
855 if (currentTime < entry->interceptKeyWakeupTime) {
856 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
857 *nextWakeupTime = entry->interceptKeyWakeupTime;
858 }
859 return false; // wait until next wakeup
860 }
861 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
862 entry->interceptKeyWakeupTime = 0;
863 }
864
865 // Give the policy a chance to intercept the key.
866 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
867 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700868 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -0700869 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800870 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700871 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +0800872 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700873 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 }
875 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700876 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877 entry->refCount += 1;
878 return false; // wait for the command to run
879 } else {
880 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
881 }
882 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 if (*dropReason == DropReason::NOT_DROPPED) {
884 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 }
886 }
887
888 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700889 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700890 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700891 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700892 : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800893 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 return true;
895 }
896
897 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800898 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700900 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
902 return false;
903 }
904
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800905 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
907 return true;
908 }
909
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800910 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700911 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912
913 // Dispatch the key.
914 dispatchEventLocked(currentTime, entry, inputTargets);
915 return true;
916}
917
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700918void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100920 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700921 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
922 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700923 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
924 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
925 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926#endif
927}
928
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700929bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
930 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000931 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700933 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934 entry->dispatchInProgress = true;
935
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700936 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937 }
938
939 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700940 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700941 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700942 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700943 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944 return true;
945 }
946
947 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
948
949 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800950 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951
952 bool conflictingPointerActions = false;
953 int32_t injectionResult;
954 if (isPointerEvent) {
955 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700956 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700957 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700958 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959 } else {
960 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700961 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700962 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 }
964 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
965 return false;
966 }
967
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800968 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100970 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700971 CancelationOptions::Mode mode(isPointerEvent
972 ? CancelationOptions::CANCEL_POINTER_EVENTS
973 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100974 CancelationOptions options(mode, "input event injection failed");
975 synthesizeCancelationEventsForMonitorsLocked(options);
976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 return true;
978 }
979
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800980 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700981 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800983 if (isPointerEvent) {
984 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
985 if (stateIndex >= 0) {
986 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800987 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800988 // The event has gone through these portal windows, so we add monitoring targets of
989 // the corresponding displays as well.
990 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800991 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +0000992 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800994 }
995 }
996 }
997 }
998
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 // Dispatch the motion.
1000 if (conflictingPointerActions) {
1001 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001002 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 synthesizeCancelationEventsForAllConnectionsLocked(options);
1004 }
1005 dispatchEventLocked(currentTime, entry, inputTargets);
1006 return true;
1007}
1008
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001009void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001011 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001012 ", policyFlags=0x%x, "
1013 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1014 "metaState=0x%x, buttonState=0x%x,"
1015 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001016 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1017 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1018 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001020 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 "x=%f, y=%f, pressure=%f, size=%f, "
1023 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1024 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001025 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1026 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1027 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1028 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1029 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1030 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1031 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1032 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1033 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1034 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035 }
1036#endif
1037}
1038
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001039void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1040 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001041 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042#if DEBUG_DISPATCH_CYCLE
1043 ALOGD("dispatchEventToCurrentInputTargets");
1044#endif
1045
1046 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1047
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001048 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001050 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001051 sp<Connection> connection =
1052 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001053 if (connection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1055 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001056 if (DEBUG_FOCUS) {
1057 ALOGD("Dropping event delivery to target with channel '%s' because it "
1058 "is no longer registered with the input dispatcher.",
1059 inputTarget.inputChannel->getName().c_str());
1060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 }
1062 }
1063}
1064
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001065int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001066 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001069 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001071 if (DEBUG_FOCUS) {
1072 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1073 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1075 mInputTargetWaitStartTime = currentTime;
1076 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1077 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001078 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 }
1080 } else {
1081 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001082 if (DEBUG_FOCUS) {
1083 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
1084 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001087 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001089 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001090 timeout =
1091 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 } else {
1093 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1094 }
1095
1096 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1097 mInputTargetWaitStartTime = currentTime;
1098 mInputTargetWaitTimeoutTime = currentTime + timeout;
1099 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001100 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001101
Yi Kong9b14ac62018-07-17 13:48:38 -07001102 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001103 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104 }
Robert Carr740167f2018-10-11 19:03:41 -07001105 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1106 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 }
1108 }
1109 }
1110
1111 if (mInputTargetWaitTimeoutExpired) {
1112 return INPUT_EVENT_INJECTION_TIMED_OUT;
1113 }
1114
1115 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001116 onANRLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001117 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118
1119 // Force poll loop to wake up immediately on next iteration once we get the
1120 // ANR response back from the policy.
1121 *nextWakeupTime = LONG_LONG_MIN;
1122 return INPUT_EVENT_INJECTION_PENDING;
1123 } else {
1124 // Force poll loop to wake up when timeout is due.
1125 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1126 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1127 }
1128 return INPUT_EVENT_INJECTION_PENDING;
1129 }
1130}
1131
Robert Carr803535b2018-08-02 16:38:15 -07001132void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1133 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1134 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1135 state.removeWindowByToken(token);
1136 }
1137}
1138
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001139void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001140 nsecs_t newTimeout, const sp<IBinder>& inputConnectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 if (newTimeout > 0) {
1142 // Extend the timeout.
1143 mInputTargetWaitTimeoutTime = now() + newTimeout;
1144 } else {
1145 // Give up.
1146 mInputTargetWaitTimeoutExpired = true;
1147
1148 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001149 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001150 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001151 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001153 if (connection->status == Connection::STATUS_NORMAL) {
1154 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1155 "application not responding");
1156 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 }
1158 }
1159 }
1160}
1161
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001162nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1164 return currentTime - mInputTargetWaitStartTime;
1165 }
1166 return 0;
1167}
1168
1169void InputDispatcher::resetANRTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001170 if (DEBUG_FOCUS) {
1171 ALOGD("Resetting ANR timeouts.");
1172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173
1174 // Reset input target wait timeout.
1175 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001176 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177}
1178
Tiger Huang721e26f2018-07-24 22:26:19 +08001179/**
1180 * Get the display id that the given event should go to. If this event specifies a valid display id,
1181 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1182 * Focused display is the display that the user most recently interacted with.
1183 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001184int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001185 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001186 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001187 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001188 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1189 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001190 break;
1191 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001192 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001193 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1194 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001195 break;
1196 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001197 case EventEntry::Type::CONFIGURATION_CHANGED:
1198 case EventEntry::Type::DEVICE_RESET: {
1199 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001200 return ADISPLAY_ID_NONE;
1201 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001202 }
1203 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1204}
1205
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001207 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001208 std::vector<InputTarget>& inputTargets,
1209 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001211 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212
Tiger Huang721e26f2018-07-24 22:26:19 +08001213 int32_t displayId = getTargetDisplayId(entry);
1214 sp<InputWindowHandle> focusedWindowHandle =
1215 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1216 sp<InputApplicationHandle> focusedApplicationHandle =
1217 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1218
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 // If there is no currently focused window and no focused application
1220 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001221 if (focusedWindowHandle == nullptr) {
1222 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001223 injectionResult =
1224 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1225 nullptr, nextWakeupTime,
1226 "Waiting because no window has focus but there is "
1227 "a focused application that may eventually add a "
1228 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 goto Unresponsive;
1230 }
1231
Arthur Hung3b413f22018-10-26 18:05:34 +08001232 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001233 "%" PRId32 ".",
1234 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1236 goto Failed;
1237 }
1238
1239 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001240 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1242 goto Failed;
1243 }
1244
Jeff Brownffb49772014-10-10 19:01:34 -07001245 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001246 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001247 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001248 injectionResult =
1249 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1250 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 goto Unresponsive;
1252 }
1253
1254 // Success! Output targets.
1255 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001256 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001257 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1258 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259
1260 // Done.
1261Failed:
1262Unresponsive:
1263 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001264 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001265 if (DEBUG_FOCUS) {
1266 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1267 "timeSpentWaitingForApplication=%0.1fms",
1268 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1269 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 return injectionResult;
1271}
1272
1273int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001274 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001275 std::vector<InputTarget>& inputTargets,
1276 nsecs_t* nextWakeupTime,
1277 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001278 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 enum InjectionPermission {
1280 INJECTION_PERMISSION_UNKNOWN,
1281 INJECTION_PERMISSION_GRANTED,
1282 INJECTION_PERMISSION_DENIED
1283 };
1284
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285 // For security reasons, we defer updating the touch state until we are sure that
1286 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001287 int32_t displayId = entry.displayId;
1288 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1290
1291 // Update the touch state as needed based on the properties of the touch event.
1292 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1293 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1294 sp<InputWindowHandle> newHoverWindowHandle;
1295
Jeff Brownf086ddb2014-02-11 14:28:48 -08001296 // Copy current touch state into mTempTouchState.
1297 // This state is always reset at the end of this function, so if we don't find state
1298 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001299 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001300 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1301 if (oldStateIndex >= 0) {
1302 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1303 mTempTouchState.copyFrom(*oldState);
1304 }
1305
1306 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001308 (mTempTouchState.deviceId != entry.deviceId || mTempTouchState.source != entry.source ||
1309 mTempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001310 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1311 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1312 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1313 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1314 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001315 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 bool wrongDevice = false;
1317 if (newGesture) {
1318 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001319 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001320 if (DEBUG_FOCUS) {
1321 ALOGD("Dropping event because a pointer for a different device is already down "
1322 "in display %" PRId32,
1323 displayId);
1324 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001325 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1327 switchedDevice = false;
1328 wrongDevice = true;
1329 goto Failed;
1330 }
1331 mTempTouchState.reset();
1332 mTempTouchState.down = down;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001333 mTempTouchState.deviceId = entry.deviceId;
1334 mTempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 mTempTouchState.displayId = displayId;
1336 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001337 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001338 if (DEBUG_FOCUS) {
1339 ALOGI("Dropping move event because a pointer for a different device is already active "
1340 "in display %" PRId32,
1341 displayId);
1342 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001343 // TODO: test multiple simultaneous input streams.
1344 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1345 switchedDevice = false;
1346 wrongDevice = true;
1347 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348 }
1349
1350 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1351 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1352
Garfield Tan00f511d2019-06-12 16:55:40 -07001353 int32_t x;
1354 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001356 // Always dispatch mouse events to cursor position.
1357 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001358 x = int32_t(entry.xCursorPosition);
1359 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001360 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001361 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1362 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001363 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001364 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001365 sp<InputWindowHandle> newTouchedWindowHandle =
1366 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1367 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001368
1369 std::vector<TouchedMonitor> newGestureMonitors = isDown
1370 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1371 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001374 if (newTouchedWindowHandle != nullptr &&
1375 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001376 // New window supports splitting, but we should never split mouse events.
1377 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 } else if (isSplit) {
1379 // New window does not support splitting but we have already split events.
1380 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001381 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 }
1383
1384 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001385 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 // Try to assign the pointer to the first foreground window we find, if there is one.
1387 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001388 }
1389
1390 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1391 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001392 "(%d, %d) in display %" PRId32 ".",
1393 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001394 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1395 goto Failed;
1396 }
1397
1398 if (newTouchedWindowHandle != nullptr) {
1399 // Set target flags.
1400 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1401 if (isSplit) {
1402 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001404 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1405 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1406 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1407 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1408 }
1409
1410 // Update hover state.
1411 if (isHoverAction) {
1412 newHoverWindowHandle = newTouchedWindowHandle;
1413 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1414 newHoverWindowHandle = mLastHoverWindowHandle;
1415 }
1416
1417 // Update the temporary touch state.
1418 BitSet32 pointerIds;
1419 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001420 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001421 pointerIds.markBit(pointerId);
1422 }
1423 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 }
1425
Michael Wright3dd60e22019-03-27 22:06:44 +00001426 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 } else {
1428 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1429
1430 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001431 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001432 if (DEBUG_FOCUS) {
1433 ALOGD("Dropping event because the pointer is not down or we previously "
1434 "dropped the pointer down event in display %" PRId32,
1435 displayId);
1436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1438 goto Failed;
1439 }
1440
1441 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001442 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001443 mTempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001444 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1445 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446
1447 sp<InputWindowHandle> oldTouchedWindowHandle =
1448 mTempTouchState.getFirstForegroundWindowHandle();
1449 sp<InputWindowHandle> newTouchedWindowHandle =
1450 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001451 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1452 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001453 if (DEBUG_FOCUS) {
1454 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1455 oldTouchedWindowHandle->getName().c_str(),
1456 newTouchedWindowHandle->getName().c_str(), displayId);
1457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 // Make a slippery exit from the old window.
1459 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001460 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1461 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462
1463 // Make a slippery entrance into the new window.
1464 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1465 isSplit = true;
1466 }
1467
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001468 int32_t targetFlags =
1469 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 if (isSplit) {
1471 targetFlags |= InputTarget::FLAG_SPLIT;
1472 }
1473 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1474 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1475 }
1476
1477 BitSet32 pointerIds;
1478 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001479 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 }
1481 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1482 }
1483 }
1484 }
1485
1486 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1487 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001488 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489#if DEBUG_HOVER
1490 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001491 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492#endif
1493 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001494 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1495 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 }
1497
1498 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001499 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500#if DEBUG_HOVER
1501 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001502 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503#endif
1504 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001505 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1506 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 }
1508 }
1509
1510 // Check permission to inject into all touched foreground windows and ensure there
1511 // is at least one touched foreground window.
1512 {
1513 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001514 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1516 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001517 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1519 injectionPermission = INJECTION_PERMISSION_DENIED;
1520 goto Failed;
1521 }
1522 }
1523 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001524 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1525 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001526 if (DEBUG_FOCUS) {
1527 ALOGD("Dropping event because there is no touched foreground window in display "
1528 "%" PRId32 " or gesture monitor to receive it.",
1529 displayId);
1530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1532 goto Failed;
1533 }
1534
1535 // Permission granted to injection into all touched foreground windows.
1536 injectionPermission = INJECTION_PERMISSION_GRANTED;
1537 }
1538
1539 // Check whether windows listening for outside touches are owned by the same UID. If it is
1540 // set the policy flag that we will not reveal coordinate information to this window.
1541 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1542 sp<InputWindowHandle> foregroundWindowHandle =
1543 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001544 if (foregroundWindowHandle) {
1545 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1546 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1547 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1548 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1549 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1550 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001551 InputTarget::FLAG_ZERO_COORDS,
1552 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 }
1555 }
1556 }
1557 }
1558
1559 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001560 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001562 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001563 std::string reason =
1564 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1565 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001566 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001567 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1568 touchedWindow.windowHandle,
1569 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 goto Unresponsive;
1571 }
1572 }
1573 }
1574
1575 // If this is the first pointer going down and the touched window has a wallpaper
1576 // then also add the touched wallpaper windows so they are locked in for the duration
1577 // of the touch gesture.
1578 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1579 // engine only supports touch events. We would need to add a mechanism similar
1580 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1581 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1582 sp<InputWindowHandle> foregroundWindowHandle =
1583 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001584 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001585 const std::vector<sp<InputWindowHandle>> windowHandles =
1586 getWindowHandlesLocked(displayId);
1587 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001589 if (info->displayId == displayId &&
1590 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1591 mTempTouchState
1592 .addOrUpdateWindow(windowHandle,
1593 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1594 InputTarget::
1595 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1596 InputTarget::FLAG_DISPATCH_AS_IS,
1597 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 }
1599 }
1600 }
1601 }
1602
1603 // Success! Output targets.
1604 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1605
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001606 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001608 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609 }
1610
Michael Wright3dd60e22019-03-27 22:06:44 +00001611 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1612 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001613 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001614 }
1615
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 // Drop the outside or hover touch windows since we will not care about them
1617 // in the next iteration.
1618 mTempTouchState.filterNonAsIsTouchWindows();
1619
1620Failed:
1621 // Check injection permission once and for all.
1622 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001623 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 injectionPermission = INJECTION_PERMISSION_GRANTED;
1625 } else {
1626 injectionPermission = INJECTION_PERMISSION_DENIED;
1627 }
1628 }
1629
1630 // Update final pieces of touch state if the injector had permission.
1631 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1632 if (!wrongDevice) {
1633 if (switchedDevice) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001634 if (DEBUG_FOCUS) {
1635 ALOGD("Conflicting pointer actions: Switched to a different device.");
1636 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 *outConflictingPointerActions = true;
1638 }
1639
1640 if (isHoverAction) {
1641 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001642 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001643 if (DEBUG_FOCUS) {
1644 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1645 "down.");
1646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 *outConflictingPointerActions = true;
1648 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001649 mTempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001650 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1651 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001652 mTempTouchState.deviceId = entry.deviceId;
1653 mTempTouchState.source = entry.source;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001654 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001656 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1657 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001659 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1661 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001662 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001663 if (DEBUG_FOCUS) {
1664 ALOGD("Conflicting pointer actions: Down received while already down.");
1665 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 *outConflictingPointerActions = true;
1667 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1669 // One pointer went up.
1670 if (isSplit) {
1671 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001672 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001674 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001675 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1677 touchedWindow.pointerIds.clearBit(pointerId);
1678 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001679 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 continue;
1681 }
1682 }
1683 i += 1;
1684 }
1685 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001686 }
1687
1688 // Save changes unless the action was scroll in which case the temporary touch
1689 // state was only valid for this one action.
1690 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1691 if (mTempTouchState.displayId >= 0) {
1692 if (oldStateIndex >= 0) {
1693 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1694 } else {
1695 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1696 }
1697 } else if (oldStateIndex >= 0) {
1698 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1699 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 }
1701
1702 // Update hover state.
1703 mLastHoverWindowHandle = newHoverWindowHandle;
1704 }
1705 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001706 if (DEBUG_FOCUS) {
1707 ALOGD("Not updating touch focus because injection was denied.");
1708 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 }
1710
1711Unresponsive:
1712 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1713 mTempTouchState.reset();
1714
1715 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001716 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001717 if (DEBUG_FOCUS) {
1718 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1719 "timeSpentWaitingForApplication=%0.1fms",
1720 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1721 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 return injectionResult;
1723}
1724
1725void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001726 int32_t targetFlags, BitSet32 pointerIds,
1727 std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001728 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1729 if (inputChannel == nullptr) {
1730 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1731 return;
1732 }
1733
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001735 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001736 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 target.flags = targetFlags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001738 target.xOffset = -windowInfo->frameLeft;
1739 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001740 target.globalScaleFactor = windowInfo->globalScaleFactor;
1741 target.windowXScale = windowInfo->windowXScale;
1742 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001744 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745}
1746
Michael Wright3dd60e22019-03-27 22:06:44 +00001747void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001748 int32_t displayId, float xOffset,
1749 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001750 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1751 mGlobalMonitorsByDisplay.find(displayId);
1752
1753 if (it != mGlobalMonitorsByDisplay.end()) {
1754 const std::vector<Monitor>& monitors = it->second;
1755 for (const Monitor& monitor : monitors) {
1756 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 }
1759}
1760
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001761void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1762 float yOffset,
1763 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001764 InputTarget target;
1765 target.inputChannel = monitor.inputChannel;
1766 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1767 target.xOffset = xOffset;
1768 target.yOffset = yOffset;
1769 target.pointerIds.clear();
1770 target.globalScaleFactor = 1.0f;
1771 inputTargets.push_back(target);
1772}
1773
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001775 const InjectionState* injectionState) {
1776 if (injectionState &&
1777 (windowHandle == nullptr ||
1778 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1779 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001780 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001782 "owned by uid %d",
1783 injectionState->injectorPid, injectionState->injectorUid,
1784 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 } else {
1786 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001787 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 }
1789 return false;
1790 }
1791 return true;
1792}
1793
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001794bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1795 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001797 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1798 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 if (otherHandle == windowHandle) {
1800 break;
1801 }
1802
1803 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001804 if (otherInfo->displayId == displayId && otherInfo->visible &&
1805 !otherInfo->isTrustedOverlay() && otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 return true;
1807 }
1808 }
1809 return false;
1810}
1811
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001812bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1813 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001814 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001815 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001816 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001817 if (otherHandle == windowHandle) {
1818 break;
1819 }
1820
1821 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001822 if (otherInfo->displayId == displayId && otherInfo->visible &&
1823 !otherInfo->isTrustedOverlay() && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001824 return true;
1825 }
1826 }
1827 return false;
1828}
1829
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001830std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
1831 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001832 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07001833 // If the window is paused then keep waiting.
1834 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001835 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001836 }
1837
1838 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001839 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001840 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001841 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001842 "registered with the input dispatcher. The window may be in the "
1843 "process of being removed.",
1844 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001845 }
1846
1847 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07001848 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001849 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001850 "The window may be in the process of being removed.",
1851 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07001852 }
1853
1854 // If the connection is backed up then keep waiting.
1855 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001856 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001857 "Outbound queue length: %zu. Wait queue length: %zu.",
1858 targetType, connection->outboundQueue.size(),
1859 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07001860 }
1861
1862 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001863 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07001864 // If the event is a key event, then we must wait for all previous events to
1865 // complete before delivering it because previous events may have the
1866 // side-effect of transferring focus to a different window and we want to
1867 // ensure that the following keys are sent to the new window.
1868 //
1869 // Suppose the user touches a button in a window then immediately presses "A".
1870 // If the button causes a pop-up window to appear then we want to ensure that
1871 // the "A" key is delivered to the new pop-up window. This is because users
1872 // often anticipate pending UI changes when typing on a keyboard.
1873 // To obtain this behavior, we must serialize key events with respect to all
1874 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001875 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001876 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001877 "finished processing all of the input events that were previously "
1878 "delivered to it. Outbound queue length: %zu. Wait queue length: "
1879 "%zu.",
1880 targetType, connection->outboundQueue.size(),
1881 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 }
Jeff Brownffb49772014-10-10 19:01:34 -07001883 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 // Touch events can always be sent to a window immediately because the user intended
1885 // to touch whatever was visible at the time. Even if focus changes or a new
1886 // window appears moments later, the touch event was meant to be delivered to
1887 // whatever window happened to be on screen at the time.
1888 //
1889 // Generic motion events, such as trackball or joystick events are a little trickier.
1890 // Like key events, generic motion events are delivered to the focused window.
1891 // Unlike key events, generic motion events don't tend to transfer focus to other
1892 // windows and it is not important for them to be serialized. So we prefer to deliver
1893 // generic motion events as soon as possible to improve efficiency and reduce lag
1894 // through batching.
1895 //
1896 // The one case where we pause input event delivery is when the wait queue is piling
1897 // up with lots of events because the application is not responding.
1898 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001899 if (!connection->waitQueue.empty() &&
1900 currentTime >=
1901 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001902 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001903 "finished processing certain input events that were delivered to "
1904 "it over "
1905 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
1906 "%0.1fms.",
1907 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1908 connection->waitQueue.size(),
1909 (currentTime - connection->waitQueue.front()->deliveryTime) *
1910 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 }
1912 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001913 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914}
1915
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001916std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 const sp<InputApplicationHandle>& applicationHandle,
1918 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001919 if (applicationHandle != nullptr) {
1920 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001921 std::string label(applicationHandle->getName());
1922 label += " - ";
1923 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924 return label;
1925 } else {
1926 return applicationHandle->getName();
1927 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001928 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 return windowHandle->getName();
1930 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001931 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 }
1933}
1934
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001935void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001936 int32_t displayId = getTargetDisplayId(eventEntry);
1937 sp<InputWindowHandle> focusedWindowHandle =
1938 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1939 if (focusedWindowHandle != nullptr) {
1940 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1942#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001943 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944#endif
1945 return;
1946 }
1947 }
1948
1949 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001950 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001951 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001952 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
1953 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001954 return;
1955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001957 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001958 eventType = USER_ACTIVITY_EVENT_TOUCH;
1959 }
1960 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001962 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001963 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
1964 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001965 return;
1966 }
1967 eventType = USER_ACTIVITY_EVENT_BUTTON;
1968 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001970 case EventEntry::Type::CONFIGURATION_CHANGED:
1971 case EventEntry::Type::DEVICE_RESET: {
1972 LOG_ALWAYS_FATAL("%s events are not user activity",
1973 EventEntry::typeToString(eventEntry.type));
1974 break;
1975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 }
1977
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001978 std::unique_ptr<CommandEntry> commandEntry =
1979 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001980 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001982 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983}
1984
1985void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001986 const sp<Connection>& connection,
1987 EventEntry* eventEntry,
1988 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001989 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001990 std::string message =
1991 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
1992 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00001993 ATRACE_NAME(message.c_str());
1994 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995#if DEBUG_DISPATCH_CYCLE
1996 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001997 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1998 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
1999 connection->getInputChannelName().c_str(), inputTarget->flags, inputTarget->xOffset,
2000 inputTarget->yOffset, inputTarget->globalScaleFactor, inputTarget->windowXScale,
2001 inputTarget->windowYScale, inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002#endif
2003
2004 // Skip this event if the connection status is not normal.
2005 // We don't want to enqueue additional outbound events if the connection is broken.
2006 if (connection->status != Connection::STATUS_NORMAL) {
2007#if DEBUG_DISPATCH_CYCLE
2008 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002009 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010#endif
2011 return;
2012 }
2013
2014 // Split a motion event if needed.
2015 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002016 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002018 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
2019 if (inputTarget->pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002020 MotionEntry* splitMotionEntry =
2021 splitMotionEvent(originalMotionEntry, inputTarget->pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022 if (!splitMotionEntry) {
2023 return; // split event was dropped
2024 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002025 if (DEBUG_FOCUS) {
2026 ALOGD("channel '%s' ~ Split motion event.",
2027 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002028 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002029 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002030 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031 splitMotionEntry->release();
2032 return;
2033 }
2034 }
2035
2036 // Not splitting. Enqueue dispatch entries for the event as is.
2037 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2038}
2039
2040void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002041 const sp<Connection>& connection,
2042 EventEntry* eventEntry,
2043 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002044 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002045 std::string message =
2046 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32
2047 ")",
2048 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002049 ATRACE_NAME(message.c_str());
2050 }
2051
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002052 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053
2054 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002055 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002056 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002057 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002058 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002059 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002060 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002061 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002062 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002063 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002064 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002065 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002066 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067
2068 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002069 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 startDispatchCycleLocked(currentTime, connection);
2071 }
2072}
2073
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002074void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2075 EventEntry* eventEntry,
2076 const InputTarget* inputTarget,
2077 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002078 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002079 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2080 connection->getInputChannelName().c_str(),
2081 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002082 ATRACE_NAME(message.c_str());
2083 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084 int32_t inputTargetFlags = inputTarget->flags;
2085 if (!(inputTargetFlags & dispatchMode)) {
2086 return;
2087 }
2088 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2089
2090 // This is a new event.
2091 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002092 DispatchEntry* dispatchEntry =
2093 new DispatchEntry(eventEntry, // increments ref
2094 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
2095 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2096 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097
2098 // Apply target flags and update the connection's input state.
2099 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002100 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002101 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
2102 dispatchEntry->resolvedAction = keyEntry.action;
2103 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002105 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2106 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002108 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2109 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002111 delete dispatchEntry;
2112 return; // skip the inconsistent event
2113 }
2114 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002117 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002118 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002119 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2120 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2121 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2122 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2123 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2124 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2125 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2126 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2127 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2128 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2129 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002130 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002131 }
2132 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002133 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2134 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002136 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2137 "event",
2138 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002140 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002143 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002144 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2145 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2146 }
2147 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2148 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002151 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2152 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002154 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2155 "event",
2156 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002158 delete dispatchEntry;
2159 return; // skip the inconsistent event
2160 }
2161
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002162 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002163 inputTarget->inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002164
2165 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002167 case EventEntry::Type::CONFIGURATION_CHANGED:
2168 case EventEntry::Type::DEVICE_RESET: {
2169 LOG_ALWAYS_FATAL("%s events should not go to apps",
2170 EventEntry::typeToString(eventEntry->type));
2171 break;
2172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 }
2174
2175 // Remember that we are waiting for this dispatch to complete.
2176 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002177 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 }
2179
2180 // Enqueue the dispatch entry.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002181 connection->outboundQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002182 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002183}
2184
chaviwfd6d3512019-03-25 13:23:49 -07002185void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002186 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002187 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002188 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2189 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002190 return;
2191 }
2192
2193 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2194 if (inputWindowHandle == nullptr) {
2195 return;
2196 }
2197
chaviw8c9cf542019-03-25 13:02:48 -07002198 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002199 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002200
2201 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2202
2203 if (!hasFocusChanged) {
2204 return;
2205 }
2206
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002207 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2208 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002209 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002210 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211}
2212
2213void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002214 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002215 if (ATRACE_ENABLED()) {
2216 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002217 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002218 ATRACE_NAME(message.c_str());
2219 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002221 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222#endif
2223
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002224 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2225 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 dispatchEntry->deliveryTime = currentTime;
2227
2228 // Publish the event.
2229 status_t status;
2230 EventEntry* eventEntry = dispatchEntry->eventEntry;
2231 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002232 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002233 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002235 // Publish the key event.
2236 status = connection->inputPublisher
2237 .publishKeyEvent(dispatchEntry->seq, keyEntry->deviceId,
2238 keyEntry->source, keyEntry->displayId,
2239 dispatchEntry->resolvedAction,
2240 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2241 keyEntry->scanCode, keyEntry->metaState,
2242 keyEntry->repeatCount, keyEntry->downTime,
2243 keyEntry->eventTime);
2244 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 }
2246
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002247 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002248 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002250 PointerCoords scaledCoords[MAX_POINTERS];
2251 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2252
2253 // Set the X and Y offset depending on the input source.
2254 float xOffset, yOffset;
2255 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2256 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2257 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2258 float wxs = dispatchEntry->windowXScale;
2259 float wys = dispatchEntry->windowYScale;
2260 xOffset = dispatchEntry->xOffset * wxs;
2261 yOffset = dispatchEntry->yOffset * wys;
2262 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
2263 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2264 scaledCoords[i] = motionEntry->pointerCoords[i];
2265 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
2266 }
2267 usingCoords = scaledCoords;
2268 }
2269 } else {
2270 xOffset = 0.0f;
2271 yOffset = 0.0f;
2272
2273 // We don't want the dispatch target to know.
2274 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2275 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2276 scaledCoords[i].clear();
2277 }
2278 usingCoords = scaledCoords;
2279 }
2280 }
2281
2282 // Publish the motion event.
2283 status = connection->inputPublisher
2284 .publishMotionEvent(dispatchEntry->seq, motionEntry->deviceId,
2285 motionEntry->source, motionEntry->displayId,
2286 dispatchEntry->resolvedAction,
2287 motionEntry->actionButton,
2288 dispatchEntry->resolvedFlags,
2289 motionEntry->edgeFlags, motionEntry->metaState,
2290 motionEntry->buttonState,
2291 motionEntry->classification, xOffset, yOffset,
2292 motionEntry->xPrecision,
2293 motionEntry->yPrecision,
2294 motionEntry->xCursorPosition,
2295 motionEntry->yCursorPosition,
2296 motionEntry->downTime, motionEntry->eventTime,
2297 motionEntry->pointerCount,
2298 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002299 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002300 break;
2301 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002302 case EventEntry::Type::CONFIGURATION_CHANGED:
2303 case EventEntry::Type::DEVICE_RESET: {
2304 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2305 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002306 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 }
2309
2310 // Check the result.
2311 if (status) {
2312 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002313 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002315 "This is unexpected because the wait queue is empty, so the pipe "
2316 "should be empty and we shouldn't have any problems writing an "
2317 "event to it, status=%d",
2318 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2320 } else {
2321 // Pipe is full and we are waiting for the app to finish process some events
2322 // before sending more events to it.
2323#if DEBUG_DISPATCH_CYCLE
2324 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002325 "waiting for the application to catch up",
2326 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327#endif
2328 connection->inputPublisherBlocked = true;
2329 }
2330 } else {
2331 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002332 "status=%d",
2333 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2335 }
2336 return;
2337 }
2338
2339 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002340 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2341 connection->outboundQueue.end(),
2342 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002343 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002344 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002345 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 }
2347}
2348
2349void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002350 const sp<Connection>& connection, uint32_t seq,
2351 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352#if DEBUG_DISPATCH_CYCLE
2353 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002354 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355#endif
2356
2357 connection->inputPublisherBlocked = false;
2358
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002359 if (connection->status == Connection::STATUS_BROKEN ||
2360 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361 return;
2362 }
2363
2364 // Notify other system components and prepare to start the next dispatch cycle.
2365 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2366}
2367
2368void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002369 const sp<Connection>& connection,
2370 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371#if DEBUG_DISPATCH_CYCLE
2372 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002373 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374#endif
2375
2376 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002377 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002378 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002379 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002380 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381
2382 // The connection appears to be unrecoverably broken.
2383 // Ignore already broken or zombie connections.
2384 if (connection->status == Connection::STATUS_NORMAL) {
2385 connection->status = Connection::STATUS_BROKEN;
2386
2387 if (notify) {
2388 // Notify other system components.
2389 onDispatchCycleBrokenLocked(currentTime, connection);
2390 }
2391 }
2392}
2393
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002394void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2395 while (!queue.empty()) {
2396 DispatchEntry* dispatchEntry = queue.front();
2397 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002398 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 }
2400}
2401
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002402void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002404 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405 }
2406 delete dispatchEntry;
2407}
2408
2409int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2410 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2411
2412 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002413 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002415 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002417 "fd=%d, events=0x%x",
2418 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419 return 0; // remove the callback
2420 }
2421
2422 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002423 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2425 if (!(events & ALOOPER_EVENT_INPUT)) {
2426 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002427 "events=0x%x",
2428 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429 return 1;
2430 }
2431
2432 nsecs_t currentTime = now();
2433 bool gotOne = false;
2434 status_t status;
2435 for (;;) {
2436 uint32_t seq;
2437 bool handled;
2438 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2439 if (status) {
2440 break;
2441 }
2442 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2443 gotOne = true;
2444 }
2445 if (gotOne) {
2446 d->runCommandsLockedInterruptible();
2447 if (status == WOULD_BLOCK) {
2448 return 1;
2449 }
2450 }
2451
2452 notify = status != DEAD_OBJECT || !connection->monitor;
2453 if (notify) {
2454 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002455 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 }
2457 } else {
2458 // Monitor channels are never explicitly unregistered.
2459 // We do it automatically when the remote endpoint is closed so don't warn
2460 // about them.
2461 notify = !connection->monitor;
2462 if (notify) {
2463 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002464 "events=0x%x",
2465 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 }
2467 }
2468
2469 // Unregister the channel.
2470 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2471 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002472 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473}
2474
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002475void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002477 for (const auto& pair : mConnectionsByFd) {
2478 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 }
2480}
2481
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002482void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002483 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002484 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2485 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2486}
2487
2488void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2489 const CancelationOptions& options,
2490 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2491 for (const auto& it : monitorsByDisplay) {
2492 const std::vector<Monitor>& monitors = it.second;
2493 for (const Monitor& monitor : monitors) {
2494 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002495 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002496 }
2497}
2498
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2500 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002501 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002502 if (connection == nullptr) {
2503 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002505
2506 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507}
2508
2509void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2510 const sp<Connection>& connection, const CancelationOptions& options) {
2511 if (connection->status == Connection::STATUS_BROKEN) {
2512 return;
2513 }
2514
2515 nsecs_t currentTime = now();
2516
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002517 std::vector<EventEntry*> cancelationEvents =
2518 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002520 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002522 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002523 "with reality: %s, mode=%d.",
2524 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2525 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526#endif
2527 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002528 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529 switch (cancelationEventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002530 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002531 logOutboundKeyDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002532 static_cast<const KeyEntry&>(*cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002534 }
2535 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002536 logOutboundMotionDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002537 static_cast<const MotionEntry&>(
2538 *cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002539 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002540 }
2541 case EventEntry::Type::CONFIGURATION_CHANGED:
2542 case EventEntry::Type::DEVICE_RESET: {
2543 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2544 EventEntry::typeToString(cancelationEventEntry->type));
2545 break;
2546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547 }
2548
2549 InputTarget target;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002550 sp<InputWindowHandle> windowHandle =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002551 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002552 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2554 target.xOffset = -windowInfo->frameLeft;
2555 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002556 target.globalScaleFactor = windowInfo->globalScaleFactor;
2557 target.windowXScale = windowInfo->windowXScale;
2558 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 } else {
2560 target.xOffset = 0;
2561 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002562 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 }
2564 target.inputChannel = connection->inputChannel;
2565 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2566
chaviw8c9cf542019-03-25 13:02:48 -07002567 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002568 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569
2570 cancelationEventEntry->release();
2571 }
2572
2573 startDispatchCycleLocked(currentTime, connection);
2574 }
2575}
2576
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002577MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002578 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579 ALOG_ASSERT(pointerIds.value != 0);
2580
2581 uint32_t splitPointerIndexMap[MAX_POINTERS];
2582 PointerProperties splitPointerProperties[MAX_POINTERS];
2583 PointerCoords splitPointerCoords[MAX_POINTERS];
2584
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002585 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 uint32_t splitPointerCount = 0;
2587
2588 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002589 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002590 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002591 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002592 uint32_t pointerId = uint32_t(pointerProperties.id);
2593 if (pointerIds.hasBit(pointerId)) {
2594 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2595 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2596 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002597 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 splitPointerCount += 1;
2599 }
2600 }
2601
2602 if (splitPointerCount != pointerIds.count()) {
2603 // This is bad. We are missing some of the pointers that we expected to deliver.
2604 // Most likely this indicates that we received an ACTION_MOVE events that has
2605 // different pointer ids than we expected based on the previous ACTION_DOWN
2606 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2607 // in this way.
2608 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002609 "we expected there to be %d pointers. This probably means we received "
2610 "a broken sequence of pointer ids from the input device.",
2611 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002612 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 }
2614
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002615 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002617 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2618 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2620 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002621 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622 uint32_t pointerId = uint32_t(pointerProperties.id);
2623 if (pointerIds.hasBit(pointerId)) {
2624 if (pointerIds.count() == 1) {
2625 // The first/last pointer went down/up.
2626 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002627 ? AMOTION_EVENT_ACTION_DOWN
2628 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629 } else {
2630 // A secondary pointer went down/up.
2631 uint32_t splitPointerIndex = 0;
2632 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2633 splitPointerIndex += 1;
2634 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002635 action = maskedAction |
2636 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 }
2638 } else {
2639 // An unrelated pointer changed.
2640 action = AMOTION_EVENT_ACTION_MOVE;
2641 }
2642 }
2643
Garfield Tan00f511d2019-06-12 16:55:40 -07002644 MotionEntry* splitMotionEntry =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002645 new MotionEntry(originalMotionEntry.sequenceNum, originalMotionEntry.eventTime,
2646 originalMotionEntry.deviceId, originalMotionEntry.source,
2647 originalMotionEntry.displayId, originalMotionEntry.policyFlags, action,
2648 originalMotionEntry.actionButton, originalMotionEntry.flags,
2649 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2650 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2651 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2652 originalMotionEntry.xCursorPosition,
2653 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002654 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002656 if (originalMotionEntry.injectionState) {
2657 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658 splitMotionEntry->injectionState->refCount += 1;
2659 }
2660
2661 return splitMotionEntry;
2662}
2663
2664void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2665#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002666 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667#endif
2668
2669 bool needWake;
2670 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002671 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672
Prabir Pradhan42611e02018-11-27 14:04:02 -08002673 ConfigurationChangedEntry* newEntry =
2674 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675 needWake = enqueueInboundEventLocked(newEntry);
2676 } // release lock
2677
2678 if (needWake) {
2679 mLooper->wake();
2680 }
2681}
2682
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002683/**
2684 * If one of the meta shortcuts is detected, process them here:
2685 * Meta + Backspace -> generate BACK
2686 * Meta + Enter -> generate HOME
2687 * This will potentially overwrite keyCode and metaState.
2688 */
2689void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002690 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002691 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2692 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2693 if (keyCode == AKEYCODE_DEL) {
2694 newKeyCode = AKEYCODE_BACK;
2695 } else if (keyCode == AKEYCODE_ENTER) {
2696 newKeyCode = AKEYCODE_HOME;
2697 }
2698 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002699 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002700 struct KeyReplacement replacement = {keyCode, deviceId};
2701 mReplacedKeys.add(replacement, newKeyCode);
2702 keyCode = newKeyCode;
2703 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2704 }
2705 } else if (action == AKEY_EVENT_ACTION_UP) {
2706 // In order to maintain a consistent stream of up and down events, check to see if the key
2707 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2708 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002709 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002710 struct KeyReplacement replacement = {keyCode, deviceId};
2711 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2712 if (index >= 0) {
2713 keyCode = mReplacedKeys.valueAt(index);
2714 mReplacedKeys.removeItemsAt(index);
2715 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2716 }
2717 }
2718}
2719
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2721#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002722 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2723 "policyFlags=0x%x, action=0x%x, "
2724 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2725 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2726 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2727 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728#endif
2729 if (!validateKeyEvent(args->action)) {
2730 return;
2731 }
2732
2733 uint32_t policyFlags = args->policyFlags;
2734 int32_t flags = args->flags;
2735 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002736 // InputDispatcher tracks and generates key repeats on behalf of
2737 // whatever notifies it, so repeatCount should always be set to 0
2738 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2740 policyFlags |= POLICY_FLAG_VIRTUAL;
2741 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2742 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743 if (policyFlags & POLICY_FLAG_FUNCTION) {
2744 metaState |= AMETA_FUNCTION_ON;
2745 }
2746
2747 policyFlags |= POLICY_FLAG_TRUSTED;
2748
Michael Wright78f24442014-08-06 15:55:28 -07002749 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002750 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002751
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 KeyEvent event;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002753 event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2754 args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755
Michael Wright2b3c3302018-03-02 17:19:13 +00002756 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002758 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2759 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002760 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763 bool needWake;
2764 { // acquire lock
2765 mLock.lock();
2766
2767 if (shouldSendKeyToInputFilterLocked(args)) {
2768 mLock.unlock();
2769
2770 policyFlags |= POLICY_FLAG_FILTERED;
2771 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2772 return; // event was consumed by the filter
2773 }
2774
2775 mLock.lock();
2776 }
2777
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002778 KeyEntry* newEntry =
2779 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2780 args->displayId, policyFlags, args->action, flags, keyCode,
2781 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782
2783 needWake = enqueueInboundEventLocked(newEntry);
2784 mLock.unlock();
2785 } // release lock
2786
2787 if (needWake) {
2788 mLooper->wake();
2789 }
2790}
2791
2792bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2793 return mInputFilterEnabled;
2794}
2795
2796void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2797#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002798 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan00f511d2019-06-12 16:55:40 -07002799 ", policyFlags=0x%x, "
2800 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
2801 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07002802 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan00f511d2019-06-12 16:55:40 -07002803 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2804 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Jaewan Kim372fbe42019-10-02 10:58:46 +09002805 args->edgeFlags, args->xPrecision, args->yPrecision, args->xCursorPosition,
Garfield Tan00f511d2019-06-12 16:55:40 -07002806 args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 for (uint32_t i = 0; i < args->pointerCount; i++) {
2808 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002809 "x=%f, y=%f, pressure=%f, size=%f, "
2810 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2811 "orientation=%f",
2812 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2813 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2814 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2815 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2816 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2817 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2818 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2819 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2820 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2821 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 }
2823#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002824 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2825 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 return;
2827 }
2828
2829 uint32_t policyFlags = args->policyFlags;
2830 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002831
2832 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002833 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002834 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2835 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002836 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838
2839 bool needWake;
2840 { // acquire lock
2841 mLock.lock();
2842
2843 if (shouldSendMotionToInputFilterLocked(args)) {
2844 mLock.unlock();
2845
2846 MotionEvent event;
Garfield Tan00f511d2019-06-12 16:55:40 -07002847 event.initialize(args->deviceId, args->source, args->displayId, args->action,
2848 args->actionButton, args->flags, args->edgeFlags, args->metaState,
2849 args->buttonState, args->classification, 0, 0, args->xPrecision,
2850 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2851 args->downTime, args->eventTime, args->pointerCount,
2852 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853
2854 policyFlags |= POLICY_FLAG_FILTERED;
2855 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2856 return; // event was consumed by the filter
2857 }
2858
2859 mLock.lock();
2860 }
2861
2862 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07002863 MotionEntry* newEntry =
2864 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2865 args->displayId, policyFlags, args->action, args->actionButton,
2866 args->flags, args->metaState, args->buttonState,
2867 args->classification, args->edgeFlags, args->xPrecision,
2868 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2869 args->downTime, args->pointerCount, args->pointerProperties,
2870 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871
2872 needWake = enqueueInboundEventLocked(newEntry);
2873 mLock.unlock();
2874 } // release lock
2875
2876 if (needWake) {
2877 mLooper->wake();
2878 }
2879}
2880
2881bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002882 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883}
2884
2885void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2886#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002887 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002888 "switchMask=0x%08x",
2889 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890#endif
2891
2892 uint32_t policyFlags = args->policyFlags;
2893 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002894 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895}
2896
2897void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2898#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002899 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
2900 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901#endif
2902
2903 bool needWake;
2904 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002905 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906
Prabir Pradhan42611e02018-11-27 14:04:02 -08002907 DeviceResetEntry* newEntry =
2908 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002909 needWake = enqueueInboundEventLocked(newEntry);
2910 } // release lock
2911
2912 if (needWake) {
2913 mLooper->wake();
2914 }
2915}
2916
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002917int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
2918 int32_t injectorUid, int32_t syncMode,
2919 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920#if DEBUG_INBOUND_EVENT_DETAILS
2921 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002922 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2923 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924#endif
2925
2926 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2927
2928 policyFlags |= POLICY_FLAG_INJECTED;
2929 if (hasInjectionPermission(injectorPid, injectorUid)) {
2930 policyFlags |= POLICY_FLAG_TRUSTED;
2931 }
2932
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07002933 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002935 case AINPUT_EVENT_TYPE_KEY: {
2936 KeyEvent keyEvent;
2937 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2938 int32_t action = keyEvent.getAction();
2939 if (!validateKeyEvent(action)) {
2940 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002943 int32_t flags = keyEvent.getFlags();
2944 int32_t keyCode = keyEvent.getKeyCode();
2945 int32_t metaState = keyEvent.getMetaState();
2946 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2947 /*byref*/ keyCode, /*byref*/ metaState);
2948 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
2949 keyEvent.getDisplayId(), action, flags, keyCode,
2950 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
2951 keyEvent.getDownTime(), keyEvent.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002952
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002953 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2954 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00002955 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002956
2957 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2958 android::base::Timer t;
2959 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
2960 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2961 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2962 std::to_string(t.duration().count()).c_str());
2963 }
2964 }
2965
2966 mLock.lock();
2967 KeyEntry* injectedEntry =
2968 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
2969 keyEvent.getDeviceId(), keyEvent.getSource(),
2970 keyEvent.getDisplayId(), policyFlags, action, flags,
2971 keyEvent.getKeyCode(), keyEvent.getScanCode(),
2972 keyEvent.getMetaState(), keyEvent.getRepeatCount(),
2973 keyEvent.getDownTime());
2974 injectedEntries.push(injectedEntry);
2975 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976 }
2977
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002978 case AINPUT_EVENT_TYPE_MOTION: {
2979 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2980 int32_t action = motionEvent->getAction();
2981 size_t pointerCount = motionEvent->getPointerCount();
2982 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2983 int32_t actionButton = motionEvent->getActionButton();
2984 int32_t displayId = motionEvent->getDisplayId();
2985 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
2986 return INPUT_EVENT_INJECTION_FAILED;
2987 }
2988
2989 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2990 nsecs_t eventTime = motionEvent->getEventTime();
2991 android::base::Timer t;
2992 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
2993 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2994 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2995 std::to_string(t.duration().count()).c_str());
2996 }
2997 }
2998
2999 mLock.lock();
3000 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3001 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3002 MotionEntry* injectedEntry =
Garfield Tan00f511d2019-06-12 16:55:40 -07003003 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3004 motionEvent->getDeviceId(), motionEvent->getSource(),
3005 motionEvent->getDisplayId(), policyFlags, action, actionButton,
3006 motionEvent->getFlags(), motionEvent->getMetaState(),
3007 motionEvent->getButtonState(), motionEvent->getClassification(),
3008 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3009 motionEvent->getYPrecision(),
3010 motionEvent->getRawXCursorPosition(),
3011 motionEvent->getRawYCursorPosition(),
3012 motionEvent->getDownTime(), uint32_t(pointerCount),
3013 pointerProperties, samplePointerCoords,
3014 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003015 injectedEntries.push(injectedEntry);
3016 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3017 sampleEventTimes += 1;
3018 samplePointerCoords += pointerCount;
3019 MotionEntry* nextInjectedEntry =
3020 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3021 motionEvent->getDeviceId(), motionEvent->getSource(),
3022 motionEvent->getDisplayId(), policyFlags, action,
3023 actionButton, motionEvent->getFlags(),
3024 motionEvent->getMetaState(), motionEvent->getButtonState(),
3025 motionEvent->getClassification(),
3026 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3027 motionEvent->getYPrecision(),
3028 motionEvent->getRawXCursorPosition(),
3029 motionEvent->getRawYCursorPosition(),
3030 motionEvent->getDownTime(), uint32_t(pointerCount),
3031 pointerProperties, samplePointerCoords,
3032 motionEvent->getXOffset(), motionEvent->getYOffset());
3033 injectedEntries.push(nextInjectedEntry);
3034 }
3035 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003038 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003039 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003040 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041 }
3042
3043 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3044 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3045 injectionState->injectionIsAsync = true;
3046 }
3047
3048 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003049 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003050
3051 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003052 while (!injectedEntries.empty()) {
3053 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3054 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055 }
3056
3057 mLock.unlock();
3058
3059 if (needWake) {
3060 mLooper->wake();
3061 }
3062
3063 int32_t injectionResult;
3064 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003065 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066
3067 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3068 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3069 } else {
3070 for (;;) {
3071 injectionResult = injectionState->injectionResult;
3072 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3073 break;
3074 }
3075
3076 nsecs_t remainingTimeout = endTime - now();
3077 if (remainingTimeout <= 0) {
3078#if DEBUG_INJECTION
3079 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003080 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081#endif
3082 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3083 break;
3084 }
3085
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003086 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087 }
3088
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003089 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3090 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091 while (injectionState->pendingForegroundDispatches != 0) {
3092#if DEBUG_INJECTION
3093 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003094 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095#endif
3096 nsecs_t remainingTimeout = endTime - now();
3097 if (remainingTimeout <= 0) {
3098#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003099 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3100 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101#endif
3102 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3103 break;
3104 }
3105
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003106 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 }
3108 }
3109 }
3110
3111 injectionState->release();
3112 } // release lock
3113
3114#if DEBUG_INJECTION
3115 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003116 "injectorPid=%d, injectorUid=%d",
3117 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118#endif
3119
3120 return injectionResult;
3121}
3122
3123bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003124 return injectorUid == 0 ||
3125 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126}
3127
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003128void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129 InjectionState* injectionState = entry->injectionState;
3130 if (injectionState) {
3131#if DEBUG_INJECTION
3132 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003133 "injectorPid=%d, injectorUid=%d",
3134 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135#endif
3136
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003137 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 // Log the outcome since the injector did not wait for the injection result.
3139 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003140 case INPUT_EVENT_INJECTION_SUCCEEDED:
3141 ALOGV("Asynchronous input event injection succeeded.");
3142 break;
3143 case INPUT_EVENT_INJECTION_FAILED:
3144 ALOGW("Asynchronous input event injection failed.");
3145 break;
3146 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3147 ALOGW("Asynchronous input event injection permission denied.");
3148 break;
3149 case INPUT_EVENT_INJECTION_TIMED_OUT:
3150 ALOGW("Asynchronous input event injection timed out.");
3151 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 }
3153 }
3154
3155 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003156 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 }
3158}
3159
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003160void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 InjectionState* injectionState = entry->injectionState;
3162 if (injectionState) {
3163 injectionState->pendingForegroundDispatches += 1;
3164 }
3165}
3166
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003167void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168 InjectionState* injectionState = entry->injectionState;
3169 if (injectionState) {
3170 injectionState->pendingForegroundDispatches -= 1;
3171
3172 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003173 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 }
3175 }
3176}
3177
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003178std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3179 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003180 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003181}
3182
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003184 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003185 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003186 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3187 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003188 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003189 return windowHandle;
3190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191 }
3192 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003193 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194}
3195
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003196bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003197 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003198 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3199 for (const sp<InputWindowHandle>& handle : windowHandles) {
3200 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003201 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003202 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203 ", but it should belong to display %" PRId32,
3204 windowHandle->getName().c_str(), it.first,
3205 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003206 }
3207 return true;
3208 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 }
3210 }
3211 return false;
3212}
3213
Robert Carr5c8a0262018-10-03 16:30:44 -07003214sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3215 size_t count = mInputChannelsByToken.count(token);
3216 if (count == 0) {
3217 return nullptr;
3218 }
3219 return mInputChannelsByToken.at(token);
3220}
3221
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003222void InputDispatcher::updateWindowHandlesForDisplayLocked(
3223 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3224 if (inputWindowHandles.empty()) {
3225 // Remove all handles on a display if there are no windows left.
3226 mWindowHandlesByDisplay.erase(displayId);
3227 return;
3228 }
3229
3230 // Since we compare the pointer of input window handles across window updates, we need
3231 // to make sure the handle object for the same window stays unchanged across updates.
3232 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
3233 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3234 for (const sp<InputWindowHandle>& handle : oldHandles) {
3235 oldHandlesByTokens[handle->getToken()] = handle;
3236 }
3237
3238 std::vector<sp<InputWindowHandle>> newHandles;
3239 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3240 if (!handle->updateInfo()) {
3241 // handle no longer valid
3242 continue;
3243 }
3244
3245 const InputWindowInfo* info = handle->getInfo();
3246 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3247 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3248 const bool noInputChannel =
3249 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3250 const bool canReceiveInput =
3251 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3252 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3253 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003254 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003255 handle->getName().c_str());
3256 }
3257 continue;
3258 }
3259
3260 if (info->displayId != displayId) {
3261 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3262 handle->getName().c_str(), displayId, info->displayId);
3263 continue;
3264 }
3265
3266 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3267 const sp<InputWindowHandle> oldHandle = oldHandlesByTokens.at(handle->getToken());
3268 oldHandle->updateFrom(handle);
3269 newHandles.push_back(oldHandle);
3270 } else {
3271 newHandles.push_back(handle);
3272 }
3273 }
3274
3275 // Insert or replace
3276 mWindowHandlesByDisplay[displayId] = newHandles;
3277}
3278
Arthur Hungb92218b2018-08-14 12:00:21 +08003279/**
3280 * Called from InputManagerService, update window handle list by displayId that can receive input.
3281 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3282 * If set an empty list, remove all handles from the specific display.
3283 * For focused handle, check if need to change and send a cancel event to previous one.
3284 * For removed handle, check if need to send a cancel event if already in touch.
3285 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003286void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003287 int32_t displayId,
3288 const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003289 if (DEBUG_FOCUS) {
3290 std::string windowList;
3291 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3292 windowList += iwh->getName() + " ";
3293 }
3294 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3295 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003297 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298
Arthur Hungb92218b2018-08-14 12:00:21 +08003299 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003300 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3301 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003303 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
3304
Tiger Huang721e26f2018-07-24 22:26:19 +08003305 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306 bool foundHoveredWindow = false;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003307 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3308 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3309 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3310 windowHandle->getInfo()->visible) {
3311 newFocusedWindowHandle = windowHandle;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003312 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003313 if (windowHandle == mLastHoverWindowHandle) {
3314 foundHoveredWindow = true;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316 }
3317
3318 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003319 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 }
3321
Tiger Huang721e26f2018-07-24 22:26:19 +08003322 sp<InputWindowHandle> oldFocusedWindowHandle =
3323 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3324
3325 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3326 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003327 if (DEBUG_FOCUS) {
3328 ALOGD("Focus left window: %s in display %" PRId32,
3329 oldFocusedWindowHandle->getName().c_str(), displayId);
3330 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331 sp<InputChannel> focusedInputChannel =
3332 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003333 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003335 "focus left window");
3336 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003338 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003340 if (newFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003341 if (DEBUG_FOCUS) {
3342 ALOGD("Focus entered window: %s in display %" PRId32,
3343 newFocusedWindowHandle->getName().c_str(), displayId);
3344 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003345 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346 }
Robert Carrf759f162018-11-13 12:57:11 -08003347
3348 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003349 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351 }
3352
Arthur Hungb92218b2018-08-14 12:00:21 +08003353 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3354 if (stateIndex >= 0) {
3355 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003356 for (size_t i = 0; i < state.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003357 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003358 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003359 if (DEBUG_FOCUS) {
3360 ALOGD("Touched window was removed: %s in display %" PRId32,
3361 touchedWindow.windowHandle->getName().c_str(), displayId);
3362 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003363 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003364 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003365 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003366 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 "touched window was removed");
3368 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3369 options);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003370 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003371 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003372 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003373 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 }
3376 }
3377
3378 // Release information for windows that are no longer present.
3379 // This ensures that unused input channels are released promptly.
3380 // Otherwise, they might stick around until the window handle is destroyed
3381 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003382 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003383 if (!hasWindowHandleLocked(oldWindowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003384 if (DEBUG_FOCUS) {
3385 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
3386 }
Arthur Hung3b413f22018-10-26 18:05:34 +08003387 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 }
3389 }
3390 } // release lock
3391
3392 // Wake up poll loop since it may need to make new input dispatching choices.
3393 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003394
3395 if (setInputWindowsListener) {
3396 setInputWindowsListener->onSetInputWindowsFinished();
3397 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398}
3399
3400void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003401 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003402 if (DEBUG_FOCUS) {
3403 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3404 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003407 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408
Tiger Huang721e26f2018-07-24 22:26:19 +08003409 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3410 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003411 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003412 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3413 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003416 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003418 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003420 oldFocusedApplicationHandle.clear();
3421 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 } // release lock
3424
3425 // Wake up poll loop since it may need to make new input dispatching choices.
3426 mLooper->wake();
3427}
3428
Tiger Huang721e26f2018-07-24 22:26:19 +08003429/**
3430 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3431 * the display not specified.
3432 *
3433 * We track any unreleased events for each window. If a window loses the ability to receive the
3434 * released event, we will send a cancel event to it. So when the focused display is changed, we
3435 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3436 * display. The display-specified events won't be affected.
3437 */
3438void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003439 if (DEBUG_FOCUS) {
3440 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3441 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003442 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003443 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003444
3445 if (mFocusedDisplayId != displayId) {
3446 sp<InputWindowHandle> oldFocusedWindowHandle =
3447 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3448 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003449 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003450 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003451 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003452 CancelationOptions
3453 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3454 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003455 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003456 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3457 }
3458 }
3459 mFocusedDisplayId = displayId;
3460
3461 // Sanity check
3462 sp<InputWindowHandle> newFocusedWindowHandle =
3463 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003464 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003465
Tiger Huang721e26f2018-07-24 22:26:19 +08003466 if (newFocusedWindowHandle == nullptr) {
3467 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3468 if (!mFocusedWindowHandlesByDisplay.empty()) {
3469 ALOGE("But another display has a focused window:");
3470 for (auto& it : mFocusedWindowHandlesByDisplay) {
3471 const int32_t displayId = it.first;
3472 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003473 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3474 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003475 }
3476 }
3477 }
3478 }
3479
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003480 if (DEBUG_FOCUS) {
3481 logDispatchStateLocked();
3482 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003483 } // release lock
3484
3485 // Wake up poll loop since it may need to make new input dispatching choices.
3486 mLooper->wake();
3487}
3488
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003490 if (DEBUG_FOCUS) {
3491 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493
3494 bool changed;
3495 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003496 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497
3498 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3499 if (mDispatchFrozen && !frozen) {
3500 resetANRTimeoutsLocked();
3501 }
3502
3503 if (mDispatchEnabled && !enabled) {
3504 resetAndDropEverythingLocked("dispatcher is being disabled");
3505 }
3506
3507 mDispatchEnabled = enabled;
3508 mDispatchFrozen = frozen;
3509 changed = true;
3510 } else {
3511 changed = false;
3512 }
3513
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003514 if (DEBUG_FOCUS) {
3515 logDispatchStateLocked();
3516 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 } // release lock
3518
3519 if (changed) {
3520 // Wake up poll loop since it may need to make new input dispatching choices.
3521 mLooper->wake();
3522 }
3523}
3524
3525void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003526 if (DEBUG_FOCUS) {
3527 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529
3530 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003531 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532
3533 if (mInputFilterEnabled == enabled) {
3534 return;
3535 }
3536
3537 mInputFilterEnabled = enabled;
3538 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3539 } // release lock
3540
3541 // Wake up poll loop since there might be work to do to drop everything.
3542 mLooper->wake();
3543}
3544
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003545void InputDispatcher::setInTouchMode(bool inTouchMode) {
3546 std::scoped_lock lock(mLock);
3547 mInTouchMode = inTouchMode;
3548}
3549
chaviwfbe5d9c2018-12-26 12:23:37 -08003550bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3551 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003552 if (DEBUG_FOCUS) {
3553 ALOGD("Trivial transfer to same window.");
3554 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003555 return true;
3556 }
3557
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003559 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560
chaviwfbe5d9c2018-12-26 12:23:37 -08003561 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3562 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003563 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003564 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 return false;
3566 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003567 if (DEBUG_FOCUS) {
3568 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3569 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3570 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003572 if (DEBUG_FOCUS) {
3573 ALOGD("Cannot transfer focus because windows are on different displays.");
3574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575 return false;
3576 }
3577
3578 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003579 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3580 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3581 for (size_t i = 0; i < state.windows.size(); i++) {
3582 const TouchedWindow& touchedWindow = state.windows[i];
3583 if (touchedWindow.windowHandle == fromWindowHandle) {
3584 int32_t oldTargetFlags = touchedWindow.targetFlags;
3585 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003587 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003589 int32_t newTargetFlags = oldTargetFlags &
3590 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3591 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003592 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593
Jeff Brownf086ddb2014-02-11 14:28:48 -08003594 found = true;
3595 goto Found;
3596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 }
3598 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003599 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003601 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003602 if (DEBUG_FOCUS) {
3603 ALOGD("Focus transfer failed because from window did not have focus.");
3604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 return false;
3606 }
3607
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003608 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3609 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003610 if (fromConnection != nullptr && toConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003612 CancelationOptions
3613 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3614 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3616 }
3617
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003618 if (DEBUG_FOCUS) {
3619 logDispatchStateLocked();
3620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 } // release lock
3622
3623 // Wake up poll loop since it may need to make new input dispatching choices.
3624 mLooper->wake();
3625 return true;
3626}
3627
3628void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003629 if (DEBUG_FOCUS) {
3630 ALOGD("Resetting and dropping all events (%s).", reason);
3631 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632
3633 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3634 synthesizeCancelationEventsForAllConnectionsLocked(options);
3635
3636 resetKeyRepeatLocked();
3637 releasePendingEventLocked();
3638 drainInboundQueueLocked();
3639 resetANRTimeoutsLocked();
3640
Jeff Brownf086ddb2014-02-11 14:28:48 -08003641 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003643 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644}
3645
3646void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003647 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 dumpDispatchStateLocked(dump);
3649
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003650 std::istringstream stream(dump);
3651 std::string line;
3652
3653 while (std::getline(stream, line, '\n')) {
3654 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655 }
3656}
3657
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003658void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003659 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3660 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3661 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003662 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663
Tiger Huang721e26f2018-07-24 22:26:19 +08003664 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3665 dump += StringPrintf(INDENT "FocusedApplications:\n");
3666 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3667 const int32_t displayId = it.first;
3668 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003669 dump += StringPrintf(INDENT2 "displayId=%" PRId32
3670 ", name='%s', dispatchingTimeout=%0.3fms\n",
3671 displayId, applicationHandle->getName().c_str(),
3672 applicationHandle->getDispatchingTimeout(
3673 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3674 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08003675 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003677 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003679
3680 if (!mFocusedWindowHandlesByDisplay.empty()) {
3681 dump += StringPrintf(INDENT "FocusedWindows:\n");
3682 for (auto& it : mFocusedWindowHandlesByDisplay) {
3683 const int32_t displayId = it.first;
3684 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003685 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3686 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003687 }
3688 } else {
3689 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3690 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691
Jeff Brownf086ddb2014-02-11 14:28:48 -08003692 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003693 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003694 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3695 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003696 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003697 state.displayId, toString(state.down), toString(state.split),
3698 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003699 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003700 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003701 for (size_t i = 0; i < state.windows.size(); i++) {
3702 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003703 dump += StringPrintf(INDENT4
3704 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3705 i, touchedWindow.windowHandle->getName().c_str(),
3706 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003707 }
3708 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003709 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003710 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003711 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003712 dump += INDENT3 "Portal windows:\n";
3713 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003714 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003715 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3716 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003717 }
3718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719 }
3720 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003721 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722 }
3723
Arthur Hungb92218b2018-08-14 12:00:21 +08003724 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003725 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003726 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003727 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003728 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003729 dump += INDENT2 "Windows:\n";
3730 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003731 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003732 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733
Arthur Hungb92218b2018-08-14 12:00:21 +08003734 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003735 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
3736 "hasWallpaper=%s, "
3737 "visible=%s, canReceiveKeys=%s, flags=0x%08x, "
3738 "type=0x%08x, layer=%d, "
3739 "frame=[%d,%d][%d,%d], globalScale=%f, "
3740 "windowScale=(%f,%f), "
3741 "touchableRegion=",
3742 i, windowInfo->name.c_str(), windowInfo->displayId,
3743 windowInfo->portalToDisplayId,
3744 toString(windowInfo->paused),
3745 toString(windowInfo->hasFocus),
3746 toString(windowInfo->hasWallpaper),
3747 toString(windowInfo->visible),
3748 toString(windowInfo->canReceiveKeys),
3749 windowInfo->layoutParamsFlags,
3750 windowInfo->layoutParamsType, windowInfo->layer,
3751 windowInfo->frameLeft, windowInfo->frameTop,
3752 windowInfo->frameRight, windowInfo->frameBottom,
3753 windowInfo->globalScaleFactor, windowInfo->windowXScale,
3754 windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003755 dumpRegion(dump, windowInfo->touchableRegion);
3756 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3757 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003758 windowInfo->ownerPid, windowInfo->ownerUid,
3759 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08003760 }
3761 } else {
3762 dump += INDENT2 "Windows: <none>\n";
3763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 }
3765 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003766 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 }
3768
Michael Wright3dd60e22019-03-27 22:06:44 +00003769 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003770 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003771 const std::vector<Monitor>& monitors = it.second;
3772 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3773 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003774 }
3775 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003776 const std::vector<Monitor>& monitors = it.second;
3777 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3778 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003781 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 }
3783
3784 nsecs_t currentTime = now();
3785
3786 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003787 if (!mRecentQueue.empty()) {
3788 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
3789 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003790 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003792 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 }
3794 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003795 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 }
3797
3798 // Dump event currently being dispatched.
3799 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003800 dump += INDENT "PendingEvent:\n";
3801 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003803 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003804 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003806 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 }
3808
3809 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003810 if (!mInboundQueue.empty()) {
3811 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
3812 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003813 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003815 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816 }
3817 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003818 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 }
3820
Michael Wright78f24442014-08-06 15:55:28 -07003821 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003822 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003823 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3824 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3825 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003826 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3827 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07003828 }
3829 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003830 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003831 }
3832
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003833 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003834 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003835 for (const auto& pair : mConnectionsByFd) {
3836 const sp<Connection>& connection = pair.second;
3837 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
3838 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3839 pair.first, connection->getInputChannelName().c_str(),
3840 connection->getWindowName().c_str(), connection->getStatusLabel(),
3841 toString(connection->monitor),
3842 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003844 if (!connection->outboundQueue.empty()) {
3845 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
3846 connection->outboundQueue.size());
3847 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 dump.append(INDENT4);
3849 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003850 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003851 entry->targetFlags, entry->resolvedAction,
3852 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853 }
3854 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003855 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 }
3857
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003858 if (!connection->waitQueue.empty()) {
3859 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
3860 connection->waitQueue.size());
3861 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003862 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003864 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003865 "age=%0.1fms, wait=%0.1fms\n",
3866 entry->targetFlags, entry->resolvedAction,
3867 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3868 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 }
3870 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003871 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 }
3873 }
3874 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003875 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 }
3877
3878 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003879 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003880 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003882 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 }
3884
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003885 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003886 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003887 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003888 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889}
3890
Michael Wright3dd60e22019-03-27 22:06:44 +00003891void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3892 const size_t numMonitors = monitors.size();
3893 for (size_t i = 0; i < numMonitors; i++) {
3894 const Monitor& monitor = monitors[i];
3895 const sp<InputChannel>& channel = monitor.inputChannel;
3896 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3897 dump += "\n";
3898 }
3899}
3900
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003901status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003903 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904#endif
3905
3906 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003907 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003908 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003909 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003911 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 return BAD_VALUE;
3913 }
3914
Michael Wright3dd60e22019-03-27 22:06:44 +00003915 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916
3917 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003918 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003919 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3922 } // release lock
3923
3924 // Wake the looper because some connections have changed.
3925 mLooper->wake();
3926 return OK;
3927}
3928
Michael Wright3dd60e22019-03-27 22:06:44 +00003929status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003930 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003931 { // acquire lock
3932 std::scoped_lock _l(mLock);
3933
3934 if (displayId < 0) {
3935 ALOGW("Attempted to register input monitor without a specified display.");
3936 return BAD_VALUE;
3937 }
3938
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003939 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003940 ALOGW("Attempted to register input monitor without an identifying token.");
3941 return BAD_VALUE;
3942 }
3943
3944 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3945
3946 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003947 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003948 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00003949
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003950 auto& monitorsByDisplay =
3951 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00003952 monitorsByDisplay[displayId].emplace_back(inputChannel);
3953
3954 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00003955 }
3956 // Wake the looper because some connections have changed.
3957 mLooper->wake();
3958 return OK;
3959}
3960
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3962#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003963 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964#endif
3965
3966 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003967 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968
3969 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3970 if (status) {
3971 return status;
3972 }
3973 } // release lock
3974
3975 // Wake the poll loop because removing the connection may have changed the current
3976 // synchronization state.
3977 mLooper->wake();
3978 return OK;
3979}
3980
3981status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003982 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003983 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003984 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003986 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987 return BAD_VALUE;
3988 }
3989
John Recke0710582019-09-26 13:46:12 -07003990 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003991 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003992 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07003993
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 if (connection->monitor) {
3995 removeMonitorChannelLocked(inputChannel);
3996 }
3997
3998 mLooper->removeFd(inputChannel->getFd());
3999
4000 nsecs_t currentTime = now();
4001 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4002
4003 connection->status = Connection::STATUS_ZOMBIE;
4004 return OK;
4005}
4006
4007void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004008 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4009 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4010}
4011
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004012void InputDispatcher::removeMonitorChannelLocked(
4013 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004014 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004015 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004016 std::vector<Monitor>& monitors = it->second;
4017 const size_t numMonitors = monitors.size();
4018 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004019 if (monitors[i].inputChannel == inputChannel) {
4020 monitors.erase(monitors.begin() + i);
4021 break;
4022 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004023 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004024 if (monitors.empty()) {
4025 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004026 } else {
4027 ++it;
4028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 }
4030}
4031
Michael Wright3dd60e22019-03-27 22:06:44 +00004032status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4033 { // acquire lock
4034 std::scoped_lock _l(mLock);
4035 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4036
4037 if (!foundDisplayId) {
4038 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4039 return BAD_VALUE;
4040 }
4041 int32_t displayId = foundDisplayId.value();
4042
4043 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4044 if (stateIndex < 0) {
4045 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4046 return BAD_VALUE;
4047 }
4048
4049 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4050 std::optional<int32_t> foundDeviceId;
4051 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004052 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004053 foundDeviceId = state.deviceId;
4054 }
4055 }
4056 if (!foundDeviceId || !state.down) {
4057 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004058 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004059 return BAD_VALUE;
4060 }
4061 int32_t deviceId = foundDeviceId.value();
4062
4063 // Send cancel events to all the input channels we're stealing from.
4064 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004065 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004066 options.deviceId = deviceId;
4067 options.displayId = displayId;
4068 for (const TouchedWindow& window : state.windows) {
4069 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
4070 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4071 }
4072 // Then clear the current touch state so we stop dispatching to them as well.
4073 state.filterNonMonitors();
4074 }
4075 return OK;
4076}
4077
Michael Wright3dd60e22019-03-27 22:06:44 +00004078std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4079 const sp<IBinder>& token) {
4080 for (const auto& it : mGestureMonitorsByDisplay) {
4081 const std::vector<Monitor>& monitors = it.second;
4082 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004083 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004084 return it.first;
4085 }
4086 }
4087 }
4088 return std::nullopt;
4089}
4090
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004091sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4092 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004093 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004094 }
4095
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004096 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004097 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004098 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004099 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 }
4101 }
Robert Carr4e670e52018-08-15 13:26:12 -07004102
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004103 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104}
4105
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004106void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4107 const sp<Connection>& connection, uint32_t seq,
4108 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004109 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4110 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 commandEntry->connection = connection;
4112 commandEntry->eventTime = currentTime;
4113 commandEntry->seq = seq;
4114 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004115 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116}
4117
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004118void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4119 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004121 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004123 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4124 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004126 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127}
4128
chaviw0c06c6e2019-01-09 13:27:07 -08004129void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004130 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004131 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4132 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004133 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4134 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004135 commandEntry->oldToken = oldToken;
4136 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004137 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004138}
4139
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004140void InputDispatcher::onANRLocked(nsecs_t currentTime,
4141 const sp<InputApplicationHandle>& applicationHandle,
4142 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4143 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4145 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4146 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004147 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4148 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4149 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150
4151 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004152 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 struct tm tm;
4154 localtime_r(&t, &tm);
4155 char timestr[64];
4156 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4157 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004158 mLastANRState += INDENT "ANR:\n";
4159 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004160 mLastANRState +=
4161 StringPrintf(INDENT2 "Window: %s\n",
4162 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004163 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4164 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4165 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 dumpDispatchStateLocked(mLastANRState);
4167
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004168 std::unique_ptr<CommandEntry> commandEntry =
4169 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004171 commandEntry->inputChannel =
4172 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004174 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175}
4176
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004177void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 mLock.unlock();
4179
4180 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4181
4182 mLock.lock();
4183}
4184
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004185void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 sp<Connection> connection = commandEntry->connection;
4187
4188 if (connection->status != Connection::STATUS_ZOMBIE) {
4189 mLock.unlock();
4190
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004191 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192
4193 mLock.lock();
4194 }
4195}
4196
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004198 sp<IBinder> oldToken = commandEntry->oldToken;
4199 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004200 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004201 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004202 mLock.lock();
4203}
4204
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004205void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004206 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004207 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 mLock.unlock();
4209
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004210 nsecs_t newTimeout =
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004211 mPolicy->notifyANR(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212
4213 mLock.lock();
4214
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004215 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216}
4217
4218void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4219 CommandEntry* commandEntry) {
4220 KeyEntry* entry = commandEntry->keyEntry;
4221
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004222 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223
4224 mLock.unlock();
4225
Michael Wright2b3c3302018-03-02 17:19:13 +00004226 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004227 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004228 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004229 : nullptr;
4230 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004231 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4232 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004234 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235
4236 mLock.lock();
4237
4238 if (delay < 0) {
4239 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4240 } else if (!delay) {
4241 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4242 } else {
4243 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4244 entry->interceptKeyWakeupTime = now() + delay;
4245 }
4246 entry->release();
4247}
4248
chaviwfd6d3512019-03-25 13:23:49 -07004249void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4250 mLock.unlock();
4251 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4252 mLock.lock();
4253}
4254
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004255void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004257 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004259 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260
4261 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004262 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004263 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004264 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004266 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004267
4268 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4269 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4270 std::string msg =
4271 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4272 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4273 dispatchEntry->eventEntry->appendDescription(msg);
4274 ALOGI("%s", msg.c_str());
4275 }
4276
4277 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004278 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004279 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4280 restartEvent =
4281 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004282 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004283 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4284 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4285 handled);
4286 } else {
4287 restartEvent = false;
4288 }
4289
4290 // Dequeue the event and start the next cycle.
4291 // Note that because the lock might have been released, it is possible that the
4292 // contents of the wait queue to have been drained, so we need to double-check
4293 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004294 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4295 if (dispatchEntryIt != connection->waitQueue.end()) {
4296 dispatchEntry = *dispatchEntryIt;
4297 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004298 traceWaitQueueLength(connection);
4299 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004300 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004301 traceOutboundQueueLength(connection);
4302 } else {
4303 releaseDispatchEntry(dispatchEntry);
4304 }
4305 }
4306
4307 // Start the next dispatch cycle for this connection.
4308 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309}
4310
4311bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004312 DispatchEntry* dispatchEntry,
4313 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004314 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004315 if (!handled) {
4316 // Report the key as unhandled, since the fallback was not handled.
4317 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4318 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004319 return false;
4320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004322 // Get the fallback key state.
4323 // Clear it out after dispatching the UP.
4324 int32_t originalKeyCode = keyEntry->keyCode;
4325 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4326 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4327 connection->inputState.removeFallbackKey(originalKeyCode);
4328 }
4329
4330 if (handled || !dispatchEntry->hasForegroundTarget()) {
4331 // If the application handles the original key for which we previously
4332 // generated a fallback or if the window is not a foreground window,
4333 // then cancel the associated fallback key, if any.
4334 if (fallbackKeyCode != -1) {
4335 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004337 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004338 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4339 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4340 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004342 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004343 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344
4345 mLock.unlock();
4346
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004347 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004348 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349
4350 mLock.lock();
4351
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004352 // Cancel the fallback key.
4353 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004355 "application handled the original non-fallback key "
4356 "or is no longer a foreground target, "
4357 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 options.keyCode = fallbackKeyCode;
4359 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004361 connection->inputState.removeFallbackKey(originalKeyCode);
4362 }
4363 } else {
4364 // If the application did not handle a non-fallback key, first check
4365 // that we are in a good state to perform unhandled key event processing
4366 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004367 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004368 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004370 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004371 "since this is not an initial down. "
4372 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4373 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004375 return false;
4376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004378 // Dispatch the unhandled key to the policy.
4379#if DEBUG_OUTBOUND_EVENT_DETAILS
4380 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004381 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4382 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004383#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004384 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004385
4386 mLock.unlock();
4387
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004388 bool fallback =
4389 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4390 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004391
4392 mLock.lock();
4393
4394 if (connection->status != Connection::STATUS_NORMAL) {
4395 connection->inputState.removeFallbackKey(originalKeyCode);
4396 return false;
4397 }
4398
4399 // Latch the fallback keycode for this key on an initial down.
4400 // The fallback keycode cannot change at any other point in the lifecycle.
4401 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004403 fallbackKeyCode = event.getKeyCode();
4404 } else {
4405 fallbackKeyCode = AKEYCODE_UNKNOWN;
4406 }
4407 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4408 }
4409
4410 ALOG_ASSERT(fallbackKeyCode != -1);
4411
4412 // Cancel the fallback key if the policy decides not to send it anymore.
4413 // We will continue to dispatch the key to the policy but we will no
4414 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004415 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4416 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004417#if DEBUG_OUTBOUND_EVENT_DETAILS
4418 if (fallback) {
4419 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004420 "as a fallback for %d, but on the DOWN it had requested "
4421 "to send %d instead. Fallback canceled.",
4422 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004423 } else {
4424 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004425 "but on the DOWN it had requested to send %d. "
4426 "Fallback canceled.",
4427 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004428 }
4429#endif
4430
4431 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4432 "canceling fallback, policy no longer desires it");
4433 options.keyCode = fallbackKeyCode;
4434 synthesizeCancelationEventsForConnectionLocked(connection, options);
4435
4436 fallback = false;
4437 fallbackKeyCode = AKEYCODE_UNKNOWN;
4438 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004439 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004440 }
4441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004442
4443#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004444 {
4445 std::string msg;
4446 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4447 connection->inputState.getFallbackKeys();
4448 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004449 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004451 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004452 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004453 }
4454#endif
4455
4456 if (fallback) {
4457 // Restart the dispatch cycle using the fallback key.
4458 keyEntry->eventTime = event.getEventTime();
4459 keyEntry->deviceId = event.getDeviceId();
4460 keyEntry->source = event.getSource();
4461 keyEntry->displayId = event.getDisplayId();
4462 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4463 keyEntry->keyCode = fallbackKeyCode;
4464 keyEntry->scanCode = event.getScanCode();
4465 keyEntry->metaState = event.getMetaState();
4466 keyEntry->repeatCount = event.getRepeatCount();
4467 keyEntry->downTime = event.getDownTime();
4468 keyEntry->syntheticRepeat = false;
4469
4470#if DEBUG_OUTBOUND_EVENT_DETAILS
4471 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004472 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4473 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004474#endif
4475 return true; // restart the event
4476 } else {
4477#if DEBUG_OUTBOUND_EVENT_DETAILS
4478 ALOGD("Unhandled key event: No fallback key.");
4479#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004480
4481 // Report the key as unhandled, since there is no fallback key.
4482 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483 }
4484 }
4485 return false;
4486}
4487
4488bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004489 DispatchEntry* dispatchEntry,
4490 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491 return false;
4492}
4493
4494void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4495 mLock.unlock();
4496
4497 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4498
4499 mLock.lock();
4500}
4501
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004502KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4503 KeyEvent event;
4504 event.initialize(entry.deviceId, entry.source, entry.displayId, entry.action, entry.flags,
4505 entry.keyCode, entry.scanCode, entry.metaState, entry.repeatCount,
4506 entry.downTime, entry.eventTime);
4507 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508}
4509
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004510void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004511 int32_t injectionResult,
4512 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513 // TODO Write some statistics about how long we spend waiting.
4514}
4515
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004516/**
4517 * Report the touch event latency to the statsd server.
4518 * Input events are reported for statistics if:
4519 * - This is a touchscreen event
4520 * - InputFilter is not enabled
4521 * - Event is not injected or synthesized
4522 *
4523 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4524 * from getting aggregated with the "old" data.
4525 */
4526void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4527 REQUIRES(mLock) {
4528 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4529 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4530 if (!reportForStatistics) {
4531 return;
4532 }
4533
4534 if (mTouchStatistics.shouldReport()) {
4535 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4536 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4537 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4538 mTouchStatistics.reset();
4539 }
4540 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4541 mTouchStatistics.addValue(latencyMicros);
4542}
4543
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544void InputDispatcher::traceInboundQueueLengthLocked() {
4545 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004546 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547 }
4548}
4549
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004550void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551 if (ATRACE_ENABLED()) {
4552 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004553 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004554 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555 }
4556}
4557
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004558void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559 if (ATRACE_ENABLED()) {
4560 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004561 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004562 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 }
4564}
4565
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004566void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004567 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004569 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570 dumpDispatchStateLocked(dump);
4571
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004572 if (!mLastANRState.empty()) {
4573 dump += "\nInput Dispatcher State at time of last ANR:\n";
4574 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575 }
4576}
4577
4578void InputDispatcher::monitor() {
4579 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004580 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004582 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583}
4584
Garfield Tane84e6f92019-08-29 17:28:41 -07004585} // namespace android::inputdispatcher