blob: 58a5b3c8d3a3edce5bca77296e69c344107e700e [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),
255 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
256 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800258 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259
Yi Kong9b14ac62018-07-17 13:48:38 -0700260 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261
262 policy->getDispatcherConfiguration(&mConfig);
263}
264
265InputDispatcher::~InputDispatcher() {
266 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800267 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268
269 resetKeyRepeatLocked();
270 releasePendingEventLocked();
271 drainInboundQueueLocked();
272 }
273
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700274 while (!mConnectionsByFd.empty()) {
275 sp<Connection> connection = mConnectionsByFd.begin()->second;
276 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800277 }
278}
279
280void InputDispatcher::dispatchOnce() {
281 nsecs_t nextWakeupTime = LONG_LONG_MAX;
282 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800283 std::scoped_lock _l(mLock);
284 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800285
286 // Run a dispatch loop if there are no pending commands.
287 // The dispatch loop might enqueue commands to run afterwards.
288 if (!haveCommandsLocked()) {
289 dispatchOnceInnerLocked(&nextWakeupTime);
290 }
291
292 // Run all pending commands if there are any.
293 // If any commands were run then force the next poll to wake up immediately.
294 if (runCommandsLockedInterruptible()) {
295 nextWakeupTime = LONG_LONG_MIN;
296 }
297 } // release lock
298
299 // Wait for callback or timeout or wake. (make sure we round up, not down)
300 nsecs_t currentTime = now();
301 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
302 mLooper->pollOnce(timeoutMillis);
303}
304
305void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
306 nsecs_t currentTime = now();
307
Jeff Browndc5992e2014-04-11 01:27:26 -0700308 // Reset the key repeat timer whenever normal dispatch is suspended while the
309 // device is in a non-interactive state. This is to ensure that we abort a key
310 // repeat if the device is just coming out of sleep.
311 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800312 resetKeyRepeatLocked();
313 }
314
315 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
316 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100317 if (DEBUG_FOCUS) {
318 ALOGD("Dispatch frozen. Waiting some more.");
319 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800320 return;
321 }
322
323 // Optimize latency of app switches.
324 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
325 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
326 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
327 if (mAppSwitchDueTime < *nextWakeupTime) {
328 *nextWakeupTime = mAppSwitchDueTime;
329 }
330
331 // Ready to start a new event.
332 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700333 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700334 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800335 if (isAppSwitchDue) {
336 // The inbound queue is empty so the app switch key we were waiting
337 // for will never arrive. Stop waiting for it.
338 resetPendingAppSwitchLocked(false);
339 isAppSwitchDue = false;
340 }
341
342 // Synthesize a key repeat if appropriate.
343 if (mKeyRepeatState.lastKeyEntry) {
344 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
345 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
346 } else {
347 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
348 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
349 }
350 }
351 }
352
353 // Nothing to do if there is no pending event.
354 if (!mPendingEvent) {
355 return;
356 }
357 } else {
358 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700359 mPendingEvent = mInboundQueue.front();
360 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800361 traceInboundQueueLengthLocked();
362 }
363
364 // Poke user activity for this event.
365 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700366 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800367 }
368
369 // Get ready to dispatch the event.
370 resetANRTimeoutsLocked();
371 }
372
373 // Now we have an event to dispatch.
374 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700375 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800376 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700377 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800378 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700379 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800380 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700381 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800382 }
383
384 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700385 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800386 }
387
388 switch (mPendingEvent->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700389 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
390 ConfigurationChangedEntry* typedEntry =
391 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
392 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700393 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700394 break;
395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800396
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700397 case EventEntry::TYPE_DEVICE_RESET: {
398 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
399 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700400 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700401 break;
402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700404 case EventEntry::TYPE_KEY: {
405 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
406 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700407 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700408 resetPendingAppSwitchLocked(true);
409 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700410 } else if (dropReason == DropReason::NOT_DROPPED) {
411 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700412 }
413 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700414 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700415 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700416 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700417 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
418 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700419 }
420 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
421 break;
422 }
423
424 case EventEntry::TYPE_MOTION: {
425 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700426 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
427 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800428 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700429 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700430 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700431 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700432 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
433 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700434 }
435 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
436 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700439 default:
440 ALOG_ASSERT(false);
441 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800442 }
443
444 if (done) {
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) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700461 case EventEntry::TYPE_KEY: {
462 // Optimize app switch latency.
463 // If the application takes too long to catch up then we drop all events preceding
464 // the app switch key.
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
483 case EventEntry::TYPE_MOTION: {
484 // Optimize case where the current application is unresponsive and the user
485 // decides to touch a window in a different application.
486 // If the application takes too long to catch up then we drop all events preceding
487 // the touch into the other window.
488 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
489 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
490 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
491 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
492 mInputTargetWaitApplicationToken != nullptr) {
493 int32_t displayId = motionEntry->displayId;
494 int32_t x =
495 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
496 int32_t y =
497 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
498 sp<InputWindowHandle> touchedWindowHandle =
499 findTouchedWindowAtLocked(displayId, x, y);
500 if (touchedWindowHandle != nullptr &&
501 touchedWindowHandle->getApplicationToken() !=
502 mInputTargetWaitApplicationToken) {
503 // User touched a different application than the one we are waiting on.
504 // Flag the event, and start pruning the input queue.
505 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 needWake = true;
507 }
508 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700509 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 }
512
513 return needWake;
514}
515
516void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
517 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700518 mRecentQueue.push_back(entry);
519 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
520 mRecentQueue.front()->release();
521 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 }
523}
524
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700525sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
526 int32_t y, bool addOutsideTargets,
527 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800529 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
530 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531 const InputWindowInfo* windowInfo = windowHandle->getInfo();
532 if (windowInfo->displayId == displayId) {
533 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534
535 if (windowInfo->visible) {
536 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700537 bool isTouchModal = (flags &
538 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
539 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800541 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700542 if (portalToDisplayId != ADISPLAY_ID_NONE &&
543 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800544 if (addPortalWindows) {
545 // For the monitoring channels of the display.
546 mTempTouchState.addPortalWindow(windowHandle);
547 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700548 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
549 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551 // Found window.
552 return windowHandle;
553 }
554 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800555
556 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700557 mTempTouchState.addOrUpdateWindow(windowHandle,
558 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
559 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800560 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 }
563 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700564 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565}
566
Garfield Tane84e6f92019-08-29 17:28:41 -0700567std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000568 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
569 std::vector<TouchedMonitor> touchedMonitors;
570
571 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
572 addGestureMonitors(monitors, touchedMonitors);
573 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
574 const InputWindowInfo* windowInfo = portalWindow->getInfo();
575 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700576 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
577 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000578 }
579 return touchedMonitors;
580}
581
582void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700583 std::vector<TouchedMonitor>& outTouchedMonitors,
584 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000585 if (monitors.empty()) {
586 return;
587 }
588 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
589 for (const Monitor& monitor : monitors) {
590 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
591 }
592}
593
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700594void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800595 const char* reason;
596 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700597 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700599 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700601 reason = "inbound event was dropped because the policy consumed it";
602 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700603 case DropReason::DISABLED:
604 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700605 ALOGI("Dropped event because input dispatch is disabled.");
606 }
607 reason = "inbound event was dropped because input dispatch is disabled";
608 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700609 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700610 ALOGI("Dropped event because of pending overdue app switch.");
611 reason = "inbound event was dropped because of pending overdue app switch";
612 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700613 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700614 ALOGI("Dropped event because the current application is not responding and the user "
615 "has started interacting with a different application.");
616 reason = "inbound event was dropped because the current application is not responding "
617 "and the user has started interacting with a different application";
618 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700619 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700620 ALOGI("Dropped event because it is stale.");
621 reason = "inbound event was dropped because it is stale";
622 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700623 case DropReason::NOT_DROPPED: {
624 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700625 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 }
628
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700629 switch (entry.type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700630 case EventEntry::TYPE_KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
632 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700633 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700635 case EventEntry::TYPE_MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700636 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
637 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700638 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
639 synthesizeCancelationEventsForAllConnectionsLocked(options);
640 } else {
641 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
642 synthesizeCancelationEventsForAllConnectionsLocked(options);
643 }
644 break;
645 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800646 }
647}
648
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800649static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700650 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
651 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652}
653
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700654bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
655 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
656 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
657 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658}
659
660bool InputDispatcher::isAppSwitchPendingLocked() {
661 return mAppSwitchDueTime != LONG_LONG_MAX;
662}
663
664void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
665 mAppSwitchDueTime = LONG_LONG_MAX;
666
667#if DEBUG_APP_SWITCH
668 if (handled) {
669 ALOGD("App switch has arrived.");
670 } else {
671 ALOGD("App switch was abandoned.");
672 }
673#endif
674}
675
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700676bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
677 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678}
679
680bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700681 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682}
683
684bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700685 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 return false;
687 }
688
689 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700690 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700691 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700693 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694
695 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700696 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 return true;
698}
699
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700700void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
701 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702}
703
704void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700705 while (!mInboundQueue.empty()) {
706 EventEntry* entry = mInboundQueue.front();
707 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 releaseInboundEventLocked(entry);
709 }
710 traceInboundQueueLengthLocked();
711}
712
713void InputDispatcher::releasePendingEventLocked() {
714 if (mPendingEvent) {
715 resetANRTimeoutsLocked();
716 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700717 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 }
719}
720
721void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
722 InjectionState* injectionState = entry->injectionState;
723 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
724#if DEBUG_DISPATCH_CYCLE
725 ALOGD("Injected inbound event was dropped.");
726#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800727 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728 }
729 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700730 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731 }
732 addRecentEventLocked(entry);
733 entry->release();
734}
735
736void InputDispatcher::resetKeyRepeatLocked() {
737 if (mKeyRepeatState.lastKeyEntry) {
738 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700739 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740 }
741}
742
Garfield Tane84e6f92019-08-29 17:28:41 -0700743KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
745
746 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700747 uint32_t policyFlags = entry->policyFlags &
748 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749 if (entry->refCount == 1) {
750 entry->recycle();
751 entry->eventTime = currentTime;
752 entry->policyFlags = policyFlags;
753 entry->repeatCount += 1;
754 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700755 KeyEntry* newEntry =
756 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId,
757 entry->source, entry->displayId, policyFlags, entry->action,
758 entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
759 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760
761 mKeyRepeatState.lastKeyEntry = newEntry;
762 entry->release();
763
764 entry = newEntry;
765 }
766 entry->syntheticRepeat = true;
767
768 // Increment reference count since we keep a reference to the event in
769 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
770 entry->refCount += 1;
771
772 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
773 return entry;
774}
775
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700776bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
777 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700779 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780#endif
781
782 // Reset key repeating in case a keyboard device was added or removed or something.
783 resetKeyRepeatLocked();
784
785 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700786 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
787 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700789 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790 return true;
791}
792
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700793bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700795 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700796 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797#endif
798
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700799 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800 options.deviceId = entry->deviceId;
801 synthesizeCancelationEventsForAllConnectionsLocked(options);
802 return true;
803}
804
805bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700806 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700808 if (!entry->dispatchInProgress) {
809 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
810 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
811 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
812 if (mKeyRepeatState.lastKeyEntry &&
813 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 // We have seen two identical key downs in a row which indicates that the device
815 // driver is automatically generating key repeats itself. We take note of the
816 // repeat here, but we disable our own next key repeat timer since it is clear that
817 // we will not need to synthesize key repeats ourselves.
818 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
819 resetKeyRepeatLocked();
820 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
821 } else {
822 // Not a repeat. Save key down state in case we do see a repeat later.
823 resetKeyRepeatLocked();
824 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
825 }
826 mKeyRepeatState.lastKeyEntry = entry;
827 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700828 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829 resetKeyRepeatLocked();
830 }
831
832 if (entry->repeatCount == 1) {
833 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
834 } else {
835 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
836 }
837
838 entry->dispatchInProgress = true;
839
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700840 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 }
842
843 // Handle case where the policy asked us to try again later last time.
844 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
845 if (currentTime < entry->interceptKeyWakeupTime) {
846 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
847 *nextWakeupTime = entry->interceptKeyWakeupTime;
848 }
849 return false; // wait until next wakeup
850 }
851 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
852 entry->interceptKeyWakeupTime = 0;
853 }
854
855 // Give the policy a chance to intercept the key.
856 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
857 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700858 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -0700859 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800860 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700861 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +0800862 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 }
865 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700866 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 entry->refCount += 1;
868 return false; // wait for the command to run
869 } else {
870 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
871 }
872 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700873 if (*dropReason == DropReason::NOT_DROPPED) {
874 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 }
876 }
877
878 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700879 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700880 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700881 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700882 : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800883 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 return true;
885 }
886
887 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800888 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700889 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700890 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
892 return false;
893 }
894
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800895 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
897 return true;
898 }
899
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800900 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700901 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902
903 // Dispatch the key.
904 dispatchEventLocked(currentTime, entry, inputTargets);
905 return true;
906}
907
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700908void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100910 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700911 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
912 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700913 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
914 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
915 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916#endif
917}
918
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700919bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
920 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000921 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700923 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 entry->dispatchInProgress = true;
925
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700926 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 }
928
929 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700930 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700931 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700932 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700933 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934 return true;
935 }
936
937 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
938
939 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800940 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941
942 bool conflictingPointerActions = false;
943 int32_t injectionResult;
944 if (isPointerEvent) {
945 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700946 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700947 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700948 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 } else {
950 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700951 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700952 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953 }
954 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
955 return false;
956 }
957
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800958 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100960 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700961 CancelationOptions::Mode mode(isPointerEvent
962 ? CancelationOptions::CANCEL_POINTER_EVENTS
963 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100964 CancelationOptions options(mode, "input event injection failed");
965 synthesizeCancelationEventsForMonitorsLocked(options);
966 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 return true;
968 }
969
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800970 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700971 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800973 if (isPointerEvent) {
974 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
975 if (stateIndex >= 0) {
976 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800977 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800978 // The event has gone through these portal windows, so we add monitoring targets of
979 // the corresponding displays as well.
980 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800981 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +0000982 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700983 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800984 }
985 }
986 }
987 }
988
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 // Dispatch the motion.
990 if (conflictingPointerActions) {
991 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700992 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 synthesizeCancelationEventsForAllConnectionsLocked(options);
994 }
995 dispatchEventLocked(currentTime, entry, inputTargets);
996 return true;
997}
998
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700999void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001001 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001002 ", policyFlags=0x%x, "
1003 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1004 "metaState=0x%x, buttonState=0x%x,"
1005 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001006 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1007 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1008 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001010 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001012 "x=%f, y=%f, pressure=%f, size=%f, "
1013 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1014 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001015 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1016 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1017 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1018 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1019 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1020 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1021 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1022 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1023 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1024 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 }
1026#endif
1027}
1028
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001029void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1030 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001031 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032#if DEBUG_DISPATCH_CYCLE
1033 ALOGD("dispatchEventToCurrentInputTargets");
1034#endif
1035
1036 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1037
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001038 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001040 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001041 sp<Connection> connection =
1042 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001043 if (connection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1045 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001046 if (DEBUG_FOCUS) {
1047 ALOGD("Dropping event delivery to target with channel '%s' because it "
1048 "is no longer registered with the input dispatcher.",
1049 inputTarget.inputChannel->getName().c_str());
1050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 }
1052 }
1053}
1054
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001055int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001056 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001058 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001059 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001061 if (DEBUG_FOCUS) {
1062 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1065 mInputTargetWaitStartTime = currentTime;
1066 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1067 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001068 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069 }
1070 } else {
1071 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001072 if (DEBUG_FOCUS) {
1073 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
1074 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001077 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001079 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 timeout =
1081 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 } else {
1083 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1084 }
1085
1086 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1087 mInputTargetWaitStartTime = currentTime;
1088 mInputTargetWaitTimeoutTime = currentTime + timeout;
1089 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001090 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091
Yi Kong9b14ac62018-07-17 13:48:38 -07001092 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001093 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 }
Robert Carr740167f2018-10-11 19:03:41 -07001095 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1096 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 }
1098 }
1099 }
1100
1101 if (mInputTargetWaitTimeoutExpired) {
1102 return INPUT_EVENT_INJECTION_TIMED_OUT;
1103 }
1104
1105 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001106 onANRLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001107 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108
1109 // Force poll loop to wake up immediately on next iteration once we get the
1110 // ANR response back from the policy.
1111 *nextWakeupTime = LONG_LONG_MIN;
1112 return INPUT_EVENT_INJECTION_PENDING;
1113 } else {
1114 // Force poll loop to wake up when timeout is due.
1115 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1116 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1117 }
1118 return INPUT_EVENT_INJECTION_PENDING;
1119 }
1120}
1121
Robert Carr803535b2018-08-02 16:38:15 -07001122void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1123 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1124 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1125 state.removeWindowByToken(token);
1126 }
1127}
1128
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001130 nsecs_t newTimeout, const sp<IBinder>& inputConnectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 if (newTimeout > 0) {
1132 // Extend the timeout.
1133 mInputTargetWaitTimeoutTime = now() + newTimeout;
1134 } else {
1135 // Give up.
1136 mInputTargetWaitTimeoutExpired = true;
1137
1138 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001139 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001140 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001141 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001143 if (connection->status == Connection::STATUS_NORMAL) {
1144 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1145 "application not responding");
1146 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
1148 }
1149 }
1150}
1151
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001152nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1154 return currentTime - mInputTargetWaitStartTime;
1155 }
1156 return 0;
1157}
1158
1159void InputDispatcher::resetANRTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001160 if (DEBUG_FOCUS) {
1161 ALOGD("Resetting ANR timeouts.");
1162 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163
1164 // Reset input target wait timeout.
1165 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001166 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167}
1168
Tiger Huang721e26f2018-07-24 22:26:19 +08001169/**
1170 * Get the display id that the given event should go to. If this event specifies a valid display id,
1171 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1172 * Focused display is the display that the user most recently interacted with.
1173 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001174int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001175 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001176 switch (entry.type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001177 case EventEntry::TYPE_KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001178 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1179 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001180 break;
1181 }
1182 case EventEntry::TYPE_MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001183 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1184 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001185 break;
1186 }
1187 default: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001188 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry.type);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001189 return ADISPLAY_ID_NONE;
1190 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001191 }
1192 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1193}
1194
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001196 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001197 std::vector<InputTarget>& inputTargets,
1198 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001200 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201
Tiger Huang721e26f2018-07-24 22:26:19 +08001202 int32_t displayId = getTargetDisplayId(entry);
1203 sp<InputWindowHandle> focusedWindowHandle =
1204 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1205 sp<InputApplicationHandle> focusedApplicationHandle =
1206 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1207
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 // If there is no currently focused window and no focused application
1209 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001210 if (focusedWindowHandle == nullptr) {
1211 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001212 injectionResult =
1213 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1214 nullptr, nextWakeupTime,
1215 "Waiting because no window has focus but there is "
1216 "a focused application that may eventually add a "
1217 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 goto Unresponsive;
1219 }
1220
Arthur Hung3b413f22018-10-26 18:05:34 +08001221 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001222 "%" PRId32 ".",
1223 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1225 goto Failed;
1226 }
1227
1228 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001229 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1231 goto Failed;
1232 }
1233
Jeff Brownffb49772014-10-10 19:01:34 -07001234 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001235 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001236 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237 injectionResult =
1238 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1239 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 goto Unresponsive;
1241 }
1242
1243 // Success! Output targets.
1244 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001245 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001246 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1247 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248
1249 // Done.
1250Failed:
1251Unresponsive:
1252 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001253 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001254 if (DEBUG_FOCUS) {
1255 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1256 "timeSpentWaitingForApplication=%0.1fms",
1257 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 return injectionResult;
1260}
1261
1262int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001263 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001264 std::vector<InputTarget>& inputTargets,
1265 nsecs_t* nextWakeupTime,
1266 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001267 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 enum InjectionPermission {
1269 INJECTION_PERMISSION_UNKNOWN,
1270 INJECTION_PERMISSION_GRANTED,
1271 INJECTION_PERMISSION_DENIED
1272 };
1273
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 // For security reasons, we defer updating the touch state until we are sure that
1275 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001276 int32_t displayId = entry.displayId;
1277 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1279
1280 // Update the touch state as needed based on the properties of the touch event.
1281 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1282 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1283 sp<InputWindowHandle> newHoverWindowHandle;
1284
Jeff Brownf086ddb2014-02-11 14:28:48 -08001285 // Copy current touch state into mTempTouchState.
1286 // This state is always reset at the end of this function, so if we don't find state
1287 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001288 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001289 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1290 if (oldStateIndex >= 0) {
1291 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1292 mTempTouchState.copyFrom(*oldState);
1293 }
1294
1295 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001296 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001297 (mTempTouchState.deviceId != entry.deviceId || mTempTouchState.source != entry.source ||
1298 mTempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001299 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1300 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1301 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1302 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1303 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001304 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305 bool wrongDevice = false;
1306 if (newGesture) {
1307 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001308 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001309 if (DEBUG_FOCUS) {
1310 ALOGD("Dropping event because a pointer for a different device is already down "
1311 "in display %" PRId32,
1312 displayId);
1313 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001314 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1316 switchedDevice = false;
1317 wrongDevice = true;
1318 goto Failed;
1319 }
1320 mTempTouchState.reset();
1321 mTempTouchState.down = down;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001322 mTempTouchState.deviceId = entry.deviceId;
1323 mTempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 mTempTouchState.displayId = displayId;
1325 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001326 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001327 if (DEBUG_FOCUS) {
1328 ALOGI("Dropping move event because a pointer for a different device is already active "
1329 "in display %" PRId32,
1330 displayId);
1331 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001332 // TODO: test multiple simultaneous input streams.
1333 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1334 switchedDevice = false;
1335 wrongDevice = true;
1336 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 }
1338
1339 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1340 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1341
Garfield Tan00f511d2019-06-12 16:55:40 -07001342 int32_t x;
1343 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001345 // Always dispatch mouse events to cursor position.
1346 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001347 x = int32_t(entry.xCursorPosition);
1348 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001349 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001350 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1351 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001352 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001353 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001354 sp<InputWindowHandle> newTouchedWindowHandle =
1355 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1356 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001357
1358 std::vector<TouchedMonitor> newGestureMonitors = isDown
1359 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1360 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001363 if (newTouchedWindowHandle != nullptr &&
1364 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001365 // New window supports splitting, but we should never split mouse events.
1366 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367 } else if (isSplit) {
1368 // New window does not support splitting but we have already split events.
1369 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001370 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371 }
1372
1373 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001374 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 // Try to assign the pointer to the first foreground window we find, if there is one.
1376 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001377 }
1378
1379 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1380 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001381 "(%d, %d) in display %" PRId32 ".",
1382 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001383 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1384 goto Failed;
1385 }
1386
1387 if (newTouchedWindowHandle != nullptr) {
1388 // Set target flags.
1389 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1390 if (isSplit) {
1391 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001393 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1394 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1395 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1396 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1397 }
1398
1399 // Update hover state.
1400 if (isHoverAction) {
1401 newHoverWindowHandle = newTouchedWindowHandle;
1402 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1403 newHoverWindowHandle = mLastHoverWindowHandle;
1404 }
1405
1406 // Update the temporary touch state.
1407 BitSet32 pointerIds;
1408 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001409 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001410 pointerIds.markBit(pointerId);
1411 }
1412 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413 }
1414
Michael Wright3dd60e22019-03-27 22:06:44 +00001415 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416 } else {
1417 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1418
1419 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001420 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001421 if (DEBUG_FOCUS) {
1422 ALOGD("Dropping event because the pointer is not down or we previously "
1423 "dropped the pointer down event in display %" PRId32,
1424 displayId);
1425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1427 goto Failed;
1428 }
1429
1430 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001431 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001432 mTempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001433 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1434 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435
1436 sp<InputWindowHandle> oldTouchedWindowHandle =
1437 mTempTouchState.getFirstForegroundWindowHandle();
1438 sp<InputWindowHandle> newTouchedWindowHandle =
1439 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001440 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1441 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001442 if (DEBUG_FOCUS) {
1443 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1444 oldTouchedWindowHandle->getName().c_str(),
1445 newTouchedWindowHandle->getName().c_str(), displayId);
1446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 // Make a slippery exit from the old window.
1448 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001449 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1450 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451
1452 // Make a slippery entrance into the new window.
1453 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1454 isSplit = true;
1455 }
1456
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001457 int32_t targetFlags =
1458 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 if (isSplit) {
1460 targetFlags |= InputTarget::FLAG_SPLIT;
1461 }
1462 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1463 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1464 }
1465
1466 BitSet32 pointerIds;
1467 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001468 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 }
1470 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1471 }
1472 }
1473 }
1474
1475 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1476 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001477 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478#if DEBUG_HOVER
1479 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001480 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481#endif
1482 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001483 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1484 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 }
1486
1487 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001488 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489#if DEBUG_HOVER
1490 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001491 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492#endif
1493 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001494 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1495 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 }
1497 }
1498
1499 // Check permission to inject into all touched foreground windows and ensure there
1500 // is at least one touched foreground window.
1501 {
1502 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001503 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1505 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001506 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1508 injectionPermission = INJECTION_PERMISSION_DENIED;
1509 goto Failed;
1510 }
1511 }
1512 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001513 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1514 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001515 if (DEBUG_FOCUS) {
1516 ALOGD("Dropping event because there is no touched foreground window in display "
1517 "%" PRId32 " or gesture monitor to receive it.",
1518 displayId);
1519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1521 goto Failed;
1522 }
1523
1524 // Permission granted to injection into all touched foreground windows.
1525 injectionPermission = INJECTION_PERMISSION_GRANTED;
1526 }
1527
1528 // Check whether windows listening for outside touches are owned by the same UID. If it is
1529 // set the policy flag that we will not reveal coordinate information to this window.
1530 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1531 sp<InputWindowHandle> foregroundWindowHandle =
1532 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001533 if (foregroundWindowHandle) {
1534 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1535 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1536 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1537 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1538 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1539 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001540 InputTarget::FLAG_ZERO_COORDS,
1541 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 }
1544 }
1545 }
1546 }
1547
1548 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001549 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001551 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001552 std::string reason =
1553 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1554 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001555 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001556 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1557 touchedWindow.windowHandle,
1558 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 goto Unresponsive;
1560 }
1561 }
1562 }
1563
1564 // If this is the first pointer going down and the touched window has a wallpaper
1565 // then also add the touched wallpaper windows so they are locked in for the duration
1566 // of the touch gesture.
1567 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1568 // engine only supports touch events. We would need to add a mechanism similar
1569 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1570 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1571 sp<InputWindowHandle> foregroundWindowHandle =
1572 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001573 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001574 const std::vector<sp<InputWindowHandle>> windowHandles =
1575 getWindowHandlesLocked(displayId);
1576 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001578 if (info->displayId == displayId &&
1579 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1580 mTempTouchState
1581 .addOrUpdateWindow(windowHandle,
1582 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1583 InputTarget::
1584 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1585 InputTarget::FLAG_DISPATCH_AS_IS,
1586 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 }
1588 }
1589 }
1590 }
1591
1592 // Success! Output targets.
1593 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1594
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001595 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001597 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 }
1599
Michael Wright3dd60e22019-03-27 22:06:44 +00001600 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1601 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001602 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001603 }
1604
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 // Drop the outside or hover touch windows since we will not care about them
1606 // in the next iteration.
1607 mTempTouchState.filterNonAsIsTouchWindows();
1608
1609Failed:
1610 // Check injection permission once and for all.
1611 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001612 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 injectionPermission = INJECTION_PERMISSION_GRANTED;
1614 } else {
1615 injectionPermission = INJECTION_PERMISSION_DENIED;
1616 }
1617 }
1618
1619 // Update final pieces of touch state if the injector had permission.
1620 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1621 if (!wrongDevice) {
1622 if (switchedDevice) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001623 if (DEBUG_FOCUS) {
1624 ALOGD("Conflicting pointer actions: Switched to a different device.");
1625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 *outConflictingPointerActions = true;
1627 }
1628
1629 if (isHoverAction) {
1630 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001631 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001632 if (DEBUG_FOCUS) {
1633 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1634 "down.");
1635 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 *outConflictingPointerActions = true;
1637 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001638 mTempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001639 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1640 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001641 mTempTouchState.deviceId = entry.deviceId;
1642 mTempTouchState.source = entry.source;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001643 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001645 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1646 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001648 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1650 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001651 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001652 if (DEBUG_FOCUS) {
1653 ALOGD("Conflicting pointer actions: Down received while already down.");
1654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 *outConflictingPointerActions = true;
1656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1658 // One pointer went up.
1659 if (isSplit) {
1660 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001661 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001663 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001664 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1666 touchedWindow.pointerIds.clearBit(pointerId);
1667 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001668 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 continue;
1670 }
1671 }
1672 i += 1;
1673 }
1674 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001675 }
1676
1677 // Save changes unless the action was scroll in which case the temporary touch
1678 // state was only valid for this one action.
1679 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1680 if (mTempTouchState.displayId >= 0) {
1681 if (oldStateIndex >= 0) {
1682 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1683 } else {
1684 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1685 }
1686 } else if (oldStateIndex >= 0) {
1687 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 }
1690
1691 // Update hover state.
1692 mLastHoverWindowHandle = newHoverWindowHandle;
1693 }
1694 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001695 if (DEBUG_FOCUS) {
1696 ALOGD("Not updating touch focus because injection was denied.");
1697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 }
1699
1700Unresponsive:
1701 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1702 mTempTouchState.reset();
1703
1704 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001705 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001706 if (DEBUG_FOCUS) {
1707 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1708 "timeSpentWaitingForApplication=%0.1fms",
1709 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 return injectionResult;
1712}
1713
1714void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001715 int32_t targetFlags, BitSet32 pointerIds,
1716 std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001717 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1718 if (inputChannel == nullptr) {
1719 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1720 return;
1721 }
1722
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001724 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001725 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 target.flags = targetFlags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001727 target.xOffset = -windowInfo->frameLeft;
1728 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001729 target.globalScaleFactor = windowInfo->globalScaleFactor;
1730 target.windowXScale = windowInfo->windowXScale;
1731 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001733 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734}
1735
Michael Wright3dd60e22019-03-27 22:06:44 +00001736void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001737 int32_t displayId, float xOffset,
1738 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001739 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1740 mGlobalMonitorsByDisplay.find(displayId);
1741
1742 if (it != mGlobalMonitorsByDisplay.end()) {
1743 const std::vector<Monitor>& monitors = it->second;
1744 for (const Monitor& monitor : monitors) {
1745 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001746 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 }
1748}
1749
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001750void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1751 float yOffset,
1752 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001753 InputTarget target;
1754 target.inputChannel = monitor.inputChannel;
1755 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1756 target.xOffset = xOffset;
1757 target.yOffset = yOffset;
1758 target.pointerIds.clear();
1759 target.globalScaleFactor = 1.0f;
1760 inputTargets.push_back(target);
1761}
1762
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001764 const InjectionState* injectionState) {
1765 if (injectionState &&
1766 (windowHandle == nullptr ||
1767 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1768 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001769 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001771 "owned by uid %d",
1772 injectionState->injectorPid, injectionState->injectorUid,
1773 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774 } else {
1775 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001776 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 }
1778 return false;
1779 }
1780 return true;
1781}
1782
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001783bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1784 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001786 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1787 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 if (otherHandle == windowHandle) {
1789 break;
1790 }
1791
1792 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001793 if (otherInfo->displayId == displayId && otherInfo->visible &&
1794 !otherInfo->isTrustedOverlay() && otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 return true;
1796 }
1797 }
1798 return false;
1799}
1800
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001801bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1802 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001803 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001804 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001805 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001806 if (otherHandle == windowHandle) {
1807 break;
1808 }
1809
1810 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001811 if (otherInfo->displayId == displayId && otherInfo->visible &&
1812 !otherInfo->isTrustedOverlay() && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001813 return true;
1814 }
1815 }
1816 return false;
1817}
1818
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001819std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
1820 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001821 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07001822 // If the window is paused then keep waiting.
1823 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001824 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001825 }
1826
1827 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001828 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001829 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001830 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001831 "registered with the input dispatcher. The window may be in the "
1832 "process of being removed.",
1833 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001834 }
1835
1836 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07001837 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001838 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001839 "The window may be in the process of being removed.",
1840 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07001841 }
1842
1843 // If the connection is backed up then keep waiting.
1844 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001845 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001846 "Outbound queue length: %zu. Wait queue length: %zu.",
1847 targetType, connection->outboundQueue.size(),
1848 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07001849 }
1850
1851 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001852 if (eventEntry.type == EventEntry::TYPE_KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07001853 // If the event is a key event, then we must wait for all previous events to
1854 // complete before delivering it because previous events may have the
1855 // side-effect of transferring focus to a different window and we want to
1856 // ensure that the following keys are sent to the new window.
1857 //
1858 // Suppose the user touches a button in a window then immediately presses "A".
1859 // If the button causes a pop-up window to appear then we want to ensure that
1860 // the "A" key is delivered to the new pop-up window. This is because users
1861 // often anticipate pending UI changes when typing on a keyboard.
1862 // To obtain this behavior, we must serialize key events with respect to all
1863 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001864 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001865 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001866 "finished processing all of the input events that were previously "
1867 "delivered to it. Outbound queue length: %zu. Wait queue length: "
1868 "%zu.",
1869 targetType, connection->outboundQueue.size(),
1870 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 }
Jeff Brownffb49772014-10-10 19:01:34 -07001872 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 // Touch events can always be sent to a window immediately because the user intended
1874 // to touch whatever was visible at the time. Even if focus changes or a new
1875 // window appears moments later, the touch event was meant to be delivered to
1876 // whatever window happened to be on screen at the time.
1877 //
1878 // Generic motion events, such as trackball or joystick events are a little trickier.
1879 // Like key events, generic motion events are delivered to the focused window.
1880 // Unlike key events, generic motion events don't tend to transfer focus to other
1881 // windows and it is not important for them to be serialized. So we prefer to deliver
1882 // generic motion events as soon as possible to improve efficiency and reduce lag
1883 // through batching.
1884 //
1885 // The one case where we pause input event delivery is when the wait queue is piling
1886 // up with lots of events because the application is not responding.
1887 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001888 if (!connection->waitQueue.empty() &&
1889 currentTime >=
1890 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001891 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001892 "finished processing certain input events that were delivered to "
1893 "it over "
1894 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
1895 "%0.1fms.",
1896 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1897 connection->waitQueue.size(),
1898 (currentTime - connection->waitQueue.front()->deliveryTime) *
1899 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 }
1901 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001902 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903}
1904
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001905std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 const sp<InputApplicationHandle>& applicationHandle,
1907 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001908 if (applicationHandle != nullptr) {
1909 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001910 std::string label(applicationHandle->getName());
1911 label += " - ";
1912 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913 return label;
1914 } else {
1915 return applicationHandle->getName();
1916 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001917 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 return windowHandle->getName();
1919 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001920 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 }
1922}
1923
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001924void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001925 int32_t displayId = getTargetDisplayId(eventEntry);
1926 sp<InputWindowHandle> focusedWindowHandle =
1927 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1928 if (focusedWindowHandle != nullptr) {
1929 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1931#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001932 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933#endif
1934 return;
1935 }
1936 }
1937
1938 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001939 switch (eventEntry.type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001940 case EventEntry::TYPE_MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001941 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
1942 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001943 return;
1944 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001946 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001947 eventType = USER_ACTIVITY_EVENT_TOUCH;
1948 }
1949 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001951 case EventEntry::TYPE_KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001952 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
1953 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001954 return;
1955 }
1956 eventType = USER_ACTIVITY_EVENT_BUTTON;
1957 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 }
1960
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001961 std::unique_ptr<CommandEntry> commandEntry =
1962 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001963 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001965 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966}
1967
1968void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001969 const sp<Connection>& connection,
1970 EventEntry* eventEntry,
1971 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001972 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001973 std::string message =
1974 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
1975 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00001976 ATRACE_NAME(message.c_str());
1977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978#if DEBUG_DISPATCH_CYCLE
1979 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001980 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1981 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
1982 connection->getInputChannelName().c_str(), inputTarget->flags, inputTarget->xOffset,
1983 inputTarget->yOffset, inputTarget->globalScaleFactor, inputTarget->windowXScale,
1984 inputTarget->windowYScale, inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985#endif
1986
1987 // Skip this event if the connection status is not normal.
1988 // We don't want to enqueue additional outbound events if the connection is broken.
1989 if (connection->status != Connection::STATUS_NORMAL) {
1990#if DEBUG_DISPATCH_CYCLE
1991 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001992 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993#endif
1994 return;
1995 }
1996
1997 // Split a motion event if needed.
1998 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1999 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
2000
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002001 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
2002 if (inputTarget->pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002003 MotionEntry* splitMotionEntry =
2004 splitMotionEvent(originalMotionEntry, inputTarget->pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 if (!splitMotionEntry) {
2006 return; // split event was dropped
2007 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002008 if (DEBUG_FOCUS) {
2009 ALOGD("channel '%s' ~ Split motion event.",
2010 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002011 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002012 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002013 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 splitMotionEntry->release();
2015 return;
2016 }
2017 }
2018
2019 // Not splitting. Enqueue dispatch entries for the event as is.
2020 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2021}
2022
2023void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002024 const sp<Connection>& connection,
2025 EventEntry* eventEntry,
2026 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002027 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002028 std::string message =
2029 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32
2030 ")",
2031 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002032 ATRACE_NAME(message.c_str());
2033 }
2034
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002035 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036
2037 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002038 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002039 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002040 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002041 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002042 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002043 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002044 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002045 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002046 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002047 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002048 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002049 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050
2051 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002052 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 startDispatchCycleLocked(currentTime, connection);
2054 }
2055}
2056
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002057void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2058 EventEntry* eventEntry,
2059 const InputTarget* inputTarget,
2060 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002061 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002062 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2063 connection->getInputChannelName().c_str(),
2064 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002065 ATRACE_NAME(message.c_str());
2066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 int32_t inputTargetFlags = inputTarget->flags;
2068 if (!(inputTargetFlags & dispatchMode)) {
2069 return;
2070 }
2071 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2072
2073 // This is a new event.
2074 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002075 DispatchEntry* dispatchEntry =
2076 new DispatchEntry(eventEntry, // increments ref
2077 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
2078 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2079 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080
2081 // Apply target flags and update the connection's input state.
2082 switch (eventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002083 case EventEntry::TYPE_KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002084 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
2085 dispatchEntry->resolvedAction = keyEntry.action;
2086 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002088 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2089 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002091 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2092 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002094 delete dispatchEntry;
2095 return; // skip the inconsistent event
2096 }
2097 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002100 case EventEntry::TYPE_MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002101 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002102 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2103 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2104 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2105 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2106 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2107 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2108 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2109 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2110 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2111 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2112 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002113 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002114 }
2115 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002116 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2117 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002119 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2120 "event",
2121 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002123 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002126 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002127 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2128 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2129 }
2130 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2131 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2132 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002134 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2135 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002137 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2138 "event",
2139 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002141 delete dispatchEntry;
2142 return; // skip the inconsistent event
2143 }
2144
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002145 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002146 inputTarget->inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002147
2148 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 }
2151
2152 // Remember that we are waiting for this dispatch to complete.
2153 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002154 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 }
2156
2157 // Enqueue the dispatch entry.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002158 connection->outboundQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002159 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002160}
2161
chaviwfd6d3512019-03-25 13:23:49 -07002162void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002163 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002164 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002165 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2166 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002167 return;
2168 }
2169
2170 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2171 if (inputWindowHandle == nullptr) {
2172 return;
2173 }
2174
chaviw8c9cf542019-03-25 13:02:48 -07002175 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002176 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002177
2178 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2179
2180 if (!hasFocusChanged) {
2181 return;
2182 }
2183
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002184 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2185 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002186 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002187 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188}
2189
2190void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002191 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002192 if (ATRACE_ENABLED()) {
2193 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002194 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002195 ATRACE_NAME(message.c_str());
2196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002198 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199#endif
2200
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002201 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2202 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203 dispatchEntry->deliveryTime = currentTime;
2204
2205 // Publish the event.
2206 status_t status;
2207 EventEntry* eventEntry = dispatchEntry->eventEntry;
2208 switch (eventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002209 case EventEntry::TYPE_KEY: {
2210 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002212 // Publish the key event.
2213 status = connection->inputPublisher
2214 .publishKeyEvent(dispatchEntry->seq, keyEntry->deviceId,
2215 keyEntry->source, keyEntry->displayId,
2216 dispatchEntry->resolvedAction,
2217 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2218 keyEntry->scanCode, keyEntry->metaState,
2219 keyEntry->repeatCount, keyEntry->downTime,
2220 keyEntry->eventTime);
2221 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 }
2223
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002224 case EventEntry::TYPE_MOTION: {
2225 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002227 PointerCoords scaledCoords[MAX_POINTERS];
2228 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2229
2230 // Set the X and Y offset depending on the input source.
2231 float xOffset, yOffset;
2232 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2233 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2234 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2235 float wxs = dispatchEntry->windowXScale;
2236 float wys = dispatchEntry->windowYScale;
2237 xOffset = dispatchEntry->xOffset * wxs;
2238 yOffset = dispatchEntry->yOffset * wys;
2239 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
2240 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2241 scaledCoords[i] = motionEntry->pointerCoords[i];
2242 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
2243 }
2244 usingCoords = scaledCoords;
2245 }
2246 } else {
2247 xOffset = 0.0f;
2248 yOffset = 0.0f;
2249
2250 // We don't want the dispatch target to know.
2251 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2252 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2253 scaledCoords[i].clear();
2254 }
2255 usingCoords = scaledCoords;
2256 }
2257 }
2258
2259 // Publish the motion event.
2260 status = connection->inputPublisher
2261 .publishMotionEvent(dispatchEntry->seq, motionEntry->deviceId,
2262 motionEntry->source, motionEntry->displayId,
2263 dispatchEntry->resolvedAction,
2264 motionEntry->actionButton,
2265 dispatchEntry->resolvedFlags,
2266 motionEntry->edgeFlags, motionEntry->metaState,
2267 motionEntry->buttonState,
2268 motionEntry->classification, xOffset, yOffset,
2269 motionEntry->xPrecision,
2270 motionEntry->yPrecision,
2271 motionEntry->xCursorPosition,
2272 motionEntry->yCursorPosition,
2273 motionEntry->downTime, motionEntry->eventTime,
2274 motionEntry->pointerCount,
2275 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002276 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002277 break;
2278 }
2279
2280 default:
2281 ALOG_ASSERT(false);
2282 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 }
2284
2285 // Check the result.
2286 if (status) {
2287 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002288 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002290 "This is unexpected because the wait queue is empty, so the pipe "
2291 "should be empty and we shouldn't have any problems writing an "
2292 "event to it, status=%d",
2293 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2295 } else {
2296 // Pipe is full and we are waiting for the app to finish process some events
2297 // before sending more events to it.
2298#if DEBUG_DISPATCH_CYCLE
2299 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002300 "waiting for the application to catch up",
2301 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302#endif
2303 connection->inputPublisherBlocked = true;
2304 }
2305 } else {
2306 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002307 "status=%d",
2308 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2310 }
2311 return;
2312 }
2313
2314 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002315 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2316 connection->outboundQueue.end(),
2317 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002318 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002319 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002320 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 }
2322}
2323
2324void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002325 const sp<Connection>& connection, uint32_t seq,
2326 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327#if DEBUG_DISPATCH_CYCLE
2328 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002329 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330#endif
2331
2332 connection->inputPublisherBlocked = false;
2333
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002334 if (connection->status == Connection::STATUS_BROKEN ||
2335 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 return;
2337 }
2338
2339 // Notify other system components and prepare to start the next dispatch cycle.
2340 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2341}
2342
2343void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002344 const sp<Connection>& connection,
2345 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346#if DEBUG_DISPATCH_CYCLE
2347 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002348 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349#endif
2350
2351 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002352 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002353 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002354 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002355 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356
2357 // The connection appears to be unrecoverably broken.
2358 // Ignore already broken or zombie connections.
2359 if (connection->status == Connection::STATUS_NORMAL) {
2360 connection->status = Connection::STATUS_BROKEN;
2361
2362 if (notify) {
2363 // Notify other system components.
2364 onDispatchCycleBrokenLocked(currentTime, connection);
2365 }
2366 }
2367}
2368
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002369void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2370 while (!queue.empty()) {
2371 DispatchEntry* dispatchEntry = queue.front();
2372 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002373 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 }
2375}
2376
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002377void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002379 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 }
2381 delete dispatchEntry;
2382}
2383
2384int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2385 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2386
2387 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002388 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002390 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002392 "fd=%d, events=0x%x",
2393 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 return 0; // remove the callback
2395 }
2396
2397 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002398 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2400 if (!(events & ALOOPER_EVENT_INPUT)) {
2401 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002402 "events=0x%x",
2403 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 return 1;
2405 }
2406
2407 nsecs_t currentTime = now();
2408 bool gotOne = false;
2409 status_t status;
2410 for (;;) {
2411 uint32_t seq;
2412 bool handled;
2413 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2414 if (status) {
2415 break;
2416 }
2417 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2418 gotOne = true;
2419 }
2420 if (gotOne) {
2421 d->runCommandsLockedInterruptible();
2422 if (status == WOULD_BLOCK) {
2423 return 1;
2424 }
2425 }
2426
2427 notify = status != DEAD_OBJECT || !connection->monitor;
2428 if (notify) {
2429 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002430 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431 }
2432 } else {
2433 // Monitor channels are never explicitly unregistered.
2434 // We do it automatically when the remote endpoint is closed so don't warn
2435 // about them.
2436 notify = !connection->monitor;
2437 if (notify) {
2438 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002439 "events=0x%x",
2440 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 }
2442 }
2443
2444 // Unregister the channel.
2445 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2446 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002447 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448}
2449
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002450void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002452 for (const auto& pair : mConnectionsByFd) {
2453 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454 }
2455}
2456
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002457void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002458 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002459 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2460 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2461}
2462
2463void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2464 const CancelationOptions& options,
2465 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2466 for (const auto& it : monitorsByDisplay) {
2467 const std::vector<Monitor>& monitors = it.second;
2468 for (const Monitor& monitor : monitors) {
2469 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002470 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002471 }
2472}
2473
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2475 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002476 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002477 if (connection == nullptr) {
2478 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002480
2481 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482}
2483
2484void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2485 const sp<Connection>& connection, const CancelationOptions& options) {
2486 if (connection->status == Connection::STATUS_BROKEN) {
2487 return;
2488 }
2489
2490 nsecs_t currentTime = now();
2491
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002492 std::vector<EventEntry*> cancelationEvents =
2493 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002495 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002497 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002498 "with reality: %s, mode=%d.",
2499 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2500 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501#endif
2502 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002503 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 switch (cancelationEventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002505 case EventEntry::TYPE_KEY:
2506 logOutboundKeyDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002507 static_cast<const KeyEntry&>(*cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002508 break;
2509 case EventEntry::TYPE_MOTION:
2510 logOutboundMotionDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002511 static_cast<const MotionEntry&>(
2512 *cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002513 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514 }
2515
2516 InputTarget target;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002517 sp<InputWindowHandle> windowHandle =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002518 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002519 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2521 target.xOffset = -windowInfo->frameLeft;
2522 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002523 target.globalScaleFactor = windowInfo->globalScaleFactor;
2524 target.windowXScale = windowInfo->windowXScale;
2525 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 } else {
2527 target.xOffset = 0;
2528 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002529 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530 }
2531 target.inputChannel = connection->inputChannel;
2532 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2533
chaviw8c9cf542019-03-25 13:02:48 -07002534 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002535 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536
2537 cancelationEventEntry->release();
2538 }
2539
2540 startDispatchCycleLocked(currentTime, connection);
2541 }
2542}
2543
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002544MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002545 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 ALOG_ASSERT(pointerIds.value != 0);
2547
2548 uint32_t splitPointerIndexMap[MAX_POINTERS];
2549 PointerProperties splitPointerProperties[MAX_POINTERS];
2550 PointerCoords splitPointerCoords[MAX_POINTERS];
2551
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002552 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 uint32_t splitPointerCount = 0;
2554
2555 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002556 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002558 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 uint32_t pointerId = uint32_t(pointerProperties.id);
2560 if (pointerIds.hasBit(pointerId)) {
2561 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2562 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2563 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002564 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 splitPointerCount += 1;
2566 }
2567 }
2568
2569 if (splitPointerCount != pointerIds.count()) {
2570 // This is bad. We are missing some of the pointers that we expected to deliver.
2571 // Most likely this indicates that we received an ACTION_MOVE events that has
2572 // different pointer ids than we expected based on the previous ACTION_DOWN
2573 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2574 // in this way.
2575 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002576 "we expected there to be %d pointers. This probably means we received "
2577 "a broken sequence of pointer ids from the input device.",
2578 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002579 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 }
2581
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002582 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002584 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2585 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2587 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002588 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 uint32_t pointerId = uint32_t(pointerProperties.id);
2590 if (pointerIds.hasBit(pointerId)) {
2591 if (pointerIds.count() == 1) {
2592 // The first/last pointer went down/up.
2593 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002594 ? AMOTION_EVENT_ACTION_DOWN
2595 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 } else {
2597 // A secondary pointer went down/up.
2598 uint32_t splitPointerIndex = 0;
2599 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2600 splitPointerIndex += 1;
2601 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002602 action = maskedAction |
2603 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604 }
2605 } else {
2606 // An unrelated pointer changed.
2607 action = AMOTION_EVENT_ACTION_MOVE;
2608 }
2609 }
2610
Garfield Tan00f511d2019-06-12 16:55:40 -07002611 MotionEntry* splitMotionEntry =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002612 new MotionEntry(originalMotionEntry.sequenceNum, originalMotionEntry.eventTime,
2613 originalMotionEntry.deviceId, originalMotionEntry.source,
2614 originalMotionEntry.displayId, originalMotionEntry.policyFlags, action,
2615 originalMotionEntry.actionButton, originalMotionEntry.flags,
2616 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2617 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2618 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2619 originalMotionEntry.xCursorPosition,
2620 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002621 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002623 if (originalMotionEntry.injectionState) {
2624 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 splitMotionEntry->injectionState->refCount += 1;
2626 }
2627
2628 return splitMotionEntry;
2629}
2630
2631void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2632#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002633 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634#endif
2635
2636 bool needWake;
2637 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002638 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639
Prabir Pradhan42611e02018-11-27 14:04:02 -08002640 ConfigurationChangedEntry* newEntry =
2641 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 needWake = enqueueInboundEventLocked(newEntry);
2643 } // release lock
2644
2645 if (needWake) {
2646 mLooper->wake();
2647 }
2648}
2649
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002650/**
2651 * If one of the meta shortcuts is detected, process them here:
2652 * Meta + Backspace -> generate BACK
2653 * Meta + Enter -> generate HOME
2654 * This will potentially overwrite keyCode and metaState.
2655 */
2656void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002657 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002658 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2659 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2660 if (keyCode == AKEYCODE_DEL) {
2661 newKeyCode = AKEYCODE_BACK;
2662 } else if (keyCode == AKEYCODE_ENTER) {
2663 newKeyCode = AKEYCODE_HOME;
2664 }
2665 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002666 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002667 struct KeyReplacement replacement = {keyCode, deviceId};
2668 mReplacedKeys.add(replacement, newKeyCode);
2669 keyCode = newKeyCode;
2670 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2671 }
2672 } else if (action == AKEY_EVENT_ACTION_UP) {
2673 // In order to maintain a consistent stream of up and down events, check to see if the key
2674 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2675 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002676 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002677 struct KeyReplacement replacement = {keyCode, deviceId};
2678 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2679 if (index >= 0) {
2680 keyCode = mReplacedKeys.valueAt(index);
2681 mReplacedKeys.removeItemsAt(index);
2682 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2683 }
2684 }
2685}
2686
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2688#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002689 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2690 "policyFlags=0x%x, action=0x%x, "
2691 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2692 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2693 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2694 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695#endif
2696 if (!validateKeyEvent(args->action)) {
2697 return;
2698 }
2699
2700 uint32_t policyFlags = args->policyFlags;
2701 int32_t flags = args->flags;
2702 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002703 // InputDispatcher tracks and generates key repeats on behalf of
2704 // whatever notifies it, so repeatCount should always be set to 0
2705 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2707 policyFlags |= POLICY_FLAG_VIRTUAL;
2708 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 if (policyFlags & POLICY_FLAG_FUNCTION) {
2711 metaState |= AMETA_FUNCTION_ON;
2712 }
2713
2714 policyFlags |= POLICY_FLAG_TRUSTED;
2715
Michael Wright78f24442014-08-06 15:55:28 -07002716 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002717 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002718
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719 KeyEvent event;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002720 event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2721 args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722
Michael Wright2b3c3302018-03-02 17:19:13 +00002723 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002725 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2726 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002727 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002728 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 bool needWake;
2731 { // acquire lock
2732 mLock.lock();
2733
2734 if (shouldSendKeyToInputFilterLocked(args)) {
2735 mLock.unlock();
2736
2737 policyFlags |= POLICY_FLAG_FILTERED;
2738 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2739 return; // event was consumed by the filter
2740 }
2741
2742 mLock.lock();
2743 }
2744
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002745 KeyEntry* newEntry =
2746 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2747 args->displayId, policyFlags, args->action, flags, keyCode,
2748 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749
2750 needWake = enqueueInboundEventLocked(newEntry);
2751 mLock.unlock();
2752 } // release lock
2753
2754 if (needWake) {
2755 mLooper->wake();
2756 }
2757}
2758
2759bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2760 return mInputFilterEnabled;
2761}
2762
2763void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2764#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002765 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan00f511d2019-06-12 16:55:40 -07002766 ", policyFlags=0x%x, "
2767 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
2768 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07002769 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan00f511d2019-06-12 16:55:40 -07002770 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2771 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Jaewan Kim372fbe42019-10-02 10:58:46 +09002772 args->edgeFlags, args->xPrecision, args->yPrecision, args->xCursorPosition,
Garfield Tan00f511d2019-06-12 16:55:40 -07002773 args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 for (uint32_t i = 0; i < args->pointerCount; i++) {
2775 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002776 "x=%f, y=%f, pressure=%f, size=%f, "
2777 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2778 "orientation=%f",
2779 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2780 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2781 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2782 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2783 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2784 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2785 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2786 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2787 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2788 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789 }
2790#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002791 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2792 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 return;
2794 }
2795
2796 uint32_t policyFlags = args->policyFlags;
2797 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002798
2799 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002800 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002801 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2802 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002803 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805
2806 bool needWake;
2807 { // acquire lock
2808 mLock.lock();
2809
2810 if (shouldSendMotionToInputFilterLocked(args)) {
2811 mLock.unlock();
2812
2813 MotionEvent event;
Garfield Tan00f511d2019-06-12 16:55:40 -07002814 event.initialize(args->deviceId, args->source, args->displayId, args->action,
2815 args->actionButton, args->flags, args->edgeFlags, args->metaState,
2816 args->buttonState, args->classification, 0, 0, args->xPrecision,
2817 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2818 args->downTime, args->eventTime, args->pointerCount,
2819 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820
2821 policyFlags |= POLICY_FLAG_FILTERED;
2822 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2823 return; // event was consumed by the filter
2824 }
2825
2826 mLock.lock();
2827 }
2828
2829 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07002830 MotionEntry* newEntry =
2831 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2832 args->displayId, policyFlags, args->action, args->actionButton,
2833 args->flags, args->metaState, args->buttonState,
2834 args->classification, args->edgeFlags, args->xPrecision,
2835 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2836 args->downTime, args->pointerCount, args->pointerProperties,
2837 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838
2839 needWake = enqueueInboundEventLocked(newEntry);
2840 mLock.unlock();
2841 } // release lock
2842
2843 if (needWake) {
2844 mLooper->wake();
2845 }
2846}
2847
2848bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002849 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850}
2851
2852void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2853#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002854 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002855 "switchMask=0x%08x",
2856 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002857#endif
2858
2859 uint32_t policyFlags = args->policyFlags;
2860 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002861 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862}
2863
2864void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2865#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002866 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
2867 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868#endif
2869
2870 bool needWake;
2871 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002872 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873
Prabir Pradhan42611e02018-11-27 14:04:02 -08002874 DeviceResetEntry* newEntry =
2875 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876 needWake = enqueueInboundEventLocked(newEntry);
2877 } // release lock
2878
2879 if (needWake) {
2880 mLooper->wake();
2881 }
2882}
2883
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002884int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
2885 int32_t injectorUid, int32_t syncMode,
2886 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887#if DEBUG_INBOUND_EVENT_DETAILS
2888 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002889 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2890 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891#endif
2892
2893 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2894
2895 policyFlags |= POLICY_FLAG_INJECTED;
2896 if (hasInjectionPermission(injectorPid, injectorUid)) {
2897 policyFlags |= POLICY_FLAG_TRUSTED;
2898 }
2899
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07002900 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002902 case AINPUT_EVENT_TYPE_KEY: {
2903 KeyEvent keyEvent;
2904 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2905 int32_t action = keyEvent.getAction();
2906 if (!validateKeyEvent(action)) {
2907 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002909
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002910 int32_t flags = keyEvent.getFlags();
2911 int32_t keyCode = keyEvent.getKeyCode();
2912 int32_t metaState = keyEvent.getMetaState();
2913 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2914 /*byref*/ keyCode, /*byref*/ metaState);
2915 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
2916 keyEvent.getDisplayId(), action, flags, keyCode,
2917 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
2918 keyEvent.getDownTime(), keyEvent.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002920 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2921 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00002922 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002923
2924 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2925 android::base::Timer t;
2926 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
2927 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2928 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2929 std::to_string(t.duration().count()).c_str());
2930 }
2931 }
2932
2933 mLock.lock();
2934 KeyEntry* injectedEntry =
2935 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
2936 keyEvent.getDeviceId(), keyEvent.getSource(),
2937 keyEvent.getDisplayId(), policyFlags, action, flags,
2938 keyEvent.getKeyCode(), keyEvent.getScanCode(),
2939 keyEvent.getMetaState(), keyEvent.getRepeatCount(),
2940 keyEvent.getDownTime());
2941 injectedEntries.push(injectedEntry);
2942 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943 }
2944
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002945 case AINPUT_EVENT_TYPE_MOTION: {
2946 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2947 int32_t action = motionEvent->getAction();
2948 size_t pointerCount = motionEvent->getPointerCount();
2949 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2950 int32_t actionButton = motionEvent->getActionButton();
2951 int32_t displayId = motionEvent->getDisplayId();
2952 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
2953 return INPUT_EVENT_INJECTION_FAILED;
2954 }
2955
2956 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2957 nsecs_t eventTime = motionEvent->getEventTime();
2958 android::base::Timer t;
2959 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
2960 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2961 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2962 std::to_string(t.duration().count()).c_str());
2963 }
2964 }
2965
2966 mLock.lock();
2967 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2968 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2969 MotionEntry* injectedEntry =
Garfield Tan00f511d2019-06-12 16:55:40 -07002970 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2971 motionEvent->getDeviceId(), motionEvent->getSource(),
2972 motionEvent->getDisplayId(), policyFlags, action, actionButton,
2973 motionEvent->getFlags(), motionEvent->getMetaState(),
2974 motionEvent->getButtonState(), motionEvent->getClassification(),
2975 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
2976 motionEvent->getYPrecision(),
2977 motionEvent->getRawXCursorPosition(),
2978 motionEvent->getRawYCursorPosition(),
2979 motionEvent->getDownTime(), uint32_t(pointerCount),
2980 pointerProperties, samplePointerCoords,
2981 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002982 injectedEntries.push(injectedEntry);
2983 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2984 sampleEventTimes += 1;
2985 samplePointerCoords += pointerCount;
2986 MotionEntry* nextInjectedEntry =
2987 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2988 motionEvent->getDeviceId(), motionEvent->getSource(),
2989 motionEvent->getDisplayId(), policyFlags, action,
2990 actionButton, motionEvent->getFlags(),
2991 motionEvent->getMetaState(), motionEvent->getButtonState(),
2992 motionEvent->getClassification(),
2993 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
2994 motionEvent->getYPrecision(),
2995 motionEvent->getRawXCursorPosition(),
2996 motionEvent->getRawYCursorPosition(),
2997 motionEvent->getDownTime(), uint32_t(pointerCount),
2998 pointerProperties, samplePointerCoords,
2999 motionEvent->getXOffset(), motionEvent->getYOffset());
3000 injectedEntries.push(nextInjectedEntry);
3001 }
3002 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003005 default:
3006 ALOGW("Cannot inject event of type %d", event->getType());
3007 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003008 }
3009
3010 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3011 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3012 injectionState->injectionIsAsync = true;
3013 }
3014
3015 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003016 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017
3018 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003019 while (!injectedEntries.empty()) {
3020 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3021 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003022 }
3023
3024 mLock.unlock();
3025
3026 if (needWake) {
3027 mLooper->wake();
3028 }
3029
3030 int32_t injectionResult;
3031 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003032 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033
3034 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3035 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3036 } else {
3037 for (;;) {
3038 injectionResult = injectionState->injectionResult;
3039 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3040 break;
3041 }
3042
3043 nsecs_t remainingTimeout = endTime - now();
3044 if (remainingTimeout <= 0) {
3045#if DEBUG_INJECTION
3046 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003047 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048#endif
3049 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3050 break;
3051 }
3052
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003053 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054 }
3055
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003056 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3057 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058 while (injectionState->pendingForegroundDispatches != 0) {
3059#if DEBUG_INJECTION
3060 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003061 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062#endif
3063 nsecs_t remainingTimeout = endTime - now();
3064 if (remainingTimeout <= 0) {
3065#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003066 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3067 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068#endif
3069 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3070 break;
3071 }
3072
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003073 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074 }
3075 }
3076 }
3077
3078 injectionState->release();
3079 } // release lock
3080
3081#if DEBUG_INJECTION
3082 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003083 "injectorPid=%d, injectorUid=%d",
3084 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085#endif
3086
3087 return injectionResult;
3088}
3089
3090bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003091 return injectorUid == 0 ||
3092 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093}
3094
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003095void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096 InjectionState* injectionState = entry->injectionState;
3097 if (injectionState) {
3098#if DEBUG_INJECTION
3099 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 "injectorPid=%d, injectorUid=%d",
3101 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102#endif
3103
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003104 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105 // Log the outcome since the injector did not wait for the injection result.
3106 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003107 case INPUT_EVENT_INJECTION_SUCCEEDED:
3108 ALOGV("Asynchronous input event injection succeeded.");
3109 break;
3110 case INPUT_EVENT_INJECTION_FAILED:
3111 ALOGW("Asynchronous input event injection failed.");
3112 break;
3113 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3114 ALOGW("Asynchronous input event injection permission denied.");
3115 break;
3116 case INPUT_EVENT_INJECTION_TIMED_OUT:
3117 ALOGW("Asynchronous input event injection timed out.");
3118 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119 }
3120 }
3121
3122 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003123 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124 }
3125}
3126
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003127void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128 InjectionState* injectionState = entry->injectionState;
3129 if (injectionState) {
3130 injectionState->pendingForegroundDispatches += 1;
3131 }
3132}
3133
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003134void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135 InjectionState* injectionState = entry->injectionState;
3136 if (injectionState) {
3137 injectionState->pendingForegroundDispatches -= 1;
3138
3139 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003140 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141 }
3142 }
3143}
3144
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003145std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3146 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003147 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003148}
3149
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003151 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003152 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003153 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3154 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003155 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003156 return windowHandle;
3157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158 }
3159 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003160 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161}
3162
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003163bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003164 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003165 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3166 for (const sp<InputWindowHandle>& handle : windowHandles) {
3167 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003168 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003169 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003170 ", but it should belong to display %" PRId32,
3171 windowHandle->getName().c_str(), it.first,
3172 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003173 }
3174 return true;
3175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 }
3177 }
3178 return false;
3179}
3180
Robert Carr5c8a0262018-10-03 16:30:44 -07003181sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3182 size_t count = mInputChannelsByToken.count(token);
3183 if (count == 0) {
3184 return nullptr;
3185 }
3186 return mInputChannelsByToken.at(token);
3187}
3188
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003189void InputDispatcher::updateWindowHandlesForDisplayLocked(
3190 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3191 if (inputWindowHandles.empty()) {
3192 // Remove all handles on a display if there are no windows left.
3193 mWindowHandlesByDisplay.erase(displayId);
3194 return;
3195 }
3196
3197 // Since we compare the pointer of input window handles across window updates, we need
3198 // to make sure the handle object for the same window stays unchanged across updates.
3199 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
3200 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3201 for (const sp<InputWindowHandle>& handle : oldHandles) {
3202 oldHandlesByTokens[handle->getToken()] = handle;
3203 }
3204
3205 std::vector<sp<InputWindowHandle>> newHandles;
3206 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3207 if (!handle->updateInfo()) {
3208 // handle no longer valid
3209 continue;
3210 }
3211
3212 const InputWindowInfo* info = handle->getInfo();
3213 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3214 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3215 const bool noInputChannel =
3216 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3217 const bool canReceiveInput =
3218 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3219 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3220 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003221 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003222 handle->getName().c_str());
3223 }
3224 continue;
3225 }
3226
3227 if (info->displayId != displayId) {
3228 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3229 handle->getName().c_str(), displayId, info->displayId);
3230 continue;
3231 }
3232
3233 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3234 const sp<InputWindowHandle> oldHandle = oldHandlesByTokens.at(handle->getToken());
3235 oldHandle->updateFrom(handle);
3236 newHandles.push_back(oldHandle);
3237 } else {
3238 newHandles.push_back(handle);
3239 }
3240 }
3241
3242 // Insert or replace
3243 mWindowHandlesByDisplay[displayId] = newHandles;
3244}
3245
Arthur Hungb92218b2018-08-14 12:00:21 +08003246/**
3247 * Called from InputManagerService, update window handle list by displayId that can receive input.
3248 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3249 * If set an empty list, remove all handles from the specific display.
3250 * For focused handle, check if need to change and send a cancel event to previous one.
3251 * For removed handle, check if need to send a cancel event if already in touch.
3252 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003253void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254 int32_t displayId,
3255 const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003256 if (DEBUG_FOCUS) {
3257 std::string windowList;
3258 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3259 windowList += iwh->getName() + " ";
3260 }
3261 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3262 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003264 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265
Arthur Hungb92218b2018-08-14 12:00:21 +08003266 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003267 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3268 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003270 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
3271
Tiger Huang721e26f2018-07-24 22:26:19 +08003272 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273 bool foundHoveredWindow = false;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003274 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3275 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3276 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3277 windowHandle->getInfo()->visible) {
3278 newFocusedWindowHandle = windowHandle;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003279 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003280 if (windowHandle == mLastHoverWindowHandle) {
3281 foundHoveredWindow = true;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003282 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283 }
3284
3285 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003286 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287 }
3288
Tiger Huang721e26f2018-07-24 22:26:19 +08003289 sp<InputWindowHandle> oldFocusedWindowHandle =
3290 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3291
3292 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3293 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003294 if (DEBUG_FOCUS) {
3295 ALOGD("Focus left window: %s in display %" PRId32,
3296 oldFocusedWindowHandle->getName().c_str(), displayId);
3297 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298 sp<InputChannel> focusedInputChannel =
3299 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003300 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003302 "focus left window");
3303 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003305 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003307 if (newFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003308 if (DEBUG_FOCUS) {
3309 ALOGD("Focus entered window: %s in display %" PRId32,
3310 newFocusedWindowHandle->getName().c_str(), displayId);
3311 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003312 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313 }
Robert Carrf759f162018-11-13 12:57:11 -08003314
3315 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003316 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318 }
3319
Arthur Hungb92218b2018-08-14 12:00:21 +08003320 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3321 if (stateIndex >= 0) {
3322 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003323 for (size_t i = 0; i < state.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003324 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003325 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003326 if (DEBUG_FOCUS) {
3327 ALOGD("Touched window was removed: %s in display %" PRId32,
3328 touchedWindow.windowHandle->getName().c_str(), displayId);
3329 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003330 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003331 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003332 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003333 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 "touched window was removed");
3335 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3336 options);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003337 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003338 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003339 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003340 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 }
3343 }
3344
3345 // Release information for windows that are no longer present.
3346 // This ensures that unused input channels are released promptly.
3347 // Otherwise, they might stick around until the window handle is destroyed
3348 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003349 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003350 if (!hasWindowHandleLocked(oldWindowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003351 if (DEBUG_FOCUS) {
3352 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
3353 }
Arthur Hung3b413f22018-10-26 18:05:34 +08003354 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355 }
3356 }
3357 } // release lock
3358
3359 // Wake up poll loop since it may need to make new input dispatching choices.
3360 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003361
3362 if (setInputWindowsListener) {
3363 setInputWindowsListener->onSetInputWindowsFinished();
3364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365}
3366
3367void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003368 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003369 if (DEBUG_FOCUS) {
3370 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3371 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003374 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375
Tiger Huang721e26f2018-07-24 22:26:19 +08003376 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3377 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003378 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003379 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3380 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003383 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003385 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003387 oldFocusedApplicationHandle.clear();
3388 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 } // release lock
3391
3392 // Wake up poll loop since it may need to make new input dispatching choices.
3393 mLooper->wake();
3394}
3395
Tiger Huang721e26f2018-07-24 22:26:19 +08003396/**
3397 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3398 * the display not specified.
3399 *
3400 * We track any unreleased events for each window. If a window loses the ability to receive the
3401 * released event, we will send a cancel event to it. So when the focused display is changed, we
3402 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3403 * display. The display-specified events won't be affected.
3404 */
3405void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003406 if (DEBUG_FOCUS) {
3407 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3408 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003409 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003410 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003411
3412 if (mFocusedDisplayId != displayId) {
3413 sp<InputWindowHandle> oldFocusedWindowHandle =
3414 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3415 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003416 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003417 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003418 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003419 CancelationOptions
3420 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3421 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003422 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003423 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3424 }
3425 }
3426 mFocusedDisplayId = displayId;
3427
3428 // Sanity check
3429 sp<InputWindowHandle> newFocusedWindowHandle =
3430 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003431 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003432
Tiger Huang721e26f2018-07-24 22:26:19 +08003433 if (newFocusedWindowHandle == nullptr) {
3434 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3435 if (!mFocusedWindowHandlesByDisplay.empty()) {
3436 ALOGE("But another display has a focused window:");
3437 for (auto& it : mFocusedWindowHandlesByDisplay) {
3438 const int32_t displayId = it.first;
3439 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003440 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3441 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003442 }
3443 }
3444 }
3445 }
3446
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003447 if (DEBUG_FOCUS) {
3448 logDispatchStateLocked();
3449 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003450 } // release lock
3451
3452 // Wake up poll loop since it may need to make new input dispatching choices.
3453 mLooper->wake();
3454}
3455
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003457 if (DEBUG_FOCUS) {
3458 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460
3461 bool changed;
3462 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003463 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003464
3465 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3466 if (mDispatchFrozen && !frozen) {
3467 resetANRTimeoutsLocked();
3468 }
3469
3470 if (mDispatchEnabled && !enabled) {
3471 resetAndDropEverythingLocked("dispatcher is being disabled");
3472 }
3473
3474 mDispatchEnabled = enabled;
3475 mDispatchFrozen = frozen;
3476 changed = true;
3477 } else {
3478 changed = false;
3479 }
3480
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003481 if (DEBUG_FOCUS) {
3482 logDispatchStateLocked();
3483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484 } // release lock
3485
3486 if (changed) {
3487 // Wake up poll loop since it may need to make new input dispatching choices.
3488 mLooper->wake();
3489 }
3490}
3491
3492void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003493 if (DEBUG_FOCUS) {
3494 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496
3497 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003498 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499
3500 if (mInputFilterEnabled == enabled) {
3501 return;
3502 }
3503
3504 mInputFilterEnabled = enabled;
3505 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3506 } // release lock
3507
3508 // Wake up poll loop since there might be work to do to drop everything.
3509 mLooper->wake();
3510}
3511
chaviwfbe5d9c2018-12-26 12:23:37 -08003512bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3513 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003514 if (DEBUG_FOCUS) {
3515 ALOGD("Trivial transfer to same window.");
3516 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003517 return true;
3518 }
3519
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003521 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522
chaviwfbe5d9c2018-12-26 12:23:37 -08003523 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3524 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003525 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003526 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 return false;
3528 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003529 if (DEBUG_FOCUS) {
3530 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3531 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003534 if (DEBUG_FOCUS) {
3535 ALOGD("Cannot transfer focus because windows are on different displays.");
3536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 return false;
3538 }
3539
3540 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003541 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3542 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3543 for (size_t i = 0; i < state.windows.size(); i++) {
3544 const TouchedWindow& touchedWindow = state.windows[i];
3545 if (touchedWindow.windowHandle == fromWindowHandle) {
3546 int32_t oldTargetFlags = touchedWindow.targetFlags;
3547 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003549 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003551 int32_t newTargetFlags = oldTargetFlags &
3552 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3553 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003554 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555
Jeff Brownf086ddb2014-02-11 14:28:48 -08003556 found = true;
3557 goto Found;
3558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 }
3560 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003561 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003563 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003564 if (DEBUG_FOCUS) {
3565 ALOGD("Focus transfer failed because from window did not have focus.");
3566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 return false;
3568 }
3569
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003570 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3571 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003572 if (fromConnection != nullptr && toConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003574 CancelationOptions
3575 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3576 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3578 }
3579
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003580 if (DEBUG_FOCUS) {
3581 logDispatchStateLocked();
3582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 } // release lock
3584
3585 // Wake up poll loop since it may need to make new input dispatching choices.
3586 mLooper->wake();
3587 return true;
3588}
3589
3590void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003591 if (DEBUG_FOCUS) {
3592 ALOGD("Resetting and dropping all events (%s).", reason);
3593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594
3595 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3596 synthesizeCancelationEventsForAllConnectionsLocked(options);
3597
3598 resetKeyRepeatLocked();
3599 releasePendingEventLocked();
3600 drainInboundQueueLocked();
3601 resetANRTimeoutsLocked();
3602
Jeff Brownf086ddb2014-02-11 14:28:48 -08003603 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003605 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606}
3607
3608void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003609 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 dumpDispatchStateLocked(dump);
3611
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003612 std::istringstream stream(dump);
3613 std::string line;
3614
3615 while (std::getline(stream, line, '\n')) {
3616 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
3618}
3619
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003620void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003621 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3622 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3623 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003624 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625
Tiger Huang721e26f2018-07-24 22:26:19 +08003626 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3627 dump += StringPrintf(INDENT "FocusedApplications:\n");
3628 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3629 const int32_t displayId = it.first;
3630 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003631 dump += StringPrintf(INDENT2 "displayId=%" PRId32
3632 ", name='%s', dispatchingTimeout=%0.3fms\n",
3633 displayId, applicationHandle->getName().c_str(),
3634 applicationHandle->getDispatchingTimeout(
3635 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3636 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08003637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003639 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003641
3642 if (!mFocusedWindowHandlesByDisplay.empty()) {
3643 dump += StringPrintf(INDENT "FocusedWindows:\n");
3644 for (auto& it : mFocusedWindowHandlesByDisplay) {
3645 const int32_t displayId = it.first;
3646 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003647 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3648 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003649 }
3650 } else {
3651 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653
Jeff Brownf086ddb2014-02-11 14:28:48 -08003654 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003655 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003656 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3657 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003658 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003659 state.displayId, toString(state.down), toString(state.split),
3660 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003661 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003662 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003663 for (size_t i = 0; i < state.windows.size(); i++) {
3664 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003665 dump += StringPrintf(INDENT4
3666 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3667 i, touchedWindow.windowHandle->getName().c_str(),
3668 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003669 }
3670 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003671 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003672 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003673 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003674 dump += INDENT3 "Portal windows:\n";
3675 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003676 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003677 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3678 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003679 }
3680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 }
3682 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003683 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 }
3685
Arthur Hungb92218b2018-08-14 12:00:21 +08003686 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003687 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003688 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003689 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003690 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003691 dump += INDENT2 "Windows:\n";
3692 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003693 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003694 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695
Arthur Hungb92218b2018-08-14 12:00:21 +08003696 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003697 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
3698 "hasWallpaper=%s, "
3699 "visible=%s, canReceiveKeys=%s, flags=0x%08x, "
3700 "type=0x%08x, layer=%d, "
3701 "frame=[%d,%d][%d,%d], globalScale=%f, "
3702 "windowScale=(%f,%f), "
3703 "touchableRegion=",
3704 i, windowInfo->name.c_str(), windowInfo->displayId,
3705 windowInfo->portalToDisplayId,
3706 toString(windowInfo->paused),
3707 toString(windowInfo->hasFocus),
3708 toString(windowInfo->hasWallpaper),
3709 toString(windowInfo->visible),
3710 toString(windowInfo->canReceiveKeys),
3711 windowInfo->layoutParamsFlags,
3712 windowInfo->layoutParamsType, windowInfo->layer,
3713 windowInfo->frameLeft, windowInfo->frameTop,
3714 windowInfo->frameRight, windowInfo->frameBottom,
3715 windowInfo->globalScaleFactor, windowInfo->windowXScale,
3716 windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003717 dumpRegion(dump, windowInfo->touchableRegion);
3718 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3719 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003720 windowInfo->ownerPid, windowInfo->ownerUid,
3721 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08003722 }
3723 } else {
3724 dump += INDENT2 "Windows: <none>\n";
3725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726 }
3727 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003728 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 }
3730
Michael Wright3dd60e22019-03-27 22:06:44 +00003731 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003732 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003733 const std::vector<Monitor>& monitors = it.second;
3734 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3735 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003736 }
3737 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003738 const std::vector<Monitor>& monitors = it.second;
3739 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3740 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003743 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 }
3745
3746 nsecs_t currentTime = now();
3747
3748 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003749 if (!mRecentQueue.empty()) {
3750 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
3751 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003752 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003754 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755 }
3756 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003757 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 }
3759
3760 // Dump event currently being dispatched.
3761 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003762 dump += INDENT "PendingEvent:\n";
3763 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003765 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003766 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003768 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 }
3770
3771 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003772 if (!mInboundQueue.empty()) {
3773 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
3774 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003775 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003777 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 }
3779 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003780 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 }
3782
Michael Wright78f24442014-08-06 15:55:28 -07003783 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003784 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003785 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3786 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3787 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003788 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3789 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07003790 }
3791 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003792 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003793 }
3794
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003795 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003796 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003797 for (const auto& pair : mConnectionsByFd) {
3798 const sp<Connection>& connection = pair.second;
3799 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
3800 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3801 pair.first, connection->getInputChannelName().c_str(),
3802 connection->getWindowName().c_str(), connection->getStatusLabel(),
3803 toString(connection->monitor),
3804 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003806 if (!connection->outboundQueue.empty()) {
3807 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
3808 connection->outboundQueue.size());
3809 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 dump.append(INDENT4);
3811 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003812 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003813 entry->targetFlags, entry->resolvedAction,
3814 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 }
3816 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003817 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 }
3819
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003820 if (!connection->waitQueue.empty()) {
3821 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
3822 connection->waitQueue.size());
3823 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003824 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003826 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003827 "age=%0.1fms, wait=%0.1fms\n",
3828 entry->targetFlags, entry->resolvedAction,
3829 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3830 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 }
3832 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003833 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 }
3835 }
3836 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003837 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 }
3839
3840 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003841 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003842 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003844 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003845 }
3846
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003847 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003848 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003849 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003850 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851}
3852
Michael Wright3dd60e22019-03-27 22:06:44 +00003853void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3854 const size_t numMonitors = monitors.size();
3855 for (size_t i = 0; i < numMonitors; i++) {
3856 const Monitor& monitor = monitors[i];
3857 const sp<InputChannel>& channel = monitor.inputChannel;
3858 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3859 dump += "\n";
3860 }
3861}
3862
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003863status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003865 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866#endif
3867
3868 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003869 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003870 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003871 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003873 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 return BAD_VALUE;
3875 }
3876
Michael Wright3dd60e22019-03-27 22:06:44 +00003877 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878
3879 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003880 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003881 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3884 } // release lock
3885
3886 // Wake the looper because some connections have changed.
3887 mLooper->wake();
3888 return OK;
3889}
3890
Michael Wright3dd60e22019-03-27 22:06:44 +00003891status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003892 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003893 { // acquire lock
3894 std::scoped_lock _l(mLock);
3895
3896 if (displayId < 0) {
3897 ALOGW("Attempted to register input monitor without a specified display.");
3898 return BAD_VALUE;
3899 }
3900
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003901 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003902 ALOGW("Attempted to register input monitor without an identifying token.");
3903 return BAD_VALUE;
3904 }
3905
3906 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3907
3908 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003909 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003910 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00003911
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003912 auto& monitorsByDisplay =
3913 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00003914 monitorsByDisplay[displayId].emplace_back(inputChannel);
3915
3916 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00003917 }
3918 // Wake the looper because some connections have changed.
3919 mLooper->wake();
3920 return OK;
3921}
3922
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3924#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003925 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926#endif
3927
3928 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003929 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930
3931 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3932 if (status) {
3933 return status;
3934 }
3935 } // release lock
3936
3937 // Wake the poll loop because removing the connection may have changed the current
3938 // synchronization state.
3939 mLooper->wake();
3940 return OK;
3941}
3942
3943status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003944 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003945 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003946 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003948 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 return BAD_VALUE;
3950 }
3951
John Recke0710582019-09-26 13:46:12 -07003952 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003953 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003954 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07003955
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 if (connection->monitor) {
3957 removeMonitorChannelLocked(inputChannel);
3958 }
3959
3960 mLooper->removeFd(inputChannel->getFd());
3961
3962 nsecs_t currentTime = now();
3963 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3964
3965 connection->status = Connection::STATUS_ZOMBIE;
3966 return OK;
3967}
3968
3969void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003970 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
3971 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
3972}
3973
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003974void InputDispatcher::removeMonitorChannelLocked(
3975 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00003976 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003977 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003978 std::vector<Monitor>& monitors = it->second;
3979 const size_t numMonitors = monitors.size();
3980 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003981 if (monitors[i].inputChannel == inputChannel) {
3982 monitors.erase(monitors.begin() + i);
3983 break;
3984 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003985 }
Michael Wright3dd60e22019-03-27 22:06:44 +00003986 if (monitors.empty()) {
3987 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003988 } else {
3989 ++it;
3990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 }
3992}
3993
Michael Wright3dd60e22019-03-27 22:06:44 +00003994status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
3995 { // acquire lock
3996 std::scoped_lock _l(mLock);
3997 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
3998
3999 if (!foundDisplayId) {
4000 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4001 return BAD_VALUE;
4002 }
4003 int32_t displayId = foundDisplayId.value();
4004
4005 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4006 if (stateIndex < 0) {
4007 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4008 return BAD_VALUE;
4009 }
4010
4011 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4012 std::optional<int32_t> foundDeviceId;
4013 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004014 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004015 foundDeviceId = state.deviceId;
4016 }
4017 }
4018 if (!foundDeviceId || !state.down) {
4019 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004020 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004021 return BAD_VALUE;
4022 }
4023 int32_t deviceId = foundDeviceId.value();
4024
4025 // Send cancel events to all the input channels we're stealing from.
4026 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004027 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004028 options.deviceId = deviceId;
4029 options.displayId = displayId;
4030 for (const TouchedWindow& window : state.windows) {
4031 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
4032 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4033 }
4034 // Then clear the current touch state so we stop dispatching to them as well.
4035 state.filterNonMonitors();
4036 }
4037 return OK;
4038}
4039
Michael Wright3dd60e22019-03-27 22:06:44 +00004040std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4041 const sp<IBinder>& token) {
4042 for (const auto& it : mGestureMonitorsByDisplay) {
4043 const std::vector<Monitor>& monitors = it.second;
4044 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004045 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004046 return it.first;
4047 }
4048 }
4049 }
4050 return std::nullopt;
4051}
4052
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004053sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4054 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004055 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004056 }
4057
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004058 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004059 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004060 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004061 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062 }
4063 }
Robert Carr4e670e52018-08-15 13:26:12 -07004064
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004065 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066}
4067
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004068void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4069 const sp<Connection>& connection, uint32_t seq,
4070 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004071 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4072 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073 commandEntry->connection = connection;
4074 commandEntry->eventTime = currentTime;
4075 commandEntry->seq = seq;
4076 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004077 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078}
4079
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004080void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4081 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004083 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004085 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4086 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004088 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089}
4090
chaviw0c06c6e2019-01-09 13:27:07 -08004091void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004092 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004093 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4094 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004095 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4096 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004097 commandEntry->oldToken = oldToken;
4098 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004099 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004100}
4101
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004102void InputDispatcher::onANRLocked(nsecs_t currentTime,
4103 const sp<InputApplicationHandle>& applicationHandle,
4104 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4105 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4107 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4108 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004109 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4110 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4111 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112
4113 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004114 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115 struct tm tm;
4116 localtime_r(&t, &tm);
4117 char timestr[64];
4118 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4119 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004120 mLastANRState += INDENT "ANR:\n";
4121 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004122 mLastANRState +=
4123 StringPrintf(INDENT2 "Window: %s\n",
4124 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004125 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4126 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4127 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128 dumpDispatchStateLocked(mLastANRState);
4129
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004130 std::unique_ptr<CommandEntry> commandEntry =
4131 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004133 commandEntry->inputChannel =
4134 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004136 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137}
4138
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004139void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 mLock.unlock();
4141
4142 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4143
4144 mLock.lock();
4145}
4146
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004147void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 sp<Connection> connection = commandEntry->connection;
4149
4150 if (connection->status != Connection::STATUS_ZOMBIE) {
4151 mLock.unlock();
4152
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004153 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154
4155 mLock.lock();
4156 }
4157}
4158
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004159void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004160 sp<IBinder> oldToken = commandEntry->oldToken;
4161 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004162 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004163 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004164 mLock.lock();
4165}
4166
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004168 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004169 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 mLock.unlock();
4171
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004172 nsecs_t newTimeout =
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004173 mPolicy->notifyANR(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174
4175 mLock.lock();
4176
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004177 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178}
4179
4180void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4181 CommandEntry* commandEntry) {
4182 KeyEntry* entry = commandEntry->keyEntry;
4183
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004184 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185
4186 mLock.unlock();
4187
Michael Wright2b3c3302018-03-02 17:19:13 +00004188 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004189 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004190 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004191 : nullptr;
4192 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004193 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4194 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004195 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197
4198 mLock.lock();
4199
4200 if (delay < 0) {
4201 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4202 } else if (!delay) {
4203 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4204 } else {
4205 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4206 entry->interceptKeyWakeupTime = now() + delay;
4207 }
4208 entry->release();
4209}
4210
chaviwfd6d3512019-03-25 13:23:49 -07004211void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4212 mLock.unlock();
4213 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4214 mLock.lock();
4215}
4216
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004217void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004219 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004221 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222
4223 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004224 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004225 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004226 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004228 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004229
4230 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4231 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4232 std::string msg =
4233 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4234 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4235 dispatchEntry->eventEntry->appendDescription(msg);
4236 ALOGI("%s", msg.c_str());
4237 }
4238
4239 bool restartEvent;
4240 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4241 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4242 restartEvent =
4243 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
4244 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4245 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4246 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4247 handled);
4248 } else {
4249 restartEvent = false;
4250 }
4251
4252 // Dequeue the event and start the next cycle.
4253 // Note that because the lock might have been released, it is possible that the
4254 // contents of the wait queue to have been drained, so we need to double-check
4255 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004256 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4257 if (dispatchEntryIt != connection->waitQueue.end()) {
4258 dispatchEntry = *dispatchEntryIt;
4259 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004260 traceWaitQueueLength(connection);
4261 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004262 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004263 traceOutboundQueueLength(connection);
4264 } else {
4265 releaseDispatchEntry(dispatchEntry);
4266 }
4267 }
4268
4269 // Start the next dispatch cycle for this connection.
4270 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271}
4272
4273bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004274 DispatchEntry* dispatchEntry,
4275 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004276 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004277 if (!handled) {
4278 // Report the key as unhandled, since the fallback was not handled.
4279 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4280 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004281 return false;
4282 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004284 // Get the fallback key state.
4285 // Clear it out after dispatching the UP.
4286 int32_t originalKeyCode = keyEntry->keyCode;
4287 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4288 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4289 connection->inputState.removeFallbackKey(originalKeyCode);
4290 }
4291
4292 if (handled || !dispatchEntry->hasForegroundTarget()) {
4293 // If the application handles the original key for which we previously
4294 // generated a fallback or if the window is not a foreground window,
4295 // then cancel the associated fallback key, if any.
4296 if (fallbackKeyCode != -1) {
4297 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004299 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4301 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4302 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004304 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004305 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306
4307 mLock.unlock();
4308
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004309 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004310 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311
4312 mLock.lock();
4313
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004314 // Cancel the fallback key.
4315 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004317 "application handled the original non-fallback key "
4318 "or is no longer a foreground target, "
4319 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 options.keyCode = fallbackKeyCode;
4321 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004323 connection->inputState.removeFallbackKey(originalKeyCode);
4324 }
4325 } else {
4326 // If the application did not handle a non-fallback key, first check
4327 // that we are in a good state to perform unhandled key event processing
4328 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004329 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004330 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004332 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004333 "since this is not an initial down. "
4334 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4335 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004337 return false;
4338 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004340 // Dispatch the unhandled key to the policy.
4341#if DEBUG_OUTBOUND_EVENT_DETAILS
4342 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004343 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4344 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004345#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004346 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004347
4348 mLock.unlock();
4349
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004350 bool fallback =
4351 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4352 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004353
4354 mLock.lock();
4355
4356 if (connection->status != Connection::STATUS_NORMAL) {
4357 connection->inputState.removeFallbackKey(originalKeyCode);
4358 return false;
4359 }
4360
4361 // Latch the fallback keycode for this key on an initial down.
4362 // The fallback keycode cannot change at any other point in the lifecycle.
4363 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004365 fallbackKeyCode = event.getKeyCode();
4366 } else {
4367 fallbackKeyCode = AKEYCODE_UNKNOWN;
4368 }
4369 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4370 }
4371
4372 ALOG_ASSERT(fallbackKeyCode != -1);
4373
4374 // Cancel the fallback key if the policy decides not to send it anymore.
4375 // We will continue to dispatch the key to the policy but we will no
4376 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004377 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4378 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004379#if DEBUG_OUTBOUND_EVENT_DETAILS
4380 if (fallback) {
4381 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004382 "as a fallback for %d, but on the DOWN it had requested "
4383 "to send %d instead. Fallback canceled.",
4384 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004385 } else {
4386 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004387 "but on the DOWN it had requested to send %d. "
4388 "Fallback canceled.",
4389 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004390 }
4391#endif
4392
4393 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4394 "canceling fallback, policy no longer desires it");
4395 options.keyCode = fallbackKeyCode;
4396 synthesizeCancelationEventsForConnectionLocked(connection, options);
4397
4398 fallback = false;
4399 fallbackKeyCode = AKEYCODE_UNKNOWN;
4400 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004401 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004402 }
4403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404
4405#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004406 {
4407 std::string msg;
4408 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4409 connection->inputState.getFallbackKeys();
4410 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004411 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004413 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004414 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004415 }
4416#endif
4417
4418 if (fallback) {
4419 // Restart the dispatch cycle using the fallback key.
4420 keyEntry->eventTime = event.getEventTime();
4421 keyEntry->deviceId = event.getDeviceId();
4422 keyEntry->source = event.getSource();
4423 keyEntry->displayId = event.getDisplayId();
4424 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4425 keyEntry->keyCode = fallbackKeyCode;
4426 keyEntry->scanCode = event.getScanCode();
4427 keyEntry->metaState = event.getMetaState();
4428 keyEntry->repeatCount = event.getRepeatCount();
4429 keyEntry->downTime = event.getDownTime();
4430 keyEntry->syntheticRepeat = false;
4431
4432#if DEBUG_OUTBOUND_EVENT_DETAILS
4433 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004434 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4435 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004436#endif
4437 return true; // restart the event
4438 } else {
4439#if DEBUG_OUTBOUND_EVENT_DETAILS
4440 ALOGD("Unhandled key event: No fallback key.");
4441#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004442
4443 // Report the key as unhandled, since there is no fallback key.
4444 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 }
4446 }
4447 return false;
4448}
4449
4450bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004451 DispatchEntry* dispatchEntry,
4452 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453 return false;
4454}
4455
4456void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4457 mLock.unlock();
4458
4459 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4460
4461 mLock.lock();
4462}
4463
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004464KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4465 KeyEvent event;
4466 event.initialize(entry.deviceId, entry.source, entry.displayId, entry.action, entry.flags,
4467 entry.keyCode, entry.scanCode, entry.metaState, entry.repeatCount,
4468 entry.downTime, entry.eventTime);
4469 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470}
4471
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004472void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004473 int32_t injectionResult,
4474 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475 // TODO Write some statistics about how long we spend waiting.
4476}
4477
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004478/**
4479 * Report the touch event latency to the statsd server.
4480 * Input events are reported for statistics if:
4481 * - This is a touchscreen event
4482 * - InputFilter is not enabled
4483 * - Event is not injected or synthesized
4484 *
4485 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4486 * from getting aggregated with the "old" data.
4487 */
4488void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4489 REQUIRES(mLock) {
4490 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4491 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4492 if (!reportForStatistics) {
4493 return;
4494 }
4495
4496 if (mTouchStatistics.shouldReport()) {
4497 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4498 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4499 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4500 mTouchStatistics.reset();
4501 }
4502 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4503 mTouchStatistics.addValue(latencyMicros);
4504}
4505
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506void InputDispatcher::traceInboundQueueLengthLocked() {
4507 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004508 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 }
4510}
4511
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004512void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513 if (ATRACE_ENABLED()) {
4514 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004515 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004516 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517 }
4518}
4519
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004520void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521 if (ATRACE_ENABLED()) {
4522 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004523 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004524 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 }
4526}
4527
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004528void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004529 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004531 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532 dumpDispatchStateLocked(dump);
4533
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004534 if (!mLastANRState.empty()) {
4535 dump += "\nInput Dispatcher State at time of last ANR:\n";
4536 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537 }
4538}
4539
4540void InputDispatcher::monitor() {
4541 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004542 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004544 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545}
4546
Garfield Tane84e6f92019-08-29 17:28:41 -07004547} // namespace android::inputdispatcher