blob: aba5a302069097d59d478dd11461f0cb821532b0 [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) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700389 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700390 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
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700397 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700398 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
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700404 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700405 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
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700424 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700425 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 }
439
440 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700441 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700442 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800443 }
Michael Wright3a981722015-06-10 15:26:13 +0100444 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800445
446 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700447 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448 }
449}
450
451bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700452 bool needWake = mInboundQueue.empty();
453 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800454 traceInboundQueueLengthLocked();
455
456 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700457 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700458 // Optimize app switch latency.
459 // If the application takes too long to catch up then we drop all events preceding
460 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700461 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700462 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700463 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700464 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700465 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700466 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800467#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700468 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700470 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700471 mAppSwitchSawKeyDown = false;
472 needWake = true;
473 }
474 }
475 }
476 break;
477 }
478
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700479 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700480 // Optimize case where the current application is unresponsive and the user
481 // decides to touch a window in a different application.
482 // If the application takes too long to catch up then we drop all events preceding
483 // the touch into the other window.
484 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
485 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
486 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
487 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
488 mInputTargetWaitApplicationToken != nullptr) {
489 int32_t displayId = motionEntry->displayId;
490 int32_t x =
491 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
492 int32_t y =
493 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
494 sp<InputWindowHandle> touchedWindowHandle =
495 findTouchedWindowAtLocked(displayId, x, y);
496 if (touchedWindowHandle != nullptr &&
497 touchedWindowHandle->getApplicationToken() !=
498 mInputTargetWaitApplicationToken) {
499 // User touched a different application than the one we are waiting on.
500 // Flag the event, and start pruning the input queue.
501 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502 needWake = true;
503 }
504 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700505 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700507 case EventEntry::Type::CONFIGURATION_CHANGED:
508 case EventEntry::Type::DEVICE_RESET: {
509 // nothing to do
510 break;
511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800512 }
513
514 return needWake;
515}
516
517void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
518 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700519 mRecentQueue.push_back(entry);
520 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
521 mRecentQueue.front()->release();
522 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800523 }
524}
525
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700526sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
527 int32_t y, bool addOutsideTargets,
528 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800530 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
531 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532 const InputWindowInfo* windowInfo = windowHandle->getInfo();
533 if (windowInfo->displayId == displayId) {
534 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535
536 if (windowInfo->visible) {
537 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700538 bool isTouchModal = (flags &
539 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
540 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800541 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800542 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700543 if (portalToDisplayId != ADISPLAY_ID_NONE &&
544 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800545 if (addPortalWindows) {
546 // For the monitoring channels of the display.
547 mTempTouchState.addPortalWindow(windowHandle);
548 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700549 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
550 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 // Found window.
553 return windowHandle;
554 }
555 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800556
557 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700558 mTempTouchState.addOrUpdateWindow(windowHandle,
559 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
560 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 }
564 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700565 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800566}
567
Garfield Tane84e6f92019-08-29 17:28:41 -0700568std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000569 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
570 std::vector<TouchedMonitor> touchedMonitors;
571
572 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
573 addGestureMonitors(monitors, touchedMonitors);
574 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
575 const InputWindowInfo* windowInfo = portalWindow->getInfo();
576 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700577 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
578 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000579 }
580 return touchedMonitors;
581}
582
583void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700584 std::vector<TouchedMonitor>& outTouchedMonitors,
585 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000586 if (monitors.empty()) {
587 return;
588 }
589 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
590 for (const Monitor& monitor : monitors) {
591 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
592 }
593}
594
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700595void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596 const char* reason;
597 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700598 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700600 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700602 reason = "inbound event was dropped because the policy consumed it";
603 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700604 case DropReason::DISABLED:
605 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700606 ALOGI("Dropped event because input dispatch is disabled.");
607 }
608 reason = "inbound event was dropped because input dispatch is disabled";
609 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700610 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700611 ALOGI("Dropped event because of pending overdue app switch.");
612 reason = "inbound event was dropped because of pending overdue app switch";
613 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700614 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700615 ALOGI("Dropped event because the current application is not responding and the user "
616 "has started interacting with a different application.");
617 reason = "inbound event was dropped because the current application is not responding "
618 "and the user has started interacting with a different application";
619 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700620 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700621 ALOGI("Dropped event because it is stale.");
622 reason = "inbound event was dropped because it is stale";
623 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700624 case DropReason::NOT_DROPPED: {
625 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700626 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628 }
629
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700630 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700631 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
633 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700634 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800635 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700636 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700637 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
638 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700639 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
640 synthesizeCancelationEventsForAllConnectionsLocked(options);
641 } else {
642 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
643 synthesizeCancelationEventsForAllConnectionsLocked(options);
644 }
645 break;
646 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700647 case EventEntry::Type::CONFIGURATION_CHANGED:
648 case EventEntry::Type::DEVICE_RESET: {
649 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
650 break;
651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652 }
653}
654
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800655static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700656 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
657 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658}
659
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700660bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
661 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
662 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
663 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664}
665
666bool InputDispatcher::isAppSwitchPendingLocked() {
667 return mAppSwitchDueTime != LONG_LONG_MAX;
668}
669
670void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
671 mAppSwitchDueTime = LONG_LONG_MAX;
672
673#if DEBUG_APP_SWITCH
674 if (handled) {
675 ALOGD("App switch has arrived.");
676 } else {
677 ALOGD("App switch was abandoned.");
678 }
679#endif
680}
681
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700682bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
683 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684}
685
686bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700687 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688}
689
690bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700691 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 return false;
693 }
694
695 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700696 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700697 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700699 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700
701 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700702 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 return true;
704}
705
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700706void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
707 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708}
709
710void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700711 while (!mInboundQueue.empty()) {
712 EventEntry* entry = mInboundQueue.front();
713 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 releaseInboundEventLocked(entry);
715 }
716 traceInboundQueueLengthLocked();
717}
718
719void InputDispatcher::releasePendingEventLocked() {
720 if (mPendingEvent) {
721 resetANRTimeoutsLocked();
722 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700723 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 }
725}
726
727void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
728 InjectionState* injectionState = entry->injectionState;
729 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
730#if DEBUG_DISPATCH_CYCLE
731 ALOGD("Injected inbound event was dropped.");
732#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800733 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734 }
735 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700736 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 }
738 addRecentEventLocked(entry);
739 entry->release();
740}
741
742void InputDispatcher::resetKeyRepeatLocked() {
743 if (mKeyRepeatState.lastKeyEntry) {
744 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700745 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746 }
747}
748
Garfield Tane84e6f92019-08-29 17:28:41 -0700749KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
751
752 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700753 uint32_t policyFlags = entry->policyFlags &
754 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 if (entry->refCount == 1) {
756 entry->recycle();
757 entry->eventTime = currentTime;
758 entry->policyFlags = policyFlags;
759 entry->repeatCount += 1;
760 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700761 KeyEntry* newEntry =
762 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId,
763 entry->source, entry->displayId, policyFlags, entry->action,
764 entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
765 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766
767 mKeyRepeatState.lastKeyEntry = newEntry;
768 entry->release();
769
770 entry = newEntry;
771 }
772 entry->syntheticRepeat = true;
773
774 // Increment reference count since we keep a reference to the event in
775 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
776 entry->refCount += 1;
777
778 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
779 return entry;
780}
781
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700782bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
783 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700785 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786#endif
787
788 // Reset key repeating in case a keyboard device was added or removed or something.
789 resetKeyRepeatLocked();
790
791 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700792 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
793 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700795 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796 return true;
797}
798
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700799bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700801 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700802 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803#endif
804
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 options.deviceId = entry->deviceId;
807 synthesizeCancelationEventsForAllConnectionsLocked(options);
808 return true;
809}
810
811bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700814 if (!entry->dispatchInProgress) {
815 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
816 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
817 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
818 if (mKeyRepeatState.lastKeyEntry &&
819 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820 // We have seen two identical key downs in a row which indicates that the device
821 // driver is automatically generating key repeats itself. We take note of the
822 // repeat here, but we disable our own next key repeat timer since it is clear that
823 // we will not need to synthesize key repeats ourselves.
824 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
825 resetKeyRepeatLocked();
826 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
827 } else {
828 // Not a repeat. Save key down state in case we do see a repeat later.
829 resetKeyRepeatLocked();
830 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
831 }
832 mKeyRepeatState.lastKeyEntry = entry;
833 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700834 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835 resetKeyRepeatLocked();
836 }
837
838 if (entry->repeatCount == 1) {
839 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
840 } else {
841 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
842 }
843
844 entry->dispatchInProgress = true;
845
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700846 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 }
848
849 // Handle case where the policy asked us to try again later last time.
850 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
851 if (currentTime < entry->interceptKeyWakeupTime) {
852 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
853 *nextWakeupTime = entry->interceptKeyWakeupTime;
854 }
855 return false; // wait until next wakeup
856 }
857 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
858 entry->interceptKeyWakeupTime = 0;
859 }
860
861 // Give the policy a chance to intercept the key.
862 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
863 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700864 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -0700865 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800866 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700867 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +0800868 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700869 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 }
871 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700872 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 entry->refCount += 1;
874 return false; // wait for the command to run
875 } else {
876 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
877 }
878 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700879 if (*dropReason == DropReason::NOT_DROPPED) {
880 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 }
882 }
883
884 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700885 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700886 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700887 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800889 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 return true;
891 }
892
893 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800894 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700895 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700896 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
898 return false;
899 }
900
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800901 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
903 return true;
904 }
905
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800906 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700907 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908
909 // Dispatch the key.
910 dispatchEventLocked(currentTime, entry, inputTargets);
911 return true;
912}
913
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700914void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800915#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100916 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700917 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
918 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700919 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
920 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
921 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922#endif
923}
924
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700925bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
926 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000927 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700929 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 entry->dispatchInProgress = true;
931
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700932 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 }
934
935 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700936 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700937 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700938 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700939 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 return true;
941 }
942
943 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
944
945 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800946 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947
948 bool conflictingPointerActions = false;
949 int32_t injectionResult;
950 if (isPointerEvent) {
951 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700953 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700954 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 } else {
956 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700957 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700958 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959 }
960 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
961 return false;
962 }
963
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800964 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100966 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700967 CancelationOptions::Mode mode(isPointerEvent
968 ? CancelationOptions::CANCEL_POINTER_EVENTS
969 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100970 CancelationOptions options(mode, "input event injection failed");
971 synthesizeCancelationEventsForMonitorsLocked(options);
972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 return true;
974 }
975
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800976 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700977 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800979 if (isPointerEvent) {
980 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
981 if (stateIndex >= 0) {
982 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800983 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800984 // The event has gone through these portal windows, so we add monitoring targets of
985 // the corresponding displays as well.
986 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800987 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +0000988 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800990 }
991 }
992 }
993 }
994
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995 // Dispatch the motion.
996 if (conflictingPointerActions) {
997 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700998 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 synthesizeCancelationEventsForAllConnectionsLocked(options);
1000 }
1001 dispatchEventLocked(currentTime, entry, inputTargets);
1002 return true;
1003}
1004
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001005void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001007 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001008 ", policyFlags=0x%x, "
1009 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1010 "metaState=0x%x, buttonState=0x%x,"
1011 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001012 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1013 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1014 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001016 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001018 "x=%f, y=%f, pressure=%f, size=%f, "
1019 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1020 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001021 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1022 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1023 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1024 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1025 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1026 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1027 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1028 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1029 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1030 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031 }
1032#endif
1033}
1034
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001035void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1036 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001037 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038#if DEBUG_DISPATCH_CYCLE
1039 ALOGD("dispatchEventToCurrentInputTargets");
1040#endif
1041
1042 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1043
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001044 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001046 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001047 sp<Connection> connection =
1048 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001049 if (connection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1051 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001052 if (DEBUG_FOCUS) {
1053 ALOGD("Dropping event delivery to target with channel '%s' because it "
1054 "is no longer registered with the input dispatcher.",
1055 inputTarget.inputChannel->getName().c_str());
1056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 }
1058 }
1059}
1060
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001061int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001062 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001064 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001065 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001067 if (DEBUG_FOCUS) {
1068 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1071 mInputTargetWaitStartTime = currentTime;
1072 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1073 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001074 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075 }
1076 } else {
1077 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001078 if (DEBUG_FOCUS) {
1079 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
1080 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001083 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001085 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 timeout =
1087 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 } else {
1089 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1090 }
1091
1092 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1093 mInputTargetWaitStartTime = currentTime;
1094 mInputTargetWaitTimeoutTime = currentTime + timeout;
1095 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001096 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097
Yi Kong9b14ac62018-07-17 13:48:38 -07001098 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001099 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100 }
Robert Carr740167f2018-10-11 19:03:41 -07001101 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1102 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001103 }
1104 }
1105 }
1106
1107 if (mInputTargetWaitTimeoutExpired) {
1108 return INPUT_EVENT_INJECTION_TIMED_OUT;
1109 }
1110
1111 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001112 onANRLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001113 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114
1115 // Force poll loop to wake up immediately on next iteration once we get the
1116 // ANR response back from the policy.
1117 *nextWakeupTime = LONG_LONG_MIN;
1118 return INPUT_EVENT_INJECTION_PENDING;
1119 } else {
1120 // Force poll loop to wake up when timeout is due.
1121 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1122 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1123 }
1124 return INPUT_EVENT_INJECTION_PENDING;
1125 }
1126}
1127
Robert Carr803535b2018-08-02 16:38:15 -07001128void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1129 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1130 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1131 state.removeWindowByToken(token);
1132 }
1133}
1134
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001135void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001136 nsecs_t newTimeout, const sp<IBinder>& inputConnectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 if (newTimeout > 0) {
1138 // Extend the timeout.
1139 mInputTargetWaitTimeoutTime = now() + newTimeout;
1140 } else {
1141 // Give up.
1142 mInputTargetWaitTimeoutExpired = true;
1143
1144 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001145 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001146 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001147 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001149 if (connection->status == Connection::STATUS_NORMAL) {
1150 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1151 "application not responding");
1152 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 }
1154 }
1155 }
1156}
1157
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001158nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1160 return currentTime - mInputTargetWaitStartTime;
1161 }
1162 return 0;
1163}
1164
1165void InputDispatcher::resetANRTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001166 if (DEBUG_FOCUS) {
1167 ALOGD("Resetting ANR timeouts.");
1168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169
1170 // Reset input target wait timeout.
1171 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001172 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173}
1174
Tiger Huang721e26f2018-07-24 22:26:19 +08001175/**
1176 * Get the display id that the given event should go to. If this event specifies a valid display id,
1177 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1178 * Focused display is the display that the user most recently interacted with.
1179 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001180int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001181 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001182 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001183 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001184 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1185 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001186 break;
1187 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001188 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001189 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1190 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001191 break;
1192 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001193 case EventEntry::Type::CONFIGURATION_CHANGED:
1194 case EventEntry::Type::DEVICE_RESET: {
1195 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001196 return ADISPLAY_ID_NONE;
1197 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001198 }
1199 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1200}
1201
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001203 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001204 std::vector<InputTarget>& inputTargets,
1205 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001207 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208
Tiger Huang721e26f2018-07-24 22:26:19 +08001209 int32_t displayId = getTargetDisplayId(entry);
1210 sp<InputWindowHandle> focusedWindowHandle =
1211 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1212 sp<InputApplicationHandle> focusedApplicationHandle =
1213 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1214
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 // If there is no currently focused window and no focused application
1216 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001217 if (focusedWindowHandle == nullptr) {
1218 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001219 injectionResult =
1220 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1221 nullptr, nextWakeupTime,
1222 "Waiting because no window has focus but there is "
1223 "a focused application that may eventually add a "
1224 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 goto Unresponsive;
1226 }
1227
Arthur Hung3b413f22018-10-26 18:05:34 +08001228 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229 "%" PRId32 ".",
1230 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1232 goto Failed;
1233 }
1234
1235 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001236 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1238 goto Failed;
1239 }
1240
Jeff Brownffb49772014-10-10 19:01:34 -07001241 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001242 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001243 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001244 injectionResult =
1245 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1246 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 goto Unresponsive;
1248 }
1249
1250 // Success! Output targets.
1251 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001252 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001253 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1254 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255
1256 // Done.
1257Failed:
1258Unresponsive:
1259 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001260 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001261 if (DEBUG_FOCUS) {
1262 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1263 "timeSpentWaitingForApplication=%0.1fms",
1264 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 return injectionResult;
1267}
1268
1269int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001270 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001271 std::vector<InputTarget>& inputTargets,
1272 nsecs_t* nextWakeupTime,
1273 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001274 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 enum InjectionPermission {
1276 INJECTION_PERMISSION_UNKNOWN,
1277 INJECTION_PERMISSION_GRANTED,
1278 INJECTION_PERMISSION_DENIED
1279 };
1280
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 // For security reasons, we defer updating the touch state until we are sure that
1282 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001283 int32_t displayId = entry.displayId;
1284 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1286
1287 // Update the touch state as needed based on the properties of the touch event.
1288 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1289 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1290 sp<InputWindowHandle> newHoverWindowHandle;
1291
Jeff Brownf086ddb2014-02-11 14:28:48 -08001292 // Copy current touch state into mTempTouchState.
1293 // This state is always reset at the end of this function, so if we don't find state
1294 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001295 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001296 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1297 if (oldStateIndex >= 0) {
1298 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1299 mTempTouchState.copyFrom(*oldState);
1300 }
1301
1302 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001304 (mTempTouchState.deviceId != entry.deviceId || mTempTouchState.source != entry.source ||
1305 mTempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001306 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1307 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1308 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1309 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1310 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001311 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312 bool wrongDevice = false;
1313 if (newGesture) {
1314 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001315 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001316 if (DEBUG_FOCUS) {
1317 ALOGD("Dropping event because a pointer for a different device is already down "
1318 "in display %" PRId32,
1319 displayId);
1320 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001321 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1323 switchedDevice = false;
1324 wrongDevice = true;
1325 goto Failed;
1326 }
1327 mTempTouchState.reset();
1328 mTempTouchState.down = down;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001329 mTempTouchState.deviceId = entry.deviceId;
1330 mTempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 mTempTouchState.displayId = displayId;
1332 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001333 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001334 if (DEBUG_FOCUS) {
1335 ALOGI("Dropping move event because a pointer for a different device is already active "
1336 "in display %" PRId32,
1337 displayId);
1338 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001339 // TODO: test multiple simultaneous input streams.
1340 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1341 switchedDevice = false;
1342 wrongDevice = true;
1343 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 }
1345
1346 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1347 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1348
Garfield Tan00f511d2019-06-12 16:55:40 -07001349 int32_t x;
1350 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001352 // Always dispatch mouse events to cursor position.
1353 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001354 x = int32_t(entry.xCursorPosition);
1355 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001356 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001357 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1358 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001359 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001360 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001361 sp<InputWindowHandle> newTouchedWindowHandle =
1362 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1363 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001364
1365 std::vector<TouchedMonitor> newGestureMonitors = isDown
1366 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1367 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001368
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001370 if (newTouchedWindowHandle != nullptr &&
1371 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001372 // New window supports splitting, but we should never split mouse events.
1373 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374 } else if (isSplit) {
1375 // New window does not support splitting but we have already split events.
1376 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001377 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 }
1379
1380 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001381 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 // Try to assign the pointer to the first foreground window we find, if there is one.
1383 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001384 }
1385
1386 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1387 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001388 "(%d, %d) in display %" PRId32 ".",
1389 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001390 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1391 goto Failed;
1392 }
1393
1394 if (newTouchedWindowHandle != nullptr) {
1395 // Set target flags.
1396 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1397 if (isSplit) {
1398 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001400 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1401 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1402 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1403 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1404 }
1405
1406 // Update hover state.
1407 if (isHoverAction) {
1408 newHoverWindowHandle = newTouchedWindowHandle;
1409 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1410 newHoverWindowHandle = mLastHoverWindowHandle;
1411 }
1412
1413 // Update the temporary touch state.
1414 BitSet32 pointerIds;
1415 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001416 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001417 pointerIds.markBit(pointerId);
1418 }
1419 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420 }
1421
Michael Wright3dd60e22019-03-27 22:06:44 +00001422 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 } else {
1424 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1425
1426 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001427 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001428 if (DEBUG_FOCUS) {
1429 ALOGD("Dropping event because the pointer is not down or we previously "
1430 "dropped the pointer down event in display %" PRId32,
1431 displayId);
1432 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1434 goto Failed;
1435 }
1436
1437 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001438 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001439 mTempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001440 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1441 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442
1443 sp<InputWindowHandle> oldTouchedWindowHandle =
1444 mTempTouchState.getFirstForegroundWindowHandle();
1445 sp<InputWindowHandle> newTouchedWindowHandle =
1446 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001447 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1448 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001449 if (DEBUG_FOCUS) {
1450 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1451 oldTouchedWindowHandle->getName().c_str(),
1452 newTouchedWindowHandle->getName().c_str(), displayId);
1453 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 // Make a slippery exit from the old window.
1455 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001456 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1457 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458
1459 // Make a slippery entrance into the new window.
1460 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1461 isSplit = true;
1462 }
1463
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001464 int32_t targetFlags =
1465 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 if (isSplit) {
1467 targetFlags |= InputTarget::FLAG_SPLIT;
1468 }
1469 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1470 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1471 }
1472
1473 BitSet32 pointerIds;
1474 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001475 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 }
1477 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1478 }
1479 }
1480 }
1481
1482 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1483 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001484 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485#if DEBUG_HOVER
1486 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001487 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488#endif
1489 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001490 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1491 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 }
1493
1494 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001495 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496#if DEBUG_HOVER
1497 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001498 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499#endif
1500 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001501 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1502 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 }
1504 }
1505
1506 // Check permission to inject into all touched foreground windows and ensure there
1507 // is at least one touched foreground window.
1508 {
1509 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001510 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1512 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001513 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1515 injectionPermission = INJECTION_PERMISSION_DENIED;
1516 goto Failed;
1517 }
1518 }
1519 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001520 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1521 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001522 if (DEBUG_FOCUS) {
1523 ALOGD("Dropping event because there is no touched foreground window in display "
1524 "%" PRId32 " or gesture monitor to receive it.",
1525 displayId);
1526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1528 goto Failed;
1529 }
1530
1531 // Permission granted to injection into all touched foreground windows.
1532 injectionPermission = INJECTION_PERMISSION_GRANTED;
1533 }
1534
1535 // Check whether windows listening for outside touches are owned by the same UID. If it is
1536 // set the policy flag that we will not reveal coordinate information to this window.
1537 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1538 sp<InputWindowHandle> foregroundWindowHandle =
1539 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001540 if (foregroundWindowHandle) {
1541 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1542 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1543 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1544 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1545 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1546 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001547 InputTarget::FLAG_ZERO_COORDS,
1548 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 }
1551 }
1552 }
1553 }
1554
1555 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001556 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001558 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001559 std::string reason =
1560 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1561 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001562 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001563 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1564 touchedWindow.windowHandle,
1565 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 goto Unresponsive;
1567 }
1568 }
1569 }
1570
1571 // If this is the first pointer going down and the touched window has a wallpaper
1572 // then also add the touched wallpaper windows so they are locked in for the duration
1573 // of the touch gesture.
1574 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1575 // engine only supports touch events. We would need to add a mechanism similar
1576 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1577 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1578 sp<InputWindowHandle> foregroundWindowHandle =
1579 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001580 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001581 const std::vector<sp<InputWindowHandle>> windowHandles =
1582 getWindowHandlesLocked(displayId);
1583 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001585 if (info->displayId == displayId &&
1586 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1587 mTempTouchState
1588 .addOrUpdateWindow(windowHandle,
1589 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1590 InputTarget::
1591 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1592 InputTarget::FLAG_DISPATCH_AS_IS,
1593 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 }
1595 }
1596 }
1597 }
1598
1599 // Success! Output targets.
1600 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1601
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001602 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001604 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 }
1606
Michael Wright3dd60e22019-03-27 22:06:44 +00001607 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1608 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001609 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001610 }
1611
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 // Drop the outside or hover touch windows since we will not care about them
1613 // in the next iteration.
1614 mTempTouchState.filterNonAsIsTouchWindows();
1615
1616Failed:
1617 // Check injection permission once and for all.
1618 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001619 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 injectionPermission = INJECTION_PERMISSION_GRANTED;
1621 } else {
1622 injectionPermission = INJECTION_PERMISSION_DENIED;
1623 }
1624 }
1625
1626 // Update final pieces of touch state if the injector had permission.
1627 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1628 if (!wrongDevice) {
1629 if (switchedDevice) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001630 if (DEBUG_FOCUS) {
1631 ALOGD("Conflicting pointer actions: Switched to a different device.");
1632 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633 *outConflictingPointerActions = true;
1634 }
1635
1636 if (isHoverAction) {
1637 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001638 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001639 if (DEBUG_FOCUS) {
1640 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1641 "down.");
1642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 *outConflictingPointerActions = true;
1644 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001645 mTempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001646 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1647 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001648 mTempTouchState.deviceId = entry.deviceId;
1649 mTempTouchState.source = entry.source;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001650 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001652 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1653 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001655 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1657 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001658 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001659 if (DEBUG_FOCUS) {
1660 ALOGD("Conflicting pointer actions: Down received while already down.");
1661 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 *outConflictingPointerActions = true;
1663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1665 // One pointer went up.
1666 if (isSplit) {
1667 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001668 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001670 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001671 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1673 touchedWindow.pointerIds.clearBit(pointerId);
1674 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001675 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 continue;
1677 }
1678 }
1679 i += 1;
1680 }
1681 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001682 }
1683
1684 // Save changes unless the action was scroll in which case the temporary touch
1685 // state was only valid for this one action.
1686 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1687 if (mTempTouchState.displayId >= 0) {
1688 if (oldStateIndex >= 0) {
1689 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1690 } else {
1691 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1692 }
1693 } else if (oldStateIndex >= 0) {
1694 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1695 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 }
1697
1698 // Update hover state.
1699 mLastHoverWindowHandle = newHoverWindowHandle;
1700 }
1701 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001702 if (DEBUG_FOCUS) {
1703 ALOGD("Not updating touch focus because injection was denied.");
1704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 }
1706
1707Unresponsive:
1708 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1709 mTempTouchState.reset();
1710
1711 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001712 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001713 if (DEBUG_FOCUS) {
1714 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1715 "timeSpentWaitingForApplication=%0.1fms",
1716 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 return injectionResult;
1719}
1720
1721void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001722 int32_t targetFlags, BitSet32 pointerIds,
1723 std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001724 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1725 if (inputChannel == nullptr) {
1726 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1727 return;
1728 }
1729
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001731 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001732 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 target.flags = targetFlags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001734 target.xOffset = -windowInfo->frameLeft;
1735 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001736 target.globalScaleFactor = windowInfo->globalScaleFactor;
1737 target.windowXScale = windowInfo->windowXScale;
1738 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001740 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741}
1742
Michael Wright3dd60e22019-03-27 22:06:44 +00001743void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001744 int32_t displayId, float xOffset,
1745 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001746 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1747 mGlobalMonitorsByDisplay.find(displayId);
1748
1749 if (it != mGlobalMonitorsByDisplay.end()) {
1750 const std::vector<Monitor>& monitors = it->second;
1751 for (const Monitor& monitor : monitors) {
1752 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 }
1755}
1756
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001757void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1758 float yOffset,
1759 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001760 InputTarget target;
1761 target.inputChannel = monitor.inputChannel;
1762 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1763 target.xOffset = xOffset;
1764 target.yOffset = yOffset;
1765 target.pointerIds.clear();
1766 target.globalScaleFactor = 1.0f;
1767 inputTargets.push_back(target);
1768}
1769
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001771 const InjectionState* injectionState) {
1772 if (injectionState &&
1773 (windowHandle == nullptr ||
1774 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1775 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001776 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001778 "owned by uid %d",
1779 injectionState->injectorPid, injectionState->injectorUid,
1780 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 } else {
1782 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001783 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 }
1785 return false;
1786 }
1787 return true;
1788}
1789
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001790bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1791 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001793 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1794 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 if (otherHandle == windowHandle) {
1796 break;
1797 }
1798
1799 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001800 if (otherInfo->displayId == displayId && otherInfo->visible &&
1801 !otherInfo->isTrustedOverlay() && otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 return true;
1803 }
1804 }
1805 return false;
1806}
1807
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001808bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1809 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001810 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001811 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001812 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001813 if (otherHandle == windowHandle) {
1814 break;
1815 }
1816
1817 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001818 if (otherInfo->displayId == displayId && otherInfo->visible &&
1819 !otherInfo->isTrustedOverlay() && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001820 return true;
1821 }
1822 }
1823 return false;
1824}
1825
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001826std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
1827 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001828 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07001829 // If the window is paused then keep waiting.
1830 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001831 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001832 }
1833
1834 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001835 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001836 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001837 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001838 "registered with the input dispatcher. The window may be in the "
1839 "process of being removed.",
1840 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001841 }
1842
1843 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07001844 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001845 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001846 "The window may be in the process of being removed.",
1847 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07001848 }
1849
1850 // If the connection is backed up then keep waiting.
1851 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001852 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001853 "Outbound queue length: %zu. Wait queue length: %zu.",
1854 targetType, connection->outboundQueue.size(),
1855 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07001856 }
1857
1858 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001859 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07001860 // If the event is a key event, then we must wait for all previous events to
1861 // complete before delivering it because previous events may have the
1862 // side-effect of transferring focus to a different window and we want to
1863 // ensure that the following keys are sent to the new window.
1864 //
1865 // Suppose the user touches a button in a window then immediately presses "A".
1866 // If the button causes a pop-up window to appear then we want to ensure that
1867 // the "A" key is delivered to the new pop-up window. This is because users
1868 // often anticipate pending UI changes when typing on a keyboard.
1869 // To obtain this behavior, we must serialize key events with respect to all
1870 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001871 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001872 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001873 "finished processing all of the input events that were previously "
1874 "delivered to it. Outbound queue length: %zu. Wait queue length: "
1875 "%zu.",
1876 targetType, connection->outboundQueue.size(),
1877 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878 }
Jeff Brownffb49772014-10-10 19:01:34 -07001879 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880 // Touch events can always be sent to a window immediately because the user intended
1881 // to touch whatever was visible at the time. Even if focus changes or a new
1882 // window appears moments later, the touch event was meant to be delivered to
1883 // whatever window happened to be on screen at the time.
1884 //
1885 // Generic motion events, such as trackball or joystick events are a little trickier.
1886 // Like key events, generic motion events are delivered to the focused window.
1887 // Unlike key events, generic motion events don't tend to transfer focus to other
1888 // windows and it is not important for them to be serialized. So we prefer to deliver
1889 // generic motion events as soon as possible to improve efficiency and reduce lag
1890 // through batching.
1891 //
1892 // The one case where we pause input event delivery is when the wait queue is piling
1893 // up with lots of events because the application is not responding.
1894 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001895 if (!connection->waitQueue.empty() &&
1896 currentTime >=
1897 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001898 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001899 "finished processing certain input events that were delivered to "
1900 "it over "
1901 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
1902 "%0.1fms.",
1903 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1904 connection->waitQueue.size(),
1905 (currentTime - connection->waitQueue.front()->deliveryTime) *
1906 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 }
1908 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001909 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910}
1911
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001912std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913 const sp<InputApplicationHandle>& applicationHandle,
1914 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001915 if (applicationHandle != nullptr) {
1916 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001917 std::string label(applicationHandle->getName());
1918 label += " - ";
1919 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920 return label;
1921 } else {
1922 return applicationHandle->getName();
1923 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001924 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 return windowHandle->getName();
1926 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001927 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 }
1929}
1930
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001931void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001932 int32_t displayId = getTargetDisplayId(eventEntry);
1933 sp<InputWindowHandle> focusedWindowHandle =
1934 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1935 if (focusedWindowHandle != nullptr) {
1936 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1938#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001939 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940#endif
1941 return;
1942 }
1943 }
1944
1945 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001946 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001947 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001948 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
1949 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001950 return;
1951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001953 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001954 eventType = USER_ACTIVITY_EVENT_TOUCH;
1955 }
1956 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001958 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001959 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
1960 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001961 return;
1962 }
1963 eventType = USER_ACTIVITY_EVENT_BUTTON;
1964 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001966 case EventEntry::Type::CONFIGURATION_CHANGED:
1967 case EventEntry::Type::DEVICE_RESET: {
1968 LOG_ALWAYS_FATAL("%s events are not user activity",
1969 EventEntry::typeToString(eventEntry.type));
1970 break;
1971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 }
1973
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001974 std::unique_ptr<CommandEntry> commandEntry =
1975 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001976 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001978 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979}
1980
1981void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001982 const sp<Connection>& connection,
1983 EventEntry* eventEntry,
1984 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001985 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001986 std::string message =
1987 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
1988 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00001989 ATRACE_NAME(message.c_str());
1990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991#if DEBUG_DISPATCH_CYCLE
1992 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001993 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1994 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
1995 connection->getInputChannelName().c_str(), inputTarget->flags, inputTarget->xOffset,
1996 inputTarget->yOffset, inputTarget->globalScaleFactor, inputTarget->windowXScale,
1997 inputTarget->windowYScale, inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998#endif
1999
2000 // Skip this event if the connection status is not normal.
2001 // We don't want to enqueue additional outbound events if the connection is broken.
2002 if (connection->status != Connection::STATUS_NORMAL) {
2003#if DEBUG_DISPATCH_CYCLE
2004 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002005 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006#endif
2007 return;
2008 }
2009
2010 // Split a motion event if needed.
2011 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002012 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002014 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
2015 if (inputTarget->pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002016 MotionEntry* splitMotionEntry =
2017 splitMotionEvent(originalMotionEntry, inputTarget->pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 if (!splitMotionEntry) {
2019 return; // split event was dropped
2020 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002021 if (DEBUG_FOCUS) {
2022 ALOGD("channel '%s' ~ Split motion event.",
2023 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002024 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002025 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002026 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 splitMotionEntry->release();
2028 return;
2029 }
2030 }
2031
2032 // Not splitting. Enqueue dispatch entries for the event as is.
2033 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2034}
2035
2036void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002037 const sp<Connection>& connection,
2038 EventEntry* eventEntry,
2039 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002040 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002041 std::string message =
2042 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32
2043 ")",
2044 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002045 ATRACE_NAME(message.c_str());
2046 }
2047
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002048 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049
2050 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002051 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002052 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002053 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002054 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002055 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002056 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002057 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002058 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002059 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002060 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002061 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002062 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063
2064 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002065 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066 startDispatchCycleLocked(currentTime, connection);
2067 }
2068}
2069
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002070void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2071 EventEntry* eventEntry,
2072 const InputTarget* inputTarget,
2073 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002074 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002075 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2076 connection->getInputChannelName().c_str(),
2077 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002078 ATRACE_NAME(message.c_str());
2079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 int32_t inputTargetFlags = inputTarget->flags;
2081 if (!(inputTargetFlags & dispatchMode)) {
2082 return;
2083 }
2084 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2085
2086 // This is a new event.
2087 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002088 DispatchEntry* dispatchEntry =
2089 new DispatchEntry(eventEntry, // increments ref
2090 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
2091 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2092 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093
2094 // Apply target flags and update the connection's input state.
2095 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002096 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002097 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
2098 dispatchEntry->resolvedAction = keyEntry.action;
2099 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002101 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2102 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002104 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2105 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002107 delete dispatchEntry;
2108 return; // skip the inconsistent event
2109 }
2110 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002113 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002114 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002115 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2116 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2117 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2118 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2119 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2120 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2121 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2122 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2123 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2124 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2125 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002126 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002127 }
2128 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002129 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2130 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002132 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2133 "event",
2134 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002136 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002139 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002140 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2141 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2142 }
2143 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2144 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2145 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002147 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2148 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002150 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2151 "event",
2152 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002154 delete dispatchEntry;
2155 return; // skip the inconsistent event
2156 }
2157
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002158 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002159 inputTarget->inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002160
2161 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002163 case EventEntry::Type::CONFIGURATION_CHANGED:
2164 case EventEntry::Type::DEVICE_RESET: {
2165 LOG_ALWAYS_FATAL("%s events should not go to apps",
2166 EventEntry::typeToString(eventEntry->type));
2167 break;
2168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 }
2170
2171 // Remember that we are waiting for this dispatch to complete.
2172 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002173 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174 }
2175
2176 // Enqueue the dispatch entry.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002177 connection->outboundQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002178 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002179}
2180
chaviwfd6d3512019-03-25 13:23:49 -07002181void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002182 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002183 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002184 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2185 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002186 return;
2187 }
2188
2189 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2190 if (inputWindowHandle == nullptr) {
2191 return;
2192 }
2193
chaviw8c9cf542019-03-25 13:02:48 -07002194 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002195 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002196
2197 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2198
2199 if (!hasFocusChanged) {
2200 return;
2201 }
2202
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002203 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2204 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002205 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002206 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207}
2208
2209void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002210 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002211 if (ATRACE_ENABLED()) {
2212 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002213 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002214 ATRACE_NAME(message.c_str());
2215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002217 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218#endif
2219
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002220 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2221 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 dispatchEntry->deliveryTime = currentTime;
2223
2224 // Publish the event.
2225 status_t status;
2226 EventEntry* eventEntry = dispatchEntry->eventEntry;
2227 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002228 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002229 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002231 // Publish the key event.
2232 status = connection->inputPublisher
2233 .publishKeyEvent(dispatchEntry->seq, keyEntry->deviceId,
2234 keyEntry->source, keyEntry->displayId,
2235 dispatchEntry->resolvedAction,
2236 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2237 keyEntry->scanCode, keyEntry->metaState,
2238 keyEntry->repeatCount, keyEntry->downTime,
2239 keyEntry->eventTime);
2240 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241 }
2242
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002243 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002244 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002246 PointerCoords scaledCoords[MAX_POINTERS];
2247 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2248
2249 // Set the X and Y offset depending on the input source.
2250 float xOffset, yOffset;
2251 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2252 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2253 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2254 float wxs = dispatchEntry->windowXScale;
2255 float wys = dispatchEntry->windowYScale;
2256 xOffset = dispatchEntry->xOffset * wxs;
2257 yOffset = dispatchEntry->yOffset * wys;
2258 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
2259 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2260 scaledCoords[i] = motionEntry->pointerCoords[i];
2261 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
2262 }
2263 usingCoords = scaledCoords;
2264 }
2265 } else {
2266 xOffset = 0.0f;
2267 yOffset = 0.0f;
2268
2269 // We don't want the dispatch target to know.
2270 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2271 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2272 scaledCoords[i].clear();
2273 }
2274 usingCoords = scaledCoords;
2275 }
2276 }
2277
2278 // Publish the motion event.
2279 status = connection->inputPublisher
2280 .publishMotionEvent(dispatchEntry->seq, motionEntry->deviceId,
2281 motionEntry->source, motionEntry->displayId,
2282 dispatchEntry->resolvedAction,
2283 motionEntry->actionButton,
2284 dispatchEntry->resolvedFlags,
2285 motionEntry->edgeFlags, motionEntry->metaState,
2286 motionEntry->buttonState,
2287 motionEntry->classification, xOffset, yOffset,
2288 motionEntry->xPrecision,
2289 motionEntry->yPrecision,
2290 motionEntry->xCursorPosition,
2291 motionEntry->yCursorPosition,
2292 motionEntry->downTime, motionEntry->eventTime,
2293 motionEntry->pointerCount,
2294 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002295 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002296 break;
2297 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002298 case EventEntry::Type::CONFIGURATION_CHANGED:
2299 case EventEntry::Type::DEVICE_RESET: {
2300 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2301 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002302 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002303 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 }
2305
2306 // Check the result.
2307 if (status) {
2308 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002309 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002311 "This is unexpected because the wait queue is empty, so the pipe "
2312 "should be empty and we shouldn't have any problems writing an "
2313 "event to it, status=%d",
2314 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2316 } else {
2317 // Pipe is full and we are waiting for the app to finish process some events
2318 // before sending more events to it.
2319#if DEBUG_DISPATCH_CYCLE
2320 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002321 "waiting for the application to catch up",
2322 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323#endif
2324 connection->inputPublisherBlocked = true;
2325 }
2326 } else {
2327 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002328 "status=%d",
2329 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2331 }
2332 return;
2333 }
2334
2335 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002336 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2337 connection->outboundQueue.end(),
2338 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002339 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002340 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002341 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342 }
2343}
2344
2345void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002346 const sp<Connection>& connection, uint32_t seq,
2347 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348#if DEBUG_DISPATCH_CYCLE
2349 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002350 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351#endif
2352
2353 connection->inputPublisherBlocked = false;
2354
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002355 if (connection->status == Connection::STATUS_BROKEN ||
2356 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357 return;
2358 }
2359
2360 // Notify other system components and prepare to start the next dispatch cycle.
2361 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2362}
2363
2364void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002365 const sp<Connection>& connection,
2366 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367#if DEBUG_DISPATCH_CYCLE
2368 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002369 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370#endif
2371
2372 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002373 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002374 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002375 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002376 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377
2378 // The connection appears to be unrecoverably broken.
2379 // Ignore already broken or zombie connections.
2380 if (connection->status == Connection::STATUS_NORMAL) {
2381 connection->status = Connection::STATUS_BROKEN;
2382
2383 if (notify) {
2384 // Notify other system components.
2385 onDispatchCycleBrokenLocked(currentTime, connection);
2386 }
2387 }
2388}
2389
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002390void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2391 while (!queue.empty()) {
2392 DispatchEntry* dispatchEntry = queue.front();
2393 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002394 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 }
2396}
2397
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002398void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002400 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401 }
2402 delete dispatchEntry;
2403}
2404
2405int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2406 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2407
2408 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002409 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002411 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002413 "fd=%d, events=0x%x",
2414 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415 return 0; // remove the callback
2416 }
2417
2418 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002419 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2421 if (!(events & ALOOPER_EVENT_INPUT)) {
2422 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002423 "events=0x%x",
2424 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 return 1;
2426 }
2427
2428 nsecs_t currentTime = now();
2429 bool gotOne = false;
2430 status_t status;
2431 for (;;) {
2432 uint32_t seq;
2433 bool handled;
2434 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2435 if (status) {
2436 break;
2437 }
2438 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2439 gotOne = true;
2440 }
2441 if (gotOne) {
2442 d->runCommandsLockedInterruptible();
2443 if (status == WOULD_BLOCK) {
2444 return 1;
2445 }
2446 }
2447
2448 notify = status != DEAD_OBJECT || !connection->monitor;
2449 if (notify) {
2450 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002451 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 }
2453 } else {
2454 // Monitor channels are never explicitly unregistered.
2455 // We do it automatically when the remote endpoint is closed so don't warn
2456 // about them.
2457 notify = !connection->monitor;
2458 if (notify) {
2459 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002460 "events=0x%x",
2461 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 }
2463 }
2464
2465 // Unregister the channel.
2466 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2467 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002468 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469}
2470
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002471void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002473 for (const auto& pair : mConnectionsByFd) {
2474 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475 }
2476}
2477
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002478void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002479 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002480 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2481 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2482}
2483
2484void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2485 const CancelationOptions& options,
2486 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2487 for (const auto& it : monitorsByDisplay) {
2488 const std::vector<Monitor>& monitors = it.second;
2489 for (const Monitor& monitor : monitors) {
2490 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002491 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002492 }
2493}
2494
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2496 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002497 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002498 if (connection == nullptr) {
2499 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002501
2502 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503}
2504
2505void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2506 const sp<Connection>& connection, const CancelationOptions& options) {
2507 if (connection->status == Connection::STATUS_BROKEN) {
2508 return;
2509 }
2510
2511 nsecs_t currentTime = now();
2512
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002513 std::vector<EventEntry*> cancelationEvents =
2514 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002516 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002518 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002519 "with reality: %s, mode=%d.",
2520 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2521 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522#endif
2523 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002524 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 switch (cancelationEventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002526 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002527 logOutboundKeyDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002528 static_cast<const KeyEntry&>(*cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002529 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002530 }
2531 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002532 logOutboundMotionDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002533 static_cast<const MotionEntry&>(
2534 *cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002535 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002536 }
2537 case EventEntry::Type::CONFIGURATION_CHANGED:
2538 case EventEntry::Type::DEVICE_RESET: {
2539 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2540 EventEntry::typeToString(cancelationEventEntry->type));
2541 break;
2542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543 }
2544
2545 InputTarget target;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002546 sp<InputWindowHandle> windowHandle =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002547 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002548 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2550 target.xOffset = -windowInfo->frameLeft;
2551 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002552 target.globalScaleFactor = windowInfo->globalScaleFactor;
2553 target.windowXScale = windowInfo->windowXScale;
2554 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555 } else {
2556 target.xOffset = 0;
2557 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002558 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 }
2560 target.inputChannel = connection->inputChannel;
2561 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2562
chaviw8c9cf542019-03-25 13:02:48 -07002563 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002564 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565
2566 cancelationEventEntry->release();
2567 }
2568
2569 startDispatchCycleLocked(currentTime, connection);
2570 }
2571}
2572
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002573MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002574 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575 ALOG_ASSERT(pointerIds.value != 0);
2576
2577 uint32_t splitPointerIndexMap[MAX_POINTERS];
2578 PointerProperties splitPointerProperties[MAX_POINTERS];
2579 PointerCoords splitPointerCoords[MAX_POINTERS];
2580
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002581 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 uint32_t splitPointerCount = 0;
2583
2584 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002585 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002587 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588 uint32_t pointerId = uint32_t(pointerProperties.id);
2589 if (pointerIds.hasBit(pointerId)) {
2590 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2591 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2592 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002593 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594 splitPointerCount += 1;
2595 }
2596 }
2597
2598 if (splitPointerCount != pointerIds.count()) {
2599 // This is bad. We are missing some of the pointers that we expected to deliver.
2600 // Most likely this indicates that we received an ACTION_MOVE events that has
2601 // different pointer ids than we expected based on the previous ACTION_DOWN
2602 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2603 // in this way.
2604 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002605 "we expected there to be %d pointers. This probably means we received "
2606 "a broken sequence of pointer ids from the input device.",
2607 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002608 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 }
2610
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002611 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002613 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2614 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2616 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002617 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618 uint32_t pointerId = uint32_t(pointerProperties.id);
2619 if (pointerIds.hasBit(pointerId)) {
2620 if (pointerIds.count() == 1) {
2621 // The first/last pointer went down/up.
2622 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002623 ? AMOTION_EVENT_ACTION_DOWN
2624 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 } else {
2626 // A secondary pointer went down/up.
2627 uint32_t splitPointerIndex = 0;
2628 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2629 splitPointerIndex += 1;
2630 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002631 action = maskedAction |
2632 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002633 }
2634 } else {
2635 // An unrelated pointer changed.
2636 action = AMOTION_EVENT_ACTION_MOVE;
2637 }
2638 }
2639
Garfield Tan00f511d2019-06-12 16:55:40 -07002640 MotionEntry* splitMotionEntry =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002641 new MotionEntry(originalMotionEntry.sequenceNum, originalMotionEntry.eventTime,
2642 originalMotionEntry.deviceId, originalMotionEntry.source,
2643 originalMotionEntry.displayId, originalMotionEntry.policyFlags, action,
2644 originalMotionEntry.actionButton, originalMotionEntry.flags,
2645 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2646 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2647 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2648 originalMotionEntry.xCursorPosition,
2649 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002650 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002652 if (originalMotionEntry.injectionState) {
2653 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654 splitMotionEntry->injectionState->refCount += 1;
2655 }
2656
2657 return splitMotionEntry;
2658}
2659
2660void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2661#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002662 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663#endif
2664
2665 bool needWake;
2666 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002667 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668
Prabir Pradhan42611e02018-11-27 14:04:02 -08002669 ConfigurationChangedEntry* newEntry =
2670 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 needWake = enqueueInboundEventLocked(newEntry);
2672 } // release lock
2673
2674 if (needWake) {
2675 mLooper->wake();
2676 }
2677}
2678
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002679/**
2680 * If one of the meta shortcuts is detected, process them here:
2681 * Meta + Backspace -> generate BACK
2682 * Meta + Enter -> generate HOME
2683 * This will potentially overwrite keyCode and metaState.
2684 */
2685void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002686 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002687 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2688 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2689 if (keyCode == AKEYCODE_DEL) {
2690 newKeyCode = AKEYCODE_BACK;
2691 } else if (keyCode == AKEYCODE_ENTER) {
2692 newKeyCode = AKEYCODE_HOME;
2693 }
2694 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002695 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002696 struct KeyReplacement replacement = {keyCode, deviceId};
2697 mReplacedKeys.add(replacement, newKeyCode);
2698 keyCode = newKeyCode;
2699 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2700 }
2701 } else if (action == AKEY_EVENT_ACTION_UP) {
2702 // In order to maintain a consistent stream of up and down events, check to see if the key
2703 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2704 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002705 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002706 struct KeyReplacement replacement = {keyCode, deviceId};
2707 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2708 if (index >= 0) {
2709 keyCode = mReplacedKeys.valueAt(index);
2710 mReplacedKeys.removeItemsAt(index);
2711 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2712 }
2713 }
2714}
2715
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2717#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002718 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2719 "policyFlags=0x%x, action=0x%x, "
2720 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2721 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2722 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2723 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724#endif
2725 if (!validateKeyEvent(args->action)) {
2726 return;
2727 }
2728
2729 uint32_t policyFlags = args->policyFlags;
2730 int32_t flags = args->flags;
2731 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002732 // InputDispatcher tracks and generates key repeats on behalf of
2733 // whatever notifies it, so repeatCount should always be set to 0
2734 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2736 policyFlags |= POLICY_FLAG_VIRTUAL;
2737 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 if (policyFlags & POLICY_FLAG_FUNCTION) {
2740 metaState |= AMETA_FUNCTION_ON;
2741 }
2742
2743 policyFlags |= POLICY_FLAG_TRUSTED;
2744
Michael Wright78f24442014-08-06 15:55:28 -07002745 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002746 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002747
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748 KeyEvent event;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002749 event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2750 args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002751
Michael Wright2b3c3302018-03-02 17:19:13 +00002752 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002754 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2755 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002756 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759 bool needWake;
2760 { // acquire lock
2761 mLock.lock();
2762
2763 if (shouldSendKeyToInputFilterLocked(args)) {
2764 mLock.unlock();
2765
2766 policyFlags |= POLICY_FLAG_FILTERED;
2767 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2768 return; // event was consumed by the filter
2769 }
2770
2771 mLock.lock();
2772 }
2773
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002774 KeyEntry* newEntry =
2775 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2776 args->displayId, policyFlags, args->action, flags, keyCode,
2777 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778
2779 needWake = enqueueInboundEventLocked(newEntry);
2780 mLock.unlock();
2781 } // release lock
2782
2783 if (needWake) {
2784 mLooper->wake();
2785 }
2786}
2787
2788bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2789 return mInputFilterEnabled;
2790}
2791
2792void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2793#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002794 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan00f511d2019-06-12 16:55:40 -07002795 ", policyFlags=0x%x, "
2796 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
2797 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07002798 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan00f511d2019-06-12 16:55:40 -07002799 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2800 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Jaewan Kim372fbe42019-10-02 10:58:46 +09002801 args->edgeFlags, args->xPrecision, args->yPrecision, args->xCursorPosition,
Garfield Tan00f511d2019-06-12 16:55:40 -07002802 args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803 for (uint32_t i = 0; i < args->pointerCount; i++) {
2804 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002805 "x=%f, y=%f, pressure=%f, size=%f, "
2806 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2807 "orientation=%f",
2808 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2809 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2810 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2811 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2812 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2813 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2814 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2815 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2816 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2817 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 }
2819#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002820 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2821 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 return;
2823 }
2824
2825 uint32_t policyFlags = args->policyFlags;
2826 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002827
2828 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002829 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002830 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2831 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002832 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834
2835 bool needWake;
2836 { // acquire lock
2837 mLock.lock();
2838
2839 if (shouldSendMotionToInputFilterLocked(args)) {
2840 mLock.unlock();
2841
2842 MotionEvent event;
Garfield Tan00f511d2019-06-12 16:55:40 -07002843 event.initialize(args->deviceId, args->source, args->displayId, args->action,
2844 args->actionButton, args->flags, args->edgeFlags, args->metaState,
2845 args->buttonState, args->classification, 0, 0, args->xPrecision,
2846 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2847 args->downTime, args->eventTime, args->pointerCount,
2848 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849
2850 policyFlags |= POLICY_FLAG_FILTERED;
2851 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2852 return; // event was consumed by the filter
2853 }
2854
2855 mLock.lock();
2856 }
2857
2858 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07002859 MotionEntry* newEntry =
2860 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2861 args->displayId, policyFlags, args->action, args->actionButton,
2862 args->flags, args->metaState, args->buttonState,
2863 args->classification, args->edgeFlags, args->xPrecision,
2864 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2865 args->downTime, args->pointerCount, args->pointerProperties,
2866 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867
2868 needWake = enqueueInboundEventLocked(newEntry);
2869 mLock.unlock();
2870 } // release lock
2871
2872 if (needWake) {
2873 mLooper->wake();
2874 }
2875}
2876
2877bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002878 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002879}
2880
2881void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2882#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002883 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002884 "switchMask=0x%08x",
2885 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886#endif
2887
2888 uint32_t policyFlags = args->policyFlags;
2889 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002890 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891}
2892
2893void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2894#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002895 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
2896 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897#endif
2898
2899 bool needWake;
2900 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002901 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902
Prabir Pradhan42611e02018-11-27 14:04:02 -08002903 DeviceResetEntry* newEntry =
2904 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905 needWake = enqueueInboundEventLocked(newEntry);
2906 } // release lock
2907
2908 if (needWake) {
2909 mLooper->wake();
2910 }
2911}
2912
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
2914 int32_t injectorUid, int32_t syncMode,
2915 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916#if DEBUG_INBOUND_EVENT_DETAILS
2917 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002918 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2919 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920#endif
2921
2922 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2923
2924 policyFlags |= POLICY_FLAG_INJECTED;
2925 if (hasInjectionPermission(injectorPid, injectorUid)) {
2926 policyFlags |= POLICY_FLAG_TRUSTED;
2927 }
2928
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07002929 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002931 case AINPUT_EVENT_TYPE_KEY: {
2932 KeyEvent keyEvent;
2933 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2934 int32_t action = keyEvent.getAction();
2935 if (!validateKeyEvent(action)) {
2936 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002939 int32_t flags = keyEvent.getFlags();
2940 int32_t keyCode = keyEvent.getKeyCode();
2941 int32_t metaState = keyEvent.getMetaState();
2942 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2943 /*byref*/ keyCode, /*byref*/ metaState);
2944 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
2945 keyEvent.getDisplayId(), action, flags, keyCode,
2946 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
2947 keyEvent.getDownTime(), keyEvent.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002949 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2950 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00002951 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002952
2953 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2954 android::base::Timer t;
2955 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
2956 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2957 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2958 std::to_string(t.duration().count()).c_str());
2959 }
2960 }
2961
2962 mLock.lock();
2963 KeyEntry* injectedEntry =
2964 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
2965 keyEvent.getDeviceId(), keyEvent.getSource(),
2966 keyEvent.getDisplayId(), policyFlags, action, flags,
2967 keyEvent.getKeyCode(), keyEvent.getScanCode(),
2968 keyEvent.getMetaState(), keyEvent.getRepeatCount(),
2969 keyEvent.getDownTime());
2970 injectedEntries.push(injectedEntry);
2971 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 }
2973
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002974 case AINPUT_EVENT_TYPE_MOTION: {
2975 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2976 int32_t action = motionEvent->getAction();
2977 size_t pointerCount = motionEvent->getPointerCount();
2978 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2979 int32_t actionButton = motionEvent->getActionButton();
2980 int32_t displayId = motionEvent->getDisplayId();
2981 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
2982 return INPUT_EVENT_INJECTION_FAILED;
2983 }
2984
2985 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2986 nsecs_t eventTime = motionEvent->getEventTime();
2987 android::base::Timer t;
2988 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
2989 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2990 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2991 std::to_string(t.duration().count()).c_str());
2992 }
2993 }
2994
2995 mLock.lock();
2996 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2997 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2998 MotionEntry* injectedEntry =
Garfield Tan00f511d2019-06-12 16:55:40 -07002999 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3000 motionEvent->getDeviceId(), motionEvent->getSource(),
3001 motionEvent->getDisplayId(), policyFlags, action, actionButton,
3002 motionEvent->getFlags(), motionEvent->getMetaState(),
3003 motionEvent->getButtonState(), motionEvent->getClassification(),
3004 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3005 motionEvent->getYPrecision(),
3006 motionEvent->getRawXCursorPosition(),
3007 motionEvent->getRawYCursorPosition(),
3008 motionEvent->getDownTime(), uint32_t(pointerCount),
3009 pointerProperties, samplePointerCoords,
3010 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003011 injectedEntries.push(injectedEntry);
3012 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3013 sampleEventTimes += 1;
3014 samplePointerCoords += pointerCount;
3015 MotionEntry* nextInjectedEntry =
3016 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3017 motionEvent->getDeviceId(), motionEvent->getSource(),
3018 motionEvent->getDisplayId(), policyFlags, action,
3019 actionButton, motionEvent->getFlags(),
3020 motionEvent->getMetaState(), motionEvent->getButtonState(),
3021 motionEvent->getClassification(),
3022 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3023 motionEvent->getYPrecision(),
3024 motionEvent->getRawXCursorPosition(),
3025 motionEvent->getRawYCursorPosition(),
3026 motionEvent->getDownTime(), uint32_t(pointerCount),
3027 pointerProperties, samplePointerCoords,
3028 motionEvent->getXOffset(), motionEvent->getYOffset());
3029 injectedEntries.push(nextInjectedEntry);
3030 }
3031 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003032 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003034 default:
3035 ALOGW("Cannot inject event of type %d", event->getType());
3036 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037 }
3038
3039 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3040 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3041 injectionState->injectionIsAsync = true;
3042 }
3043
3044 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003045 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046
3047 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003048 while (!injectedEntries.empty()) {
3049 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3050 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051 }
3052
3053 mLock.unlock();
3054
3055 if (needWake) {
3056 mLooper->wake();
3057 }
3058
3059 int32_t injectionResult;
3060 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003061 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062
3063 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3064 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3065 } else {
3066 for (;;) {
3067 injectionResult = injectionState->injectionResult;
3068 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3069 break;
3070 }
3071
3072 nsecs_t remainingTimeout = endTime - now();
3073 if (remainingTimeout <= 0) {
3074#if DEBUG_INJECTION
3075 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003076 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077#endif
3078 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3079 break;
3080 }
3081
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003082 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083 }
3084
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003085 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3086 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087 while (injectionState->pendingForegroundDispatches != 0) {
3088#if DEBUG_INJECTION
3089 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003090 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091#endif
3092 nsecs_t remainingTimeout = endTime - now();
3093 if (remainingTimeout <= 0) {
3094#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003095 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3096 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097#endif
3098 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3099 break;
3100 }
3101
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003102 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 }
3104 }
3105 }
3106
3107 injectionState->release();
3108 } // release lock
3109
3110#if DEBUG_INJECTION
3111 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003112 "injectorPid=%d, injectorUid=%d",
3113 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114#endif
3115
3116 return injectionResult;
3117}
3118
3119bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003120 return injectorUid == 0 ||
3121 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122}
3123
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003124void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125 InjectionState* injectionState = entry->injectionState;
3126 if (injectionState) {
3127#if DEBUG_INJECTION
3128 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003129 "injectorPid=%d, injectorUid=%d",
3130 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131#endif
3132
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003133 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003134 // Log the outcome since the injector did not wait for the injection result.
3135 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003136 case INPUT_EVENT_INJECTION_SUCCEEDED:
3137 ALOGV("Asynchronous input event injection succeeded.");
3138 break;
3139 case INPUT_EVENT_INJECTION_FAILED:
3140 ALOGW("Asynchronous input event injection failed.");
3141 break;
3142 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3143 ALOGW("Asynchronous input event injection permission denied.");
3144 break;
3145 case INPUT_EVENT_INJECTION_TIMED_OUT:
3146 ALOGW("Asynchronous input event injection timed out.");
3147 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 }
3149 }
3150
3151 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003152 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 }
3154}
3155
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003156void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 InjectionState* injectionState = entry->injectionState;
3158 if (injectionState) {
3159 injectionState->pendingForegroundDispatches += 1;
3160 }
3161}
3162
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003163void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 InjectionState* injectionState = entry->injectionState;
3165 if (injectionState) {
3166 injectionState->pendingForegroundDispatches -= 1;
3167
3168 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003169 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 }
3171 }
3172}
3173
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003174std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3175 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003176 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003177}
3178
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003180 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003181 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003182 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3183 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003184 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003185 return windowHandle;
3186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 }
3188 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003189 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190}
3191
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003192bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003193 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003194 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3195 for (const sp<InputWindowHandle>& handle : windowHandles) {
3196 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003197 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003198 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003199 ", but it should belong to display %" PRId32,
3200 windowHandle->getName().c_str(), it.first,
3201 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003202 }
3203 return true;
3204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 }
3206 }
3207 return false;
3208}
3209
Robert Carr5c8a0262018-10-03 16:30:44 -07003210sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3211 size_t count = mInputChannelsByToken.count(token);
3212 if (count == 0) {
3213 return nullptr;
3214 }
3215 return mInputChannelsByToken.at(token);
3216}
3217
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003218void InputDispatcher::updateWindowHandlesForDisplayLocked(
3219 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3220 if (inputWindowHandles.empty()) {
3221 // Remove all handles on a display if there are no windows left.
3222 mWindowHandlesByDisplay.erase(displayId);
3223 return;
3224 }
3225
3226 // Since we compare the pointer of input window handles across window updates, we need
3227 // to make sure the handle object for the same window stays unchanged across updates.
3228 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
3229 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3230 for (const sp<InputWindowHandle>& handle : oldHandles) {
3231 oldHandlesByTokens[handle->getToken()] = handle;
3232 }
3233
3234 std::vector<sp<InputWindowHandle>> newHandles;
3235 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3236 if (!handle->updateInfo()) {
3237 // handle no longer valid
3238 continue;
3239 }
3240
3241 const InputWindowInfo* info = handle->getInfo();
3242 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3243 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3244 const bool noInputChannel =
3245 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3246 const bool canReceiveInput =
3247 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3248 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3249 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003250 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003251 handle->getName().c_str());
3252 }
3253 continue;
3254 }
3255
3256 if (info->displayId != displayId) {
3257 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3258 handle->getName().c_str(), displayId, info->displayId);
3259 continue;
3260 }
3261
3262 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3263 const sp<InputWindowHandle> oldHandle = oldHandlesByTokens.at(handle->getToken());
3264 oldHandle->updateFrom(handle);
3265 newHandles.push_back(oldHandle);
3266 } else {
3267 newHandles.push_back(handle);
3268 }
3269 }
3270
3271 // Insert or replace
3272 mWindowHandlesByDisplay[displayId] = newHandles;
3273}
3274
Arthur Hungb92218b2018-08-14 12:00:21 +08003275/**
3276 * Called from InputManagerService, update window handle list by displayId that can receive input.
3277 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3278 * If set an empty list, remove all handles from the specific display.
3279 * For focused handle, check if need to change and send a cancel event to previous one.
3280 * For removed handle, check if need to send a cancel event if already in touch.
3281 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003282void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003283 int32_t displayId,
3284 const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003285 if (DEBUG_FOCUS) {
3286 std::string windowList;
3287 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3288 windowList += iwh->getName() + " ";
3289 }
3290 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3291 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003293 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294
Arthur Hungb92218b2018-08-14 12:00:21 +08003295 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003296 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3297 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003299 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
3300
Tiger Huang721e26f2018-07-24 22:26:19 +08003301 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 bool foundHoveredWindow = false;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003303 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3304 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3305 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3306 windowHandle->getInfo()->visible) {
3307 newFocusedWindowHandle = windowHandle;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003308 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003309 if (windowHandle == mLastHoverWindowHandle) {
3310 foundHoveredWindow = true;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 }
3313
3314 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003315 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316 }
3317
Tiger Huang721e26f2018-07-24 22:26:19 +08003318 sp<InputWindowHandle> oldFocusedWindowHandle =
3319 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3320
3321 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3322 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003323 if (DEBUG_FOCUS) {
3324 ALOGD("Focus left window: %s in display %" PRId32,
3325 oldFocusedWindowHandle->getName().c_str(), displayId);
3326 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003327 sp<InputChannel> focusedInputChannel =
3328 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003329 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331 "focus left window");
3332 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003334 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003336 if (newFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003337 if (DEBUG_FOCUS) {
3338 ALOGD("Focus entered window: %s in display %" PRId32,
3339 newFocusedWindowHandle->getName().c_str(), displayId);
3340 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003341 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 }
Robert Carrf759f162018-11-13 12:57:11 -08003343
3344 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003345 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003346 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347 }
3348
Arthur Hungb92218b2018-08-14 12:00:21 +08003349 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3350 if (stateIndex >= 0) {
3351 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003352 for (size_t i = 0; i < state.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003353 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003354 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003355 if (DEBUG_FOCUS) {
3356 ALOGD("Touched window was removed: %s in display %" PRId32,
3357 touchedWindow.windowHandle->getName().c_str(), displayId);
3358 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003359 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003360 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003361 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003362 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003363 "touched window was removed");
3364 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3365 options);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003366 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003367 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003368 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003369 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 }
3372 }
3373
3374 // Release information for windows that are no longer present.
3375 // This ensures that unused input channels are released promptly.
3376 // Otherwise, they might stick around until the window handle is destroyed
3377 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003378 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003379 if (!hasWindowHandleLocked(oldWindowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003380 if (DEBUG_FOCUS) {
3381 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
3382 }
Arthur Hung3b413f22018-10-26 18:05:34 +08003383 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 }
3385 }
3386 } // release lock
3387
3388 // Wake up poll loop since it may need to make new input dispatching choices.
3389 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003390
3391 if (setInputWindowsListener) {
3392 setInputWindowsListener->onSetInputWindowsFinished();
3393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394}
3395
3396void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003397 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003398 if (DEBUG_FOCUS) {
3399 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3400 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003403 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404
Tiger Huang721e26f2018-07-24 22:26:19 +08003405 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3406 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003407 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003408 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3409 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003412 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003414 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003416 oldFocusedApplicationHandle.clear();
3417 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 } // release lock
3420
3421 // Wake up poll loop since it may need to make new input dispatching choices.
3422 mLooper->wake();
3423}
3424
Tiger Huang721e26f2018-07-24 22:26:19 +08003425/**
3426 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3427 * the display not specified.
3428 *
3429 * We track any unreleased events for each window. If a window loses the ability to receive the
3430 * released event, we will send a cancel event to it. So when the focused display is changed, we
3431 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3432 * display. The display-specified events won't be affected.
3433 */
3434void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003435 if (DEBUG_FOCUS) {
3436 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3437 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003438 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003439 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003440
3441 if (mFocusedDisplayId != displayId) {
3442 sp<InputWindowHandle> oldFocusedWindowHandle =
3443 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3444 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003445 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003446 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003447 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003448 CancelationOptions
3449 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3450 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003451 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003452 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3453 }
3454 }
3455 mFocusedDisplayId = displayId;
3456
3457 // Sanity check
3458 sp<InputWindowHandle> newFocusedWindowHandle =
3459 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003460 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003461
Tiger Huang721e26f2018-07-24 22:26:19 +08003462 if (newFocusedWindowHandle == nullptr) {
3463 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3464 if (!mFocusedWindowHandlesByDisplay.empty()) {
3465 ALOGE("But another display has a focused window:");
3466 for (auto& it : mFocusedWindowHandlesByDisplay) {
3467 const int32_t displayId = it.first;
3468 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003469 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3470 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003471 }
3472 }
3473 }
3474 }
3475
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003476 if (DEBUG_FOCUS) {
3477 logDispatchStateLocked();
3478 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003479 } // release lock
3480
3481 // Wake up poll loop since it may need to make new input dispatching choices.
3482 mLooper->wake();
3483}
3484
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003486 if (DEBUG_FOCUS) {
3487 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3488 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489
3490 bool changed;
3491 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003492 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493
3494 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3495 if (mDispatchFrozen && !frozen) {
3496 resetANRTimeoutsLocked();
3497 }
3498
3499 if (mDispatchEnabled && !enabled) {
3500 resetAndDropEverythingLocked("dispatcher is being disabled");
3501 }
3502
3503 mDispatchEnabled = enabled;
3504 mDispatchFrozen = frozen;
3505 changed = true;
3506 } else {
3507 changed = false;
3508 }
3509
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003510 if (DEBUG_FOCUS) {
3511 logDispatchStateLocked();
3512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 } // release lock
3514
3515 if (changed) {
3516 // Wake up poll loop since it may need to make new input dispatching choices.
3517 mLooper->wake();
3518 }
3519}
3520
3521void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003522 if (DEBUG_FOCUS) {
3523 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525
3526 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003527 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528
3529 if (mInputFilterEnabled == enabled) {
3530 return;
3531 }
3532
3533 mInputFilterEnabled = enabled;
3534 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3535 } // release lock
3536
3537 // Wake up poll loop since there might be work to do to drop everything.
3538 mLooper->wake();
3539}
3540
chaviwfbe5d9c2018-12-26 12:23:37 -08003541bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3542 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003543 if (DEBUG_FOCUS) {
3544 ALOGD("Trivial transfer to same window.");
3545 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003546 return true;
3547 }
3548
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003550 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551
chaviwfbe5d9c2018-12-26 12:23:37 -08003552 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3553 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003554 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003555 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556 return false;
3557 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003558 if (DEBUG_FOCUS) {
3559 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3560 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003563 if (DEBUG_FOCUS) {
3564 ALOGD("Cannot transfer focus because windows are on different displays.");
3565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566 return false;
3567 }
3568
3569 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003570 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3571 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3572 for (size_t i = 0; i < state.windows.size(); i++) {
3573 const TouchedWindow& touchedWindow = state.windows[i];
3574 if (touchedWindow.windowHandle == fromWindowHandle) {
3575 int32_t oldTargetFlags = touchedWindow.targetFlags;
3576 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003578 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003580 int32_t newTargetFlags = oldTargetFlags &
3581 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3582 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003583 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584
Jeff Brownf086ddb2014-02-11 14:28:48 -08003585 found = true;
3586 goto Found;
3587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 }
3589 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003590 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003592 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003593 if (DEBUG_FOCUS) {
3594 ALOGD("Focus transfer failed because from window did not have focus.");
3595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 return false;
3597 }
3598
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003599 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3600 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003601 if (fromConnection != nullptr && toConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003603 CancelationOptions
3604 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3605 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3607 }
3608
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003609 if (DEBUG_FOCUS) {
3610 logDispatchStateLocked();
3611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 } // release lock
3613
3614 // Wake up poll loop since it may need to make new input dispatching choices.
3615 mLooper->wake();
3616 return true;
3617}
3618
3619void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003620 if (DEBUG_FOCUS) {
3621 ALOGD("Resetting and dropping all events (%s).", reason);
3622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623
3624 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3625 synthesizeCancelationEventsForAllConnectionsLocked(options);
3626
3627 resetKeyRepeatLocked();
3628 releasePendingEventLocked();
3629 drainInboundQueueLocked();
3630 resetANRTimeoutsLocked();
3631
Jeff Brownf086ddb2014-02-11 14:28:48 -08003632 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003634 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635}
3636
3637void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003638 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 dumpDispatchStateLocked(dump);
3640
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003641 std::istringstream stream(dump);
3642 std::string line;
3643
3644 while (std::getline(stream, line, '\n')) {
3645 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 }
3647}
3648
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003649void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003650 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3651 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3652 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003653 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654
Tiger Huang721e26f2018-07-24 22:26:19 +08003655 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3656 dump += StringPrintf(INDENT "FocusedApplications:\n");
3657 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3658 const int32_t displayId = it.first;
3659 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003660 dump += StringPrintf(INDENT2 "displayId=%" PRId32
3661 ", name='%s', dispatchingTimeout=%0.3fms\n",
3662 displayId, applicationHandle->getName().c_str(),
3663 applicationHandle->getDispatchingTimeout(
3664 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3665 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08003666 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003667 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003668 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003670
3671 if (!mFocusedWindowHandlesByDisplay.empty()) {
3672 dump += StringPrintf(INDENT "FocusedWindows:\n");
3673 for (auto& it : mFocusedWindowHandlesByDisplay) {
3674 const int32_t displayId = it.first;
3675 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003676 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3677 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003678 }
3679 } else {
3680 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3681 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682
Jeff Brownf086ddb2014-02-11 14:28:48 -08003683 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003684 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003685 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3686 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003687 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003688 state.displayId, toString(state.down), toString(state.split),
3689 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003690 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003691 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003692 for (size_t i = 0; i < state.windows.size(); i++) {
3693 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003694 dump += StringPrintf(INDENT4
3695 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3696 i, touchedWindow.windowHandle->getName().c_str(),
3697 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003698 }
3699 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003700 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003701 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003702 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003703 dump += INDENT3 "Portal windows:\n";
3704 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003705 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003706 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3707 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003708 }
3709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 }
3711 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003712 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 }
3714
Arthur Hungb92218b2018-08-14 12:00:21 +08003715 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003716 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003717 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003718 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003719 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003720 dump += INDENT2 "Windows:\n";
3721 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003722 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003723 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724
Arthur Hungb92218b2018-08-14 12:00:21 +08003725 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003726 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
3727 "hasWallpaper=%s, "
3728 "visible=%s, canReceiveKeys=%s, flags=0x%08x, "
3729 "type=0x%08x, layer=%d, "
3730 "frame=[%d,%d][%d,%d], globalScale=%f, "
3731 "windowScale=(%f,%f), "
3732 "touchableRegion=",
3733 i, windowInfo->name.c_str(), windowInfo->displayId,
3734 windowInfo->portalToDisplayId,
3735 toString(windowInfo->paused),
3736 toString(windowInfo->hasFocus),
3737 toString(windowInfo->hasWallpaper),
3738 toString(windowInfo->visible),
3739 toString(windowInfo->canReceiveKeys),
3740 windowInfo->layoutParamsFlags,
3741 windowInfo->layoutParamsType, windowInfo->layer,
3742 windowInfo->frameLeft, windowInfo->frameTop,
3743 windowInfo->frameRight, windowInfo->frameBottom,
3744 windowInfo->globalScaleFactor, windowInfo->windowXScale,
3745 windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003746 dumpRegion(dump, windowInfo->touchableRegion);
3747 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3748 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003749 windowInfo->ownerPid, windowInfo->ownerUid,
3750 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08003751 }
3752 } else {
3753 dump += INDENT2 "Windows: <none>\n";
3754 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755 }
3756 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003757 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 }
3759
Michael Wright3dd60e22019-03-27 22:06:44 +00003760 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003761 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003762 const std::vector<Monitor>& monitors = it.second;
3763 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3764 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003765 }
3766 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003767 const std::vector<Monitor>& monitors = it.second;
3768 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3769 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003772 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 }
3774
3775 nsecs_t currentTime = now();
3776
3777 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003778 if (!mRecentQueue.empty()) {
3779 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
3780 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003781 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003783 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 }
3785 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003786 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 }
3788
3789 // Dump event currently being dispatched.
3790 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003791 dump += INDENT "PendingEvent:\n";
3792 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003794 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003795 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003797 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798 }
3799
3800 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003801 if (!mInboundQueue.empty()) {
3802 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
3803 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003804 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003806 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 }
3808 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003809 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 }
3811
Michael Wright78f24442014-08-06 15:55:28 -07003812 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003813 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003814 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3815 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3816 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003817 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3818 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07003819 }
3820 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003821 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003822 }
3823
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003824 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003825 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003826 for (const auto& pair : mConnectionsByFd) {
3827 const sp<Connection>& connection = pair.second;
3828 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
3829 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3830 pair.first, connection->getInputChannelName().c_str(),
3831 connection->getWindowName().c_str(), connection->getStatusLabel(),
3832 toString(connection->monitor),
3833 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003835 if (!connection->outboundQueue.empty()) {
3836 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
3837 connection->outboundQueue.size());
3838 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 dump.append(INDENT4);
3840 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003841 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003842 entry->targetFlags, entry->resolvedAction,
3843 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844 }
3845 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003846 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847 }
3848
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003849 if (!connection->waitQueue.empty()) {
3850 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
3851 connection->waitQueue.size());
3852 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003853 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003855 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003856 "age=%0.1fms, wait=%0.1fms\n",
3857 entry->targetFlags, entry->resolvedAction,
3858 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3859 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003860 }
3861 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003862 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 }
3864 }
3865 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003866 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 }
3868
3869 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003870 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003871 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003873 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 }
3875
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003876 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003877 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003878 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003879 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880}
3881
Michael Wright3dd60e22019-03-27 22:06:44 +00003882void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3883 const size_t numMonitors = monitors.size();
3884 for (size_t i = 0; i < numMonitors; i++) {
3885 const Monitor& monitor = monitors[i];
3886 const sp<InputChannel>& channel = monitor.inputChannel;
3887 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3888 dump += "\n";
3889 }
3890}
3891
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003892status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003894 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895#endif
3896
3897 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003898 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003899 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003900 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003902 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 return BAD_VALUE;
3904 }
3905
Michael Wright3dd60e22019-03-27 22:06:44 +00003906 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907
3908 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 Wrightd02c5b62014-02-10 15:10:22 -08003911
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3913 } // release lock
3914
3915 // Wake the looper because some connections have changed.
3916 mLooper->wake();
3917 return OK;
3918}
3919
Michael Wright3dd60e22019-03-27 22:06:44 +00003920status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003921 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003922 { // acquire lock
3923 std::scoped_lock _l(mLock);
3924
3925 if (displayId < 0) {
3926 ALOGW("Attempted to register input monitor without a specified display.");
3927 return BAD_VALUE;
3928 }
3929
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003930 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003931 ALOGW("Attempted to register input monitor without an identifying token.");
3932 return BAD_VALUE;
3933 }
3934
3935 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3936
3937 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003938 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003939 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00003940
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003941 auto& monitorsByDisplay =
3942 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00003943 monitorsByDisplay[displayId].emplace_back(inputChannel);
3944
3945 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00003946 }
3947 // Wake the looper because some connections have changed.
3948 mLooper->wake();
3949 return OK;
3950}
3951
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3953#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003954 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955#endif
3956
3957 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003958 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959
3960 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3961 if (status) {
3962 return status;
3963 }
3964 } // release lock
3965
3966 // Wake the poll loop because removing the connection may have changed the current
3967 // synchronization state.
3968 mLooper->wake();
3969 return OK;
3970}
3971
3972status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003973 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003974 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003975 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003977 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 return BAD_VALUE;
3979 }
3980
John Recke0710582019-09-26 13:46:12 -07003981 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003982 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003983 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07003984
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985 if (connection->monitor) {
3986 removeMonitorChannelLocked(inputChannel);
3987 }
3988
3989 mLooper->removeFd(inputChannel->getFd());
3990
3991 nsecs_t currentTime = now();
3992 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3993
3994 connection->status = Connection::STATUS_ZOMBIE;
3995 return OK;
3996}
3997
3998void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003999 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4000 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4001}
4002
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004003void InputDispatcher::removeMonitorChannelLocked(
4004 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004005 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004006 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004007 std::vector<Monitor>& monitors = it->second;
4008 const size_t numMonitors = monitors.size();
4009 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004010 if (monitors[i].inputChannel == inputChannel) {
4011 monitors.erase(monitors.begin() + i);
4012 break;
4013 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004014 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004015 if (monitors.empty()) {
4016 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004017 } else {
4018 ++it;
4019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020 }
4021}
4022
Michael Wright3dd60e22019-03-27 22:06:44 +00004023status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4024 { // acquire lock
4025 std::scoped_lock _l(mLock);
4026 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4027
4028 if (!foundDisplayId) {
4029 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4030 return BAD_VALUE;
4031 }
4032 int32_t displayId = foundDisplayId.value();
4033
4034 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4035 if (stateIndex < 0) {
4036 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4037 return BAD_VALUE;
4038 }
4039
4040 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4041 std::optional<int32_t> foundDeviceId;
4042 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004043 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004044 foundDeviceId = state.deviceId;
4045 }
4046 }
4047 if (!foundDeviceId || !state.down) {
4048 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004049 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004050 return BAD_VALUE;
4051 }
4052 int32_t deviceId = foundDeviceId.value();
4053
4054 // Send cancel events to all the input channels we're stealing from.
4055 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004056 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004057 options.deviceId = deviceId;
4058 options.displayId = displayId;
4059 for (const TouchedWindow& window : state.windows) {
4060 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
4061 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4062 }
4063 // Then clear the current touch state so we stop dispatching to them as well.
4064 state.filterNonMonitors();
4065 }
4066 return OK;
4067}
4068
Michael Wright3dd60e22019-03-27 22:06:44 +00004069std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4070 const sp<IBinder>& token) {
4071 for (const auto& it : mGestureMonitorsByDisplay) {
4072 const std::vector<Monitor>& monitors = it.second;
4073 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004074 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004075 return it.first;
4076 }
4077 }
4078 }
4079 return std::nullopt;
4080}
4081
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004082sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4083 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004084 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004085 }
4086
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004087 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004088 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004089 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004090 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 }
4092 }
Robert Carr4e670e52018-08-15 13:26:12 -07004093
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004094 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095}
4096
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004097void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4098 const sp<Connection>& connection, uint32_t seq,
4099 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004100 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4101 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102 commandEntry->connection = connection;
4103 commandEntry->eventTime = currentTime;
4104 commandEntry->seq = seq;
4105 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004106 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107}
4108
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004109void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4110 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004112 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004114 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4115 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004117 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118}
4119
chaviw0c06c6e2019-01-09 13:27:07 -08004120void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004121 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004122 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4123 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004124 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4125 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004126 commandEntry->oldToken = oldToken;
4127 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004128 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004129}
4130
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004131void InputDispatcher::onANRLocked(nsecs_t currentTime,
4132 const sp<InputApplicationHandle>& applicationHandle,
4133 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4134 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4136 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4137 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004138 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4139 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4140 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141
4142 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004143 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 struct tm tm;
4145 localtime_r(&t, &tm);
4146 char timestr[64];
4147 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4148 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004149 mLastANRState += INDENT "ANR:\n";
4150 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004151 mLastANRState +=
4152 StringPrintf(INDENT2 "Window: %s\n",
4153 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004154 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4155 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4156 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 dumpDispatchStateLocked(mLastANRState);
4158
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004159 std::unique_ptr<CommandEntry> commandEntry =
4160 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004162 commandEntry->inputChannel =
4163 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004165 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166}
4167
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004168void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 mLock.unlock();
4170
4171 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4172
4173 mLock.lock();
4174}
4175
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004176void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177 sp<Connection> connection = commandEntry->connection;
4178
4179 if (connection->status != Connection::STATUS_ZOMBIE) {
4180 mLock.unlock();
4181
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004182 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183
4184 mLock.lock();
4185 }
4186}
4187
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004188void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004189 sp<IBinder> oldToken = commandEntry->oldToken;
4190 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004191 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004192 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004193 mLock.lock();
4194}
4195
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004197 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004198 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 mLock.unlock();
4200
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 nsecs_t newTimeout =
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004202 mPolicy->notifyANR(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203
4204 mLock.lock();
4205
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004206 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207}
4208
4209void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4210 CommandEntry* commandEntry) {
4211 KeyEntry* entry = commandEntry->keyEntry;
4212
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004213 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214
4215 mLock.unlock();
4216
Michael Wright2b3c3302018-03-02 17:19:13 +00004217 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004218 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004219 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004220 : nullptr;
4221 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004222 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4223 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004225 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226
4227 mLock.lock();
4228
4229 if (delay < 0) {
4230 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4231 } else if (!delay) {
4232 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4233 } else {
4234 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4235 entry->interceptKeyWakeupTime = now() + delay;
4236 }
4237 entry->release();
4238}
4239
chaviwfd6d3512019-03-25 13:23:49 -07004240void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4241 mLock.unlock();
4242 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4243 mLock.lock();
4244}
4245
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004248 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004250 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251
4252 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004253 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004254 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004255 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004257 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004258
4259 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4260 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4261 std::string msg =
4262 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4263 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4264 dispatchEntry->eventEntry->appendDescription(msg);
4265 ALOGI("%s", msg.c_str());
4266 }
4267
4268 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004269 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004270 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4271 restartEvent =
4272 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004273 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004274 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4275 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4276 handled);
4277 } else {
4278 restartEvent = false;
4279 }
4280
4281 // Dequeue the event and start the next cycle.
4282 // Note that because the lock might have been released, it is possible that the
4283 // contents of the wait queue to have been drained, so we need to double-check
4284 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004285 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4286 if (dispatchEntryIt != connection->waitQueue.end()) {
4287 dispatchEntry = *dispatchEntryIt;
4288 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004289 traceWaitQueueLength(connection);
4290 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004291 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004292 traceOutboundQueueLength(connection);
4293 } else {
4294 releaseDispatchEntry(dispatchEntry);
4295 }
4296 }
4297
4298 // Start the next dispatch cycle for this connection.
4299 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300}
4301
4302bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004303 DispatchEntry* dispatchEntry,
4304 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004305 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004306 if (!handled) {
4307 // Report the key as unhandled, since the fallback was not handled.
4308 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4309 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004310 return false;
4311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004313 // Get the fallback key state.
4314 // Clear it out after dispatching the UP.
4315 int32_t originalKeyCode = keyEntry->keyCode;
4316 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4317 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4318 connection->inputState.removeFallbackKey(originalKeyCode);
4319 }
4320
4321 if (handled || !dispatchEntry->hasForegroundTarget()) {
4322 // If the application handles the original key for which we previously
4323 // generated a fallback or if the window is not a foreground window,
4324 // then cancel the associated fallback key, if any.
4325 if (fallbackKeyCode != -1) {
4326 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004328 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004329 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4330 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4331 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004333 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004334 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335
4336 mLock.unlock();
4337
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004338 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004339 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340
4341 mLock.lock();
4342
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004343 // Cancel the fallback key.
4344 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004346 "application handled the original non-fallback key "
4347 "or is no longer a foreground target, "
4348 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349 options.keyCode = fallbackKeyCode;
4350 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004352 connection->inputState.removeFallbackKey(originalKeyCode);
4353 }
4354 } else {
4355 // If the application did not handle a non-fallback key, first check
4356 // that we are in a good state to perform unhandled key event processing
4357 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004358 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004359 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004361 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004362 "since this is not an initial down. "
4363 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4364 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004366 return false;
4367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004369 // Dispatch the unhandled key to the policy.
4370#if DEBUG_OUTBOUND_EVENT_DETAILS
4371 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004372 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4373 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004374#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004375 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004376
4377 mLock.unlock();
4378
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004379 bool fallback =
4380 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4381 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004382
4383 mLock.lock();
4384
4385 if (connection->status != Connection::STATUS_NORMAL) {
4386 connection->inputState.removeFallbackKey(originalKeyCode);
4387 return false;
4388 }
4389
4390 // Latch the fallback keycode for this key on an initial down.
4391 // The fallback keycode cannot change at any other point in the lifecycle.
4392 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004394 fallbackKeyCode = event.getKeyCode();
4395 } else {
4396 fallbackKeyCode = AKEYCODE_UNKNOWN;
4397 }
4398 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4399 }
4400
4401 ALOG_ASSERT(fallbackKeyCode != -1);
4402
4403 // Cancel the fallback key if the policy decides not to send it anymore.
4404 // We will continue to dispatch the key to the policy but we will no
4405 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004406 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4407 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004408#if DEBUG_OUTBOUND_EVENT_DETAILS
4409 if (fallback) {
4410 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004411 "as a fallback for %d, but on the DOWN it had requested "
4412 "to send %d instead. Fallback canceled.",
4413 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004414 } else {
4415 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004416 "but on the DOWN it had requested to send %d. "
4417 "Fallback canceled.",
4418 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004419 }
4420#endif
4421
4422 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4423 "canceling fallback, policy no longer desires it");
4424 options.keyCode = fallbackKeyCode;
4425 synthesizeCancelationEventsForConnectionLocked(connection, options);
4426
4427 fallback = false;
4428 fallbackKeyCode = AKEYCODE_UNKNOWN;
4429 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004430 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004431 }
4432 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433
4434#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004435 {
4436 std::string msg;
4437 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4438 connection->inputState.getFallbackKeys();
4439 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004440 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004441 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004442 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004443 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004444 }
4445#endif
4446
4447 if (fallback) {
4448 // Restart the dispatch cycle using the fallback key.
4449 keyEntry->eventTime = event.getEventTime();
4450 keyEntry->deviceId = event.getDeviceId();
4451 keyEntry->source = event.getSource();
4452 keyEntry->displayId = event.getDisplayId();
4453 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4454 keyEntry->keyCode = fallbackKeyCode;
4455 keyEntry->scanCode = event.getScanCode();
4456 keyEntry->metaState = event.getMetaState();
4457 keyEntry->repeatCount = event.getRepeatCount();
4458 keyEntry->downTime = event.getDownTime();
4459 keyEntry->syntheticRepeat = false;
4460
4461#if DEBUG_OUTBOUND_EVENT_DETAILS
4462 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004463 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4464 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004465#endif
4466 return true; // restart the event
4467 } else {
4468#if DEBUG_OUTBOUND_EVENT_DETAILS
4469 ALOGD("Unhandled key event: No fallback key.");
4470#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004471
4472 // Report the key as unhandled, since there is no fallback key.
4473 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474 }
4475 }
4476 return false;
4477}
4478
4479bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004480 DispatchEntry* dispatchEntry,
4481 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 return false;
4483}
4484
4485void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4486 mLock.unlock();
4487
4488 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4489
4490 mLock.lock();
4491}
4492
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004493KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4494 KeyEvent event;
4495 event.initialize(entry.deviceId, entry.source, entry.displayId, entry.action, entry.flags,
4496 entry.keyCode, entry.scanCode, entry.metaState, entry.repeatCount,
4497 entry.downTime, entry.eventTime);
4498 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499}
4500
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004501void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004502 int32_t injectionResult,
4503 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504 // TODO Write some statistics about how long we spend waiting.
4505}
4506
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004507/**
4508 * Report the touch event latency to the statsd server.
4509 * Input events are reported for statistics if:
4510 * - This is a touchscreen event
4511 * - InputFilter is not enabled
4512 * - Event is not injected or synthesized
4513 *
4514 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4515 * from getting aggregated with the "old" data.
4516 */
4517void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4518 REQUIRES(mLock) {
4519 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4520 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4521 if (!reportForStatistics) {
4522 return;
4523 }
4524
4525 if (mTouchStatistics.shouldReport()) {
4526 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4527 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4528 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4529 mTouchStatistics.reset();
4530 }
4531 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4532 mTouchStatistics.addValue(latencyMicros);
4533}
4534
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535void InputDispatcher::traceInboundQueueLengthLocked() {
4536 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004537 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 }
4539}
4540
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004541void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542 if (ATRACE_ENABLED()) {
4543 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004544 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004545 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 }
4547}
4548
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004549void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550 if (ATRACE_ENABLED()) {
4551 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004552 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004553 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554 }
4555}
4556
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004557void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004558 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004560 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561 dumpDispatchStateLocked(dump);
4562
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004563 if (!mLastANRState.empty()) {
4564 dump += "\nInput Dispatcher State at time of last ANR:\n";
4565 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566 }
4567}
4568
4569void InputDispatcher::monitor() {
4570 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004571 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004573 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574}
4575
Garfield Tane84e6f92019-08-29 17:28:41 -07004576} // namespace android::inputdispatcher