blob: c21994112960ff7ff953440d27e2f2823d2ab702 [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 }
2298
2299 default:
2300 ALOG_ASSERT(false);
2301 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302 }
2303
2304 // Check the result.
2305 if (status) {
2306 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002307 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002309 "This is unexpected because the wait queue is empty, so the pipe "
2310 "should be empty and we shouldn't have any problems writing an "
2311 "event to it, status=%d",
2312 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2314 } else {
2315 // Pipe is full and we are waiting for the app to finish process some events
2316 // before sending more events to it.
2317#if DEBUG_DISPATCH_CYCLE
2318 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002319 "waiting for the application to catch up",
2320 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321#endif
2322 connection->inputPublisherBlocked = true;
2323 }
2324 } else {
2325 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002326 "status=%d",
2327 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2329 }
2330 return;
2331 }
2332
2333 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002334 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2335 connection->outboundQueue.end(),
2336 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002337 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002338 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002339 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 }
2341}
2342
2343void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002344 const sp<Connection>& connection, uint32_t seq,
2345 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346#if DEBUG_DISPATCH_CYCLE
2347 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002348 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349#endif
2350
2351 connection->inputPublisherBlocked = false;
2352
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002353 if (connection->status == Connection::STATUS_BROKEN ||
2354 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 return;
2356 }
2357
2358 // Notify other system components and prepare to start the next dispatch cycle.
2359 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2360}
2361
2362void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002363 const sp<Connection>& connection,
2364 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365#if DEBUG_DISPATCH_CYCLE
2366 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002367 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368#endif
2369
2370 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002371 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002372 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002373 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002374 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375
2376 // The connection appears to be unrecoverably broken.
2377 // Ignore already broken or zombie connections.
2378 if (connection->status == Connection::STATUS_NORMAL) {
2379 connection->status = Connection::STATUS_BROKEN;
2380
2381 if (notify) {
2382 // Notify other system components.
2383 onDispatchCycleBrokenLocked(currentTime, connection);
2384 }
2385 }
2386}
2387
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002388void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2389 while (!queue.empty()) {
2390 DispatchEntry* dispatchEntry = queue.front();
2391 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002392 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 }
2394}
2395
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002396void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002398 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 }
2400 delete dispatchEntry;
2401}
2402
2403int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2404 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2405
2406 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002407 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002409 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002411 "fd=%d, events=0x%x",
2412 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 return 0; // remove the callback
2414 }
2415
2416 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002417 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2419 if (!(events & ALOOPER_EVENT_INPUT)) {
2420 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002421 "events=0x%x",
2422 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423 return 1;
2424 }
2425
2426 nsecs_t currentTime = now();
2427 bool gotOne = false;
2428 status_t status;
2429 for (;;) {
2430 uint32_t seq;
2431 bool handled;
2432 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2433 if (status) {
2434 break;
2435 }
2436 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2437 gotOne = true;
2438 }
2439 if (gotOne) {
2440 d->runCommandsLockedInterruptible();
2441 if (status == WOULD_BLOCK) {
2442 return 1;
2443 }
2444 }
2445
2446 notify = status != DEAD_OBJECT || !connection->monitor;
2447 if (notify) {
2448 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002449 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 }
2451 } else {
2452 // Monitor channels are never explicitly unregistered.
2453 // We do it automatically when the remote endpoint is closed so don't warn
2454 // about them.
2455 notify = !connection->monitor;
2456 if (notify) {
2457 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002458 "events=0x%x",
2459 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 }
2461 }
2462
2463 // Unregister the channel.
2464 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2465 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002466 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467}
2468
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002469void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002471 for (const auto& pair : mConnectionsByFd) {
2472 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473 }
2474}
2475
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002476void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002477 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002478 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2479 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2480}
2481
2482void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2483 const CancelationOptions& options,
2484 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2485 for (const auto& it : monitorsByDisplay) {
2486 const std::vector<Monitor>& monitors = it.second;
2487 for (const Monitor& monitor : monitors) {
2488 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002489 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002490 }
2491}
2492
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2494 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002495 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002496 if (connection == nullptr) {
2497 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002499
2500 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501}
2502
2503void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2504 const sp<Connection>& connection, const CancelationOptions& options) {
2505 if (connection->status == Connection::STATUS_BROKEN) {
2506 return;
2507 }
2508
2509 nsecs_t currentTime = now();
2510
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002511 std::vector<EventEntry*> cancelationEvents =
2512 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002514 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002516 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002517 "with reality: %s, mode=%d.",
2518 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2519 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520#endif
2521 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002522 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523 switch (cancelationEventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002524 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002525 logOutboundKeyDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002526 static_cast<const KeyEntry&>(*cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002527 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002528 }
2529 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002530 logOutboundMotionDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002531 static_cast<const MotionEntry&>(
2532 *cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002534 }
2535 case EventEntry::Type::CONFIGURATION_CHANGED:
2536 case EventEntry::Type::DEVICE_RESET: {
2537 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2538 EventEntry::typeToString(cancelationEventEntry->type));
2539 break;
2540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541 }
2542
2543 InputTarget target;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002544 sp<InputWindowHandle> windowHandle =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002545 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002546 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2548 target.xOffset = -windowInfo->frameLeft;
2549 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002550 target.globalScaleFactor = windowInfo->globalScaleFactor;
2551 target.windowXScale = windowInfo->windowXScale;
2552 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 } else {
2554 target.xOffset = 0;
2555 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002556 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 }
2558 target.inputChannel = connection->inputChannel;
2559 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2560
chaviw8c9cf542019-03-25 13:02:48 -07002561 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002562 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563
2564 cancelationEventEntry->release();
2565 }
2566
2567 startDispatchCycleLocked(currentTime, connection);
2568 }
2569}
2570
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002571MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002572 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573 ALOG_ASSERT(pointerIds.value != 0);
2574
2575 uint32_t splitPointerIndexMap[MAX_POINTERS];
2576 PointerProperties splitPointerProperties[MAX_POINTERS];
2577 PointerCoords splitPointerCoords[MAX_POINTERS];
2578
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002579 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 uint32_t splitPointerCount = 0;
2581
2582 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002583 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002585 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 uint32_t pointerId = uint32_t(pointerProperties.id);
2587 if (pointerIds.hasBit(pointerId)) {
2588 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2589 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2590 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002591 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002592 splitPointerCount += 1;
2593 }
2594 }
2595
2596 if (splitPointerCount != pointerIds.count()) {
2597 // This is bad. We are missing some of the pointers that we expected to deliver.
2598 // Most likely this indicates that we received an ACTION_MOVE events that has
2599 // different pointer ids than we expected based on the previous ACTION_DOWN
2600 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2601 // in this way.
2602 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002603 "we expected there to be %d pointers. This probably means we received "
2604 "a broken sequence of pointer ids from the input device.",
2605 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002606 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 }
2608
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002609 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002611 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2612 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2614 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002615 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616 uint32_t pointerId = uint32_t(pointerProperties.id);
2617 if (pointerIds.hasBit(pointerId)) {
2618 if (pointerIds.count() == 1) {
2619 // The first/last pointer went down/up.
2620 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002621 ? AMOTION_EVENT_ACTION_DOWN
2622 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 } else {
2624 // A secondary pointer went down/up.
2625 uint32_t splitPointerIndex = 0;
2626 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2627 splitPointerIndex += 1;
2628 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002629 action = maskedAction |
2630 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631 }
2632 } else {
2633 // An unrelated pointer changed.
2634 action = AMOTION_EVENT_ACTION_MOVE;
2635 }
2636 }
2637
Garfield Tan00f511d2019-06-12 16:55:40 -07002638 MotionEntry* splitMotionEntry =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002639 new MotionEntry(originalMotionEntry.sequenceNum, originalMotionEntry.eventTime,
2640 originalMotionEntry.deviceId, originalMotionEntry.source,
2641 originalMotionEntry.displayId, originalMotionEntry.policyFlags, action,
2642 originalMotionEntry.actionButton, originalMotionEntry.flags,
2643 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2644 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2645 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2646 originalMotionEntry.xCursorPosition,
2647 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002648 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002650 if (originalMotionEntry.injectionState) {
2651 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652 splitMotionEntry->injectionState->refCount += 1;
2653 }
2654
2655 return splitMotionEntry;
2656}
2657
2658void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2659#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002660 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661#endif
2662
2663 bool needWake;
2664 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002665 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002666
Prabir Pradhan42611e02018-11-27 14:04:02 -08002667 ConfigurationChangedEntry* newEntry =
2668 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 needWake = enqueueInboundEventLocked(newEntry);
2670 } // release lock
2671
2672 if (needWake) {
2673 mLooper->wake();
2674 }
2675}
2676
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002677/**
2678 * If one of the meta shortcuts is detected, process them here:
2679 * Meta + Backspace -> generate BACK
2680 * Meta + Enter -> generate HOME
2681 * This will potentially overwrite keyCode and metaState.
2682 */
2683void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002684 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002685 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2686 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2687 if (keyCode == AKEYCODE_DEL) {
2688 newKeyCode = AKEYCODE_BACK;
2689 } else if (keyCode == AKEYCODE_ENTER) {
2690 newKeyCode = AKEYCODE_HOME;
2691 }
2692 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002693 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002694 struct KeyReplacement replacement = {keyCode, deviceId};
2695 mReplacedKeys.add(replacement, newKeyCode);
2696 keyCode = newKeyCode;
2697 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2698 }
2699 } else if (action == AKEY_EVENT_ACTION_UP) {
2700 // In order to maintain a consistent stream of up and down events, check to see if the key
2701 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2702 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002703 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002704 struct KeyReplacement replacement = {keyCode, deviceId};
2705 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2706 if (index >= 0) {
2707 keyCode = mReplacedKeys.valueAt(index);
2708 mReplacedKeys.removeItemsAt(index);
2709 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2710 }
2711 }
2712}
2713
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2715#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002716 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2717 "policyFlags=0x%x, action=0x%x, "
2718 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2719 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2720 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2721 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722#endif
2723 if (!validateKeyEvent(args->action)) {
2724 return;
2725 }
2726
2727 uint32_t policyFlags = args->policyFlags;
2728 int32_t flags = args->flags;
2729 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002730 // InputDispatcher tracks and generates key repeats on behalf of
2731 // whatever notifies it, so repeatCount should always be set to 0
2732 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2734 policyFlags |= POLICY_FLAG_VIRTUAL;
2735 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737 if (policyFlags & POLICY_FLAG_FUNCTION) {
2738 metaState |= AMETA_FUNCTION_ON;
2739 }
2740
2741 policyFlags |= POLICY_FLAG_TRUSTED;
2742
Michael Wright78f24442014-08-06 15:55:28 -07002743 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002744 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002745
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746 KeyEvent event;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002747 event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2748 args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749
Michael Wright2b3c3302018-03-02 17:19:13 +00002750 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002751 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002752 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2753 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002754 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 bool needWake;
2758 { // acquire lock
2759 mLock.lock();
2760
2761 if (shouldSendKeyToInputFilterLocked(args)) {
2762 mLock.unlock();
2763
2764 policyFlags |= POLICY_FLAG_FILTERED;
2765 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2766 return; // event was consumed by the filter
2767 }
2768
2769 mLock.lock();
2770 }
2771
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002772 KeyEntry* newEntry =
2773 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2774 args->displayId, policyFlags, args->action, flags, keyCode,
2775 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776
2777 needWake = enqueueInboundEventLocked(newEntry);
2778 mLock.unlock();
2779 } // release lock
2780
2781 if (needWake) {
2782 mLooper->wake();
2783 }
2784}
2785
2786bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2787 return mInputFilterEnabled;
2788}
2789
2790void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2791#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002792 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan00f511d2019-06-12 16:55:40 -07002793 ", policyFlags=0x%x, "
2794 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
2795 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07002796 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan00f511d2019-06-12 16:55:40 -07002797 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2798 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Jaewan Kim372fbe42019-10-02 10:58:46 +09002799 args->edgeFlags, args->xPrecision, args->yPrecision, args->xCursorPosition,
Garfield Tan00f511d2019-06-12 16:55:40 -07002800 args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801 for (uint32_t i = 0; i < args->pointerCount; i++) {
2802 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002803 "x=%f, y=%f, pressure=%f, size=%f, "
2804 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2805 "orientation=%f",
2806 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2807 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2808 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2809 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2810 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2811 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2812 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2813 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2814 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2815 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816 }
2817#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002818 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2819 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 return;
2821 }
2822
2823 uint32_t policyFlags = args->policyFlags;
2824 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002825
2826 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002827 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002828 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2829 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002830 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832
2833 bool needWake;
2834 { // acquire lock
2835 mLock.lock();
2836
2837 if (shouldSendMotionToInputFilterLocked(args)) {
2838 mLock.unlock();
2839
2840 MotionEvent event;
Garfield Tan00f511d2019-06-12 16:55:40 -07002841 event.initialize(args->deviceId, args->source, args->displayId, args->action,
2842 args->actionButton, args->flags, args->edgeFlags, args->metaState,
2843 args->buttonState, args->classification, 0, 0, args->xPrecision,
2844 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2845 args->downTime, args->eventTime, args->pointerCount,
2846 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847
2848 policyFlags |= POLICY_FLAG_FILTERED;
2849 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2850 return; // event was consumed by the filter
2851 }
2852
2853 mLock.lock();
2854 }
2855
2856 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07002857 MotionEntry* newEntry =
2858 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2859 args->displayId, policyFlags, args->action, args->actionButton,
2860 args->flags, args->metaState, args->buttonState,
2861 args->classification, args->edgeFlags, args->xPrecision,
2862 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2863 args->downTime, args->pointerCount, args->pointerProperties,
2864 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865
2866 needWake = enqueueInboundEventLocked(newEntry);
2867 mLock.unlock();
2868 } // release lock
2869
2870 if (needWake) {
2871 mLooper->wake();
2872 }
2873}
2874
2875bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002876 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877}
2878
2879void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2880#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002881 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002882 "switchMask=0x%08x",
2883 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884#endif
2885
2886 uint32_t policyFlags = args->policyFlags;
2887 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002888 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889}
2890
2891void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2892#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002893 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
2894 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895#endif
2896
2897 bool needWake;
2898 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002899 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900
Prabir Pradhan42611e02018-11-27 14:04:02 -08002901 DeviceResetEntry* newEntry =
2902 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903 needWake = enqueueInboundEventLocked(newEntry);
2904 } // release lock
2905
2906 if (needWake) {
2907 mLooper->wake();
2908 }
2909}
2910
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
2912 int32_t injectorUid, int32_t syncMode,
2913 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914#if DEBUG_INBOUND_EVENT_DETAILS
2915 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002916 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2917 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918#endif
2919
2920 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2921
2922 policyFlags |= POLICY_FLAG_INJECTED;
2923 if (hasInjectionPermission(injectorPid, injectorUid)) {
2924 policyFlags |= POLICY_FLAG_TRUSTED;
2925 }
2926
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07002927 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 case AINPUT_EVENT_TYPE_KEY: {
2930 KeyEvent keyEvent;
2931 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2932 int32_t action = keyEvent.getAction();
2933 if (!validateKeyEvent(action)) {
2934 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002937 int32_t flags = keyEvent.getFlags();
2938 int32_t keyCode = keyEvent.getKeyCode();
2939 int32_t metaState = keyEvent.getMetaState();
2940 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2941 /*byref*/ keyCode, /*byref*/ metaState);
2942 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
2943 keyEvent.getDisplayId(), action, flags, keyCode,
2944 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
2945 keyEvent.getDownTime(), keyEvent.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002947 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2948 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00002949 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002950
2951 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2952 android::base::Timer t;
2953 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
2954 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2955 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2956 std::to_string(t.duration().count()).c_str());
2957 }
2958 }
2959
2960 mLock.lock();
2961 KeyEntry* injectedEntry =
2962 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
2963 keyEvent.getDeviceId(), keyEvent.getSource(),
2964 keyEvent.getDisplayId(), policyFlags, action, flags,
2965 keyEvent.getKeyCode(), keyEvent.getScanCode(),
2966 keyEvent.getMetaState(), keyEvent.getRepeatCount(),
2967 keyEvent.getDownTime());
2968 injectedEntries.push(injectedEntry);
2969 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970 }
2971
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002972 case AINPUT_EVENT_TYPE_MOTION: {
2973 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2974 int32_t action = motionEvent->getAction();
2975 size_t pointerCount = motionEvent->getPointerCount();
2976 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2977 int32_t actionButton = motionEvent->getActionButton();
2978 int32_t displayId = motionEvent->getDisplayId();
2979 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
2980 return INPUT_EVENT_INJECTION_FAILED;
2981 }
2982
2983 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2984 nsecs_t eventTime = motionEvent->getEventTime();
2985 android::base::Timer t;
2986 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
2987 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2988 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2989 std::to_string(t.duration().count()).c_str());
2990 }
2991 }
2992
2993 mLock.lock();
2994 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2995 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2996 MotionEntry* injectedEntry =
Garfield Tan00f511d2019-06-12 16:55:40 -07002997 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2998 motionEvent->getDeviceId(), motionEvent->getSource(),
2999 motionEvent->getDisplayId(), policyFlags, action, actionButton,
3000 motionEvent->getFlags(), motionEvent->getMetaState(),
3001 motionEvent->getButtonState(), motionEvent->getClassification(),
3002 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3003 motionEvent->getYPrecision(),
3004 motionEvent->getRawXCursorPosition(),
3005 motionEvent->getRawYCursorPosition(),
3006 motionEvent->getDownTime(), uint32_t(pointerCount),
3007 pointerProperties, samplePointerCoords,
3008 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003009 injectedEntries.push(injectedEntry);
3010 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3011 sampleEventTimes += 1;
3012 samplePointerCoords += pointerCount;
3013 MotionEntry* nextInjectedEntry =
3014 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3015 motionEvent->getDeviceId(), motionEvent->getSource(),
3016 motionEvent->getDisplayId(), policyFlags, action,
3017 actionButton, motionEvent->getFlags(),
3018 motionEvent->getMetaState(), motionEvent->getButtonState(),
3019 motionEvent->getClassification(),
3020 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3021 motionEvent->getYPrecision(),
3022 motionEvent->getRawXCursorPosition(),
3023 motionEvent->getRawYCursorPosition(),
3024 motionEvent->getDownTime(), uint32_t(pointerCount),
3025 pointerProperties, samplePointerCoords,
3026 motionEvent->getXOffset(), motionEvent->getYOffset());
3027 injectedEntries.push(nextInjectedEntry);
3028 }
3029 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003032 default:
3033 ALOGW("Cannot inject event of type %d", event->getType());
3034 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003035 }
3036
3037 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3038 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3039 injectionState->injectionIsAsync = true;
3040 }
3041
3042 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003043 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044
3045 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003046 while (!injectedEntries.empty()) {
3047 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3048 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049 }
3050
3051 mLock.unlock();
3052
3053 if (needWake) {
3054 mLooper->wake();
3055 }
3056
3057 int32_t injectionResult;
3058 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003059 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003060
3061 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3062 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3063 } else {
3064 for (;;) {
3065 injectionResult = injectionState->injectionResult;
3066 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3067 break;
3068 }
3069
3070 nsecs_t remainingTimeout = endTime - now();
3071 if (remainingTimeout <= 0) {
3072#if DEBUG_INJECTION
3073 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003074 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003075#endif
3076 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3077 break;
3078 }
3079
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003080 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081 }
3082
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003083 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3084 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085 while (injectionState->pendingForegroundDispatches != 0) {
3086#if DEBUG_INJECTION
3087 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089#endif
3090 nsecs_t remainingTimeout = endTime - now();
3091 if (remainingTimeout <= 0) {
3092#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003093 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3094 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095#endif
3096 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3097 break;
3098 }
3099
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003100 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 }
3102 }
3103 }
3104
3105 injectionState->release();
3106 } // release lock
3107
3108#if DEBUG_INJECTION
3109 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003110 "injectorPid=%d, injectorUid=%d",
3111 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112#endif
3113
3114 return injectionResult;
3115}
3116
3117bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003118 return injectorUid == 0 ||
3119 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120}
3121
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003122void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003123 InjectionState* injectionState = entry->injectionState;
3124 if (injectionState) {
3125#if DEBUG_INJECTION
3126 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003127 "injectorPid=%d, injectorUid=%d",
3128 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129#endif
3130
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003131 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 // Log the outcome since the injector did not wait for the injection result.
3133 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003134 case INPUT_EVENT_INJECTION_SUCCEEDED:
3135 ALOGV("Asynchronous input event injection succeeded.");
3136 break;
3137 case INPUT_EVENT_INJECTION_FAILED:
3138 ALOGW("Asynchronous input event injection failed.");
3139 break;
3140 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3141 ALOGW("Asynchronous input event injection permission denied.");
3142 break;
3143 case INPUT_EVENT_INJECTION_TIMED_OUT:
3144 ALOGW("Asynchronous input event injection timed out.");
3145 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 }
3147 }
3148
3149 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003150 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 }
3152}
3153
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003154void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155 InjectionState* injectionState = entry->injectionState;
3156 if (injectionState) {
3157 injectionState->pendingForegroundDispatches += 1;
3158 }
3159}
3160
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003161void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 InjectionState* injectionState = entry->injectionState;
3163 if (injectionState) {
3164 injectionState->pendingForegroundDispatches -= 1;
3165
3166 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003167 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168 }
3169 }
3170}
3171
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003172std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3173 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003174 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003175}
3176
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003178 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003179 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003180 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3181 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003182 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003183 return windowHandle;
3184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 }
3186 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003187 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188}
3189
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003190bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003191 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003192 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3193 for (const sp<InputWindowHandle>& handle : windowHandles) {
3194 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003195 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003196 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003197 ", but it should belong to display %" PRId32,
3198 windowHandle->getName().c_str(), it.first,
3199 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003200 }
3201 return true;
3202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 }
3204 }
3205 return false;
3206}
3207
Robert Carr5c8a0262018-10-03 16:30:44 -07003208sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3209 size_t count = mInputChannelsByToken.count(token);
3210 if (count == 0) {
3211 return nullptr;
3212 }
3213 return mInputChannelsByToken.at(token);
3214}
3215
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003216void InputDispatcher::updateWindowHandlesForDisplayLocked(
3217 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3218 if (inputWindowHandles.empty()) {
3219 // Remove all handles on a display if there are no windows left.
3220 mWindowHandlesByDisplay.erase(displayId);
3221 return;
3222 }
3223
3224 // Since we compare the pointer of input window handles across window updates, we need
3225 // to make sure the handle object for the same window stays unchanged across updates.
3226 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
3227 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3228 for (const sp<InputWindowHandle>& handle : oldHandles) {
3229 oldHandlesByTokens[handle->getToken()] = handle;
3230 }
3231
3232 std::vector<sp<InputWindowHandle>> newHandles;
3233 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3234 if (!handle->updateInfo()) {
3235 // handle no longer valid
3236 continue;
3237 }
3238
3239 const InputWindowInfo* info = handle->getInfo();
3240 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3241 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3242 const bool noInputChannel =
3243 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3244 const bool canReceiveInput =
3245 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3246 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3247 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003248 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003249 handle->getName().c_str());
3250 }
3251 continue;
3252 }
3253
3254 if (info->displayId != displayId) {
3255 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3256 handle->getName().c_str(), displayId, info->displayId);
3257 continue;
3258 }
3259
3260 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3261 const sp<InputWindowHandle> oldHandle = oldHandlesByTokens.at(handle->getToken());
3262 oldHandle->updateFrom(handle);
3263 newHandles.push_back(oldHandle);
3264 } else {
3265 newHandles.push_back(handle);
3266 }
3267 }
3268
3269 // Insert or replace
3270 mWindowHandlesByDisplay[displayId] = newHandles;
3271}
3272
Arthur Hungb92218b2018-08-14 12:00:21 +08003273/**
3274 * Called from InputManagerService, update window handle list by displayId that can receive input.
3275 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3276 * If set an empty list, remove all handles from the specific display.
3277 * For focused handle, check if need to change and send a cancel event to previous one.
3278 * For removed handle, check if need to send a cancel event if already in touch.
3279 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003280void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003281 int32_t displayId,
3282 const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003283 if (DEBUG_FOCUS) {
3284 std::string windowList;
3285 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3286 windowList += iwh->getName() + " ";
3287 }
3288 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003291 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292
Arthur Hungb92218b2018-08-14 12:00:21 +08003293 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003294 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3295 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003297 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
3298
Tiger Huang721e26f2018-07-24 22:26:19 +08003299 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 bool foundHoveredWindow = false;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003301 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3302 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3303 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3304 windowHandle->getInfo()->visible) {
3305 newFocusedWindowHandle = windowHandle;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003306 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003307 if (windowHandle == mLastHoverWindowHandle) {
3308 foundHoveredWindow = true;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 }
3311
3312 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003313 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314 }
3315
Tiger Huang721e26f2018-07-24 22:26:19 +08003316 sp<InputWindowHandle> oldFocusedWindowHandle =
3317 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3318
3319 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3320 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003321 if (DEBUG_FOCUS) {
3322 ALOGD("Focus left window: %s in display %" PRId32,
3323 oldFocusedWindowHandle->getName().c_str(), displayId);
3324 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003325 sp<InputChannel> focusedInputChannel =
3326 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003327 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 "focus left window");
3330 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003332 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003334 if (newFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003335 if (DEBUG_FOCUS) {
3336 ALOGD("Focus entered window: %s in display %" PRId32,
3337 newFocusedWindowHandle->getName().c_str(), displayId);
3338 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003339 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 }
Robert Carrf759f162018-11-13 12:57:11 -08003341
3342 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003343 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345 }
3346
Arthur Hungb92218b2018-08-14 12:00:21 +08003347 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3348 if (stateIndex >= 0) {
3349 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003350 for (size_t i = 0; i < state.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003351 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003352 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003353 if (DEBUG_FOCUS) {
3354 ALOGD("Touched window was removed: %s in display %" PRId32,
3355 touchedWindow.windowHandle->getName().c_str(), displayId);
3356 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003357 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003358 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003359 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003360 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003361 "touched window was removed");
3362 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3363 options);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003364 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003365 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003366 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369 }
3370 }
3371
3372 // Release information for windows that are no longer present.
3373 // This ensures that unused input channels are released promptly.
3374 // Otherwise, they might stick around until the window handle is destroyed
3375 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003376 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003377 if (!hasWindowHandleLocked(oldWindowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003378 if (DEBUG_FOCUS) {
3379 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
3380 }
Arthur Hung3b413f22018-10-26 18:05:34 +08003381 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 }
3383 }
3384 } // release lock
3385
3386 // Wake up poll loop since it may need to make new input dispatching choices.
3387 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003388
3389 if (setInputWindowsListener) {
3390 setInputWindowsListener->onSetInputWindowsFinished();
3391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392}
3393
3394void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003395 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003396 if (DEBUG_FOCUS) {
3397 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3398 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003401 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402
Tiger Huang721e26f2018-07-24 22:26:19 +08003403 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3404 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003405 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003406 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3407 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003410 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003412 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003414 oldFocusedApplicationHandle.clear();
3415 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417 } // release lock
3418
3419 // Wake up poll loop since it may need to make new input dispatching choices.
3420 mLooper->wake();
3421}
3422
Tiger Huang721e26f2018-07-24 22:26:19 +08003423/**
3424 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3425 * the display not specified.
3426 *
3427 * We track any unreleased events for each window. If a window loses the ability to receive the
3428 * released event, we will send a cancel event to it. So when the focused display is changed, we
3429 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3430 * display. The display-specified events won't be affected.
3431 */
3432void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003433 if (DEBUG_FOCUS) {
3434 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3435 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003436 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003437 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003438
3439 if (mFocusedDisplayId != displayId) {
3440 sp<InputWindowHandle> oldFocusedWindowHandle =
3441 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3442 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003443 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003444 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003445 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003446 CancelationOptions
3447 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3448 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003449 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003450 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3451 }
3452 }
3453 mFocusedDisplayId = displayId;
3454
3455 // Sanity check
3456 sp<InputWindowHandle> newFocusedWindowHandle =
3457 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003458 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003459
Tiger Huang721e26f2018-07-24 22:26:19 +08003460 if (newFocusedWindowHandle == nullptr) {
3461 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3462 if (!mFocusedWindowHandlesByDisplay.empty()) {
3463 ALOGE("But another display has a focused window:");
3464 for (auto& it : mFocusedWindowHandlesByDisplay) {
3465 const int32_t displayId = it.first;
3466 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003467 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3468 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003469 }
3470 }
3471 }
3472 }
3473
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003474 if (DEBUG_FOCUS) {
3475 logDispatchStateLocked();
3476 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003477 } // release lock
3478
3479 // Wake up poll loop since it may need to make new input dispatching choices.
3480 mLooper->wake();
3481}
3482
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003484 if (DEBUG_FOCUS) {
3485 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487
3488 bool changed;
3489 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003490 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491
3492 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3493 if (mDispatchFrozen && !frozen) {
3494 resetANRTimeoutsLocked();
3495 }
3496
3497 if (mDispatchEnabled && !enabled) {
3498 resetAndDropEverythingLocked("dispatcher is being disabled");
3499 }
3500
3501 mDispatchEnabled = enabled;
3502 mDispatchFrozen = frozen;
3503 changed = true;
3504 } else {
3505 changed = false;
3506 }
3507
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003508 if (DEBUG_FOCUS) {
3509 logDispatchStateLocked();
3510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 } // release lock
3512
3513 if (changed) {
3514 // Wake up poll loop since it may need to make new input dispatching choices.
3515 mLooper->wake();
3516 }
3517}
3518
3519void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003520 if (DEBUG_FOCUS) {
3521 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523
3524 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003525 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526
3527 if (mInputFilterEnabled == enabled) {
3528 return;
3529 }
3530
3531 mInputFilterEnabled = enabled;
3532 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3533 } // release lock
3534
3535 // Wake up poll loop since there might be work to do to drop everything.
3536 mLooper->wake();
3537}
3538
chaviwfbe5d9c2018-12-26 12:23:37 -08003539bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3540 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003541 if (DEBUG_FOCUS) {
3542 ALOGD("Trivial transfer to same window.");
3543 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003544 return true;
3545 }
3546
Michael Wrightd02c5b62014-02-10 15:10:22 -08003547 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003548 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549
chaviwfbe5d9c2018-12-26 12:23:37 -08003550 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3551 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003552 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003553 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554 return false;
3555 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003556 if (DEBUG_FOCUS) {
3557 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3558 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003561 if (DEBUG_FOCUS) {
3562 ALOGD("Cannot transfer focus because windows are on different displays.");
3563 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 return false;
3565 }
3566
3567 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003568 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3569 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3570 for (size_t i = 0; i < state.windows.size(); i++) {
3571 const TouchedWindow& touchedWindow = state.windows[i];
3572 if (touchedWindow.windowHandle == fromWindowHandle) {
3573 int32_t oldTargetFlags = touchedWindow.targetFlags;
3574 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003576 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003578 int32_t newTargetFlags = oldTargetFlags &
3579 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3580 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003581 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582
Jeff Brownf086ddb2014-02-11 14:28:48 -08003583 found = true;
3584 goto Found;
3585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 }
3587 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003588 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003590 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003591 if (DEBUG_FOCUS) {
3592 ALOGD("Focus transfer failed because from window did not have focus.");
3593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 return false;
3595 }
3596
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003597 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3598 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003599 if (fromConnection != nullptr && toConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003601 CancelationOptions
3602 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3603 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3605 }
3606
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003607 if (DEBUG_FOCUS) {
3608 logDispatchStateLocked();
3609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 } // release lock
3611
3612 // Wake up poll loop since it may need to make new input dispatching choices.
3613 mLooper->wake();
3614 return true;
3615}
3616
3617void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003618 if (DEBUG_FOCUS) {
3619 ALOGD("Resetting and dropping all events (%s).", reason);
3620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621
3622 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3623 synthesizeCancelationEventsForAllConnectionsLocked(options);
3624
3625 resetKeyRepeatLocked();
3626 releasePendingEventLocked();
3627 drainInboundQueueLocked();
3628 resetANRTimeoutsLocked();
3629
Jeff Brownf086ddb2014-02-11 14:28:48 -08003630 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003632 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633}
3634
3635void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003636 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 dumpDispatchStateLocked(dump);
3638
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003639 std::istringstream stream(dump);
3640 std::string line;
3641
3642 while (std::getline(stream, line, '\n')) {
3643 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 }
3645}
3646
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003647void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003648 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3649 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3650 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003651 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652
Tiger Huang721e26f2018-07-24 22:26:19 +08003653 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3654 dump += StringPrintf(INDENT "FocusedApplications:\n");
3655 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3656 const int32_t displayId = it.first;
3657 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003658 dump += StringPrintf(INDENT2 "displayId=%" PRId32
3659 ", name='%s', dispatchingTimeout=%0.3fms\n",
3660 displayId, applicationHandle->getName().c_str(),
3661 applicationHandle->getDispatchingTimeout(
3662 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3663 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08003664 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003665 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003666 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003667 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003668
3669 if (!mFocusedWindowHandlesByDisplay.empty()) {
3670 dump += StringPrintf(INDENT "FocusedWindows:\n");
3671 for (auto& it : mFocusedWindowHandlesByDisplay) {
3672 const int32_t displayId = it.first;
3673 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003674 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3675 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003676 }
3677 } else {
3678 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3679 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680
Jeff Brownf086ddb2014-02-11 14:28:48 -08003681 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003682 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003683 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3684 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003685 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003686 state.displayId, toString(state.down), toString(state.split),
3687 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003688 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003689 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003690 for (size_t i = 0; i < state.windows.size(); i++) {
3691 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003692 dump += StringPrintf(INDENT4
3693 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3694 i, touchedWindow.windowHandle->getName().c_str(),
3695 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003696 }
3697 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003698 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003699 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003700 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003701 dump += INDENT3 "Portal windows:\n";
3702 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003703 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003704 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3705 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003706 }
3707 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 }
3709 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003710 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 }
3712
Arthur Hungb92218b2018-08-14 12:00:21 +08003713 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003714 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003715 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003716 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003717 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003718 dump += INDENT2 "Windows:\n";
3719 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003720 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003721 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722
Arthur Hungb92218b2018-08-14 12:00:21 +08003723 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003724 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
3725 "hasWallpaper=%s, "
3726 "visible=%s, canReceiveKeys=%s, flags=0x%08x, "
3727 "type=0x%08x, layer=%d, "
3728 "frame=[%d,%d][%d,%d], globalScale=%f, "
3729 "windowScale=(%f,%f), "
3730 "touchableRegion=",
3731 i, windowInfo->name.c_str(), windowInfo->displayId,
3732 windowInfo->portalToDisplayId,
3733 toString(windowInfo->paused),
3734 toString(windowInfo->hasFocus),
3735 toString(windowInfo->hasWallpaper),
3736 toString(windowInfo->visible),
3737 toString(windowInfo->canReceiveKeys),
3738 windowInfo->layoutParamsFlags,
3739 windowInfo->layoutParamsType, windowInfo->layer,
3740 windowInfo->frameLeft, windowInfo->frameTop,
3741 windowInfo->frameRight, windowInfo->frameBottom,
3742 windowInfo->globalScaleFactor, windowInfo->windowXScale,
3743 windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003744 dumpRegion(dump, windowInfo->touchableRegion);
3745 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3746 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003747 windowInfo->ownerPid, windowInfo->ownerUid,
3748 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08003749 }
3750 } else {
3751 dump += INDENT2 "Windows: <none>\n";
3752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 }
3754 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003755 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 }
3757
Michael Wright3dd60e22019-03-27 22:06:44 +00003758 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003759 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003760 const std::vector<Monitor>& monitors = it.second;
3761 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3762 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003763 }
3764 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003765 const std::vector<Monitor>& monitors = it.second;
3766 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3767 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003770 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 }
3772
3773 nsecs_t currentTime = now();
3774
3775 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003776 if (!mRecentQueue.empty()) {
3777 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
3778 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003779 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003781 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 }
3783 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003784 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 }
3786
3787 // Dump event currently being dispatched.
3788 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003789 dump += INDENT "PendingEvent:\n";
3790 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003792 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003793 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003795 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 }
3797
3798 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003799 if (!mInboundQueue.empty()) {
3800 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
3801 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003802 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003804 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 }
3806 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003807 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808 }
3809
Michael Wright78f24442014-08-06 15:55:28 -07003810 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003811 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003812 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3813 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3814 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003815 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3816 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07003817 }
3818 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003819 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003820 }
3821
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003822 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003823 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003824 for (const auto& pair : mConnectionsByFd) {
3825 const sp<Connection>& connection = pair.second;
3826 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
3827 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3828 pair.first, connection->getInputChannelName().c_str(),
3829 connection->getWindowName().c_str(), connection->getStatusLabel(),
3830 toString(connection->monitor),
3831 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003833 if (!connection->outboundQueue.empty()) {
3834 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
3835 connection->outboundQueue.size());
3836 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837 dump.append(INDENT4);
3838 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003839 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003840 entry->targetFlags, entry->resolvedAction,
3841 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 }
3843 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003844 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003845 }
3846
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003847 if (!connection->waitQueue.empty()) {
3848 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
3849 connection->waitQueue.size());
3850 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003851 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003853 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003854 "age=%0.1fms, wait=%0.1fms\n",
3855 entry->targetFlags, entry->resolvedAction,
3856 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3857 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858 }
3859 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003860 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861 }
3862 }
3863 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003864 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865 }
3866
3867 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003868 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003869 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003871 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 }
3873
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003874 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003875 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003876 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003877 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878}
3879
Michael Wright3dd60e22019-03-27 22:06:44 +00003880void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3881 const size_t numMonitors = monitors.size();
3882 for (size_t i = 0; i < numMonitors; i++) {
3883 const Monitor& monitor = monitors[i];
3884 const sp<InputChannel>& channel = monitor.inputChannel;
3885 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3886 dump += "\n";
3887 }
3888}
3889
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003890status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003892 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893#endif
3894
3895 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003896 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003897 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003898 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003900 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901 return BAD_VALUE;
3902 }
3903
Michael Wright3dd60e22019-03-27 22:06:44 +00003904 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905
3906 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003907 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003908 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3911 } // release lock
3912
3913 // Wake the looper because some connections have changed.
3914 mLooper->wake();
3915 return OK;
3916}
3917
Michael Wright3dd60e22019-03-27 22:06:44 +00003918status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003919 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003920 { // acquire lock
3921 std::scoped_lock _l(mLock);
3922
3923 if (displayId < 0) {
3924 ALOGW("Attempted to register input monitor without a specified display.");
3925 return BAD_VALUE;
3926 }
3927
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003928 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003929 ALOGW("Attempted to register input monitor without an identifying token.");
3930 return BAD_VALUE;
3931 }
3932
3933 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3934
3935 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003936 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003937 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00003938
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003939 auto& monitorsByDisplay =
3940 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00003941 monitorsByDisplay[displayId].emplace_back(inputChannel);
3942
3943 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00003944 }
3945 // Wake the looper because some connections have changed.
3946 mLooper->wake();
3947 return OK;
3948}
3949
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3951#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003952 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953#endif
3954
3955 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003956 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957
3958 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3959 if (status) {
3960 return status;
3961 }
3962 } // release lock
3963
3964 // Wake the poll loop because removing the connection may have changed the current
3965 // synchronization state.
3966 mLooper->wake();
3967 return OK;
3968}
3969
3970status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003971 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003972 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003973 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003975 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 return BAD_VALUE;
3977 }
3978
John Recke0710582019-09-26 13:46:12 -07003979 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003980 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003981 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07003982
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 if (connection->monitor) {
3984 removeMonitorChannelLocked(inputChannel);
3985 }
3986
3987 mLooper->removeFd(inputChannel->getFd());
3988
3989 nsecs_t currentTime = now();
3990 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3991
3992 connection->status = Connection::STATUS_ZOMBIE;
3993 return OK;
3994}
3995
3996void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003997 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
3998 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
3999}
4000
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004001void InputDispatcher::removeMonitorChannelLocked(
4002 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004003 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004004 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004005 std::vector<Monitor>& monitors = it->second;
4006 const size_t numMonitors = monitors.size();
4007 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004008 if (monitors[i].inputChannel == inputChannel) {
4009 monitors.erase(monitors.begin() + i);
4010 break;
4011 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004012 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004013 if (monitors.empty()) {
4014 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004015 } else {
4016 ++it;
4017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018 }
4019}
4020
Michael Wright3dd60e22019-03-27 22:06:44 +00004021status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4022 { // acquire lock
4023 std::scoped_lock _l(mLock);
4024 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4025
4026 if (!foundDisplayId) {
4027 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4028 return BAD_VALUE;
4029 }
4030 int32_t displayId = foundDisplayId.value();
4031
4032 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4033 if (stateIndex < 0) {
4034 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4035 return BAD_VALUE;
4036 }
4037
4038 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4039 std::optional<int32_t> foundDeviceId;
4040 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004041 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004042 foundDeviceId = state.deviceId;
4043 }
4044 }
4045 if (!foundDeviceId || !state.down) {
4046 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004047 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004048 return BAD_VALUE;
4049 }
4050 int32_t deviceId = foundDeviceId.value();
4051
4052 // Send cancel events to all the input channels we're stealing from.
4053 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004054 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004055 options.deviceId = deviceId;
4056 options.displayId = displayId;
4057 for (const TouchedWindow& window : state.windows) {
4058 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
4059 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4060 }
4061 // Then clear the current touch state so we stop dispatching to them as well.
4062 state.filterNonMonitors();
4063 }
4064 return OK;
4065}
4066
Michael Wright3dd60e22019-03-27 22:06:44 +00004067std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4068 const sp<IBinder>& token) {
4069 for (const auto& it : mGestureMonitorsByDisplay) {
4070 const std::vector<Monitor>& monitors = it.second;
4071 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004072 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004073 return it.first;
4074 }
4075 }
4076 }
4077 return std::nullopt;
4078}
4079
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004080sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4081 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004082 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004083 }
4084
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004085 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004086 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004087 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004088 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 }
4090 }
Robert Carr4e670e52018-08-15 13:26:12 -07004091
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004092 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093}
4094
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004095void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4096 const sp<Connection>& connection, uint32_t seq,
4097 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004098 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4099 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 commandEntry->connection = connection;
4101 commandEntry->eventTime = currentTime;
4102 commandEntry->seq = seq;
4103 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004104 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105}
4106
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004107void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4108 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004110 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004112 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4113 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004115 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116}
4117
chaviw0c06c6e2019-01-09 13:27:07 -08004118void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004119 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004120 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4121 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004122 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4123 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004124 commandEntry->oldToken = oldToken;
4125 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004126 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004127}
4128
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004129void InputDispatcher::onANRLocked(nsecs_t currentTime,
4130 const sp<InputApplicationHandle>& applicationHandle,
4131 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4132 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4134 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4135 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004136 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4137 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4138 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139
4140 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004141 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 struct tm tm;
4143 localtime_r(&t, &tm);
4144 char timestr[64];
4145 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4146 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004147 mLastANRState += INDENT "ANR:\n";
4148 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004149 mLastANRState +=
4150 StringPrintf(INDENT2 "Window: %s\n",
4151 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004152 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4153 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4154 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 dumpDispatchStateLocked(mLastANRState);
4156
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004157 std::unique_ptr<CommandEntry> commandEntry =
4158 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004160 commandEntry->inputChannel =
4161 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004163 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164}
4165
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004166void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167 mLock.unlock();
4168
4169 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4170
4171 mLock.lock();
4172}
4173
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004174void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 sp<Connection> connection = commandEntry->connection;
4176
4177 if (connection->status != Connection::STATUS_ZOMBIE) {
4178 mLock.unlock();
4179
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004180 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181
4182 mLock.lock();
4183 }
4184}
4185
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004186void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004187 sp<IBinder> oldToken = commandEntry->oldToken;
4188 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004189 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004190 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004191 mLock.lock();
4192}
4193
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004194void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004195 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004196 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197 mLock.unlock();
4198
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004199 nsecs_t newTimeout =
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004200 mPolicy->notifyANR(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201
4202 mLock.lock();
4203
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004204 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205}
4206
4207void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4208 CommandEntry* commandEntry) {
4209 KeyEntry* entry = commandEntry->keyEntry;
4210
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004211 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212
4213 mLock.unlock();
4214
Michael Wright2b3c3302018-03-02 17:19:13 +00004215 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004216 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004217 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004218 : nullptr;
4219 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004220 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4221 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004222 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004223 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224
4225 mLock.lock();
4226
4227 if (delay < 0) {
4228 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4229 } else if (!delay) {
4230 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4231 } else {
4232 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4233 entry->interceptKeyWakeupTime = now() + delay;
4234 }
4235 entry->release();
4236}
4237
chaviwfd6d3512019-03-25 13:23:49 -07004238void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4239 mLock.unlock();
4240 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4241 mLock.lock();
4242}
4243
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004244void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004246 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004248 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249
4250 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004251 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004252 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004253 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004255 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004256
4257 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4258 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4259 std::string msg =
4260 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4261 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4262 dispatchEntry->eventEntry->appendDescription(msg);
4263 ALOGI("%s", msg.c_str());
4264 }
4265
4266 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004267 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004268 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4269 restartEvent =
4270 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004271 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004272 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4273 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4274 handled);
4275 } else {
4276 restartEvent = false;
4277 }
4278
4279 // Dequeue the event and start the next cycle.
4280 // Note that because the lock might have been released, it is possible that the
4281 // contents of the wait queue to have been drained, so we need to double-check
4282 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004283 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4284 if (dispatchEntryIt != connection->waitQueue.end()) {
4285 dispatchEntry = *dispatchEntryIt;
4286 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004287 traceWaitQueueLength(connection);
4288 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004289 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004290 traceOutboundQueueLength(connection);
4291 } else {
4292 releaseDispatchEntry(dispatchEntry);
4293 }
4294 }
4295
4296 // Start the next dispatch cycle for this connection.
4297 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298}
4299
4300bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004301 DispatchEntry* dispatchEntry,
4302 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004303 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004304 if (!handled) {
4305 // Report the key as unhandled, since the fallback was not handled.
4306 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4307 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004308 return false;
4309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004311 // Get the fallback key state.
4312 // Clear it out after dispatching the UP.
4313 int32_t originalKeyCode = keyEntry->keyCode;
4314 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4315 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4316 connection->inputState.removeFallbackKey(originalKeyCode);
4317 }
4318
4319 if (handled || !dispatchEntry->hasForegroundTarget()) {
4320 // If the application handles the original key for which we previously
4321 // generated a fallback or if the window is not a foreground window,
4322 // then cancel the associated fallback key, if any.
4323 if (fallbackKeyCode != -1) {
4324 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004326 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004327 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4328 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4329 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004331 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004332 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333
4334 mLock.unlock();
4335
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004336 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004337 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338
4339 mLock.lock();
4340
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004341 // Cancel the fallback key.
4342 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004344 "application handled the original non-fallback key "
4345 "or is no longer a foreground target, "
4346 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 options.keyCode = fallbackKeyCode;
4348 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004350 connection->inputState.removeFallbackKey(originalKeyCode);
4351 }
4352 } else {
4353 // If the application did not handle a non-fallback key, first check
4354 // that we are in a good state to perform unhandled key event processing
4355 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004356 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004357 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004359 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004360 "since this is not an initial down. "
4361 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4362 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004364 return false;
4365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004367 // Dispatch the unhandled key to the policy.
4368#if DEBUG_OUTBOUND_EVENT_DETAILS
4369 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004370 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4371 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004372#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004373 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004374
4375 mLock.unlock();
4376
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004377 bool fallback =
4378 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4379 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004380
4381 mLock.lock();
4382
4383 if (connection->status != Connection::STATUS_NORMAL) {
4384 connection->inputState.removeFallbackKey(originalKeyCode);
4385 return false;
4386 }
4387
4388 // Latch the fallback keycode for this key on an initial down.
4389 // The fallback keycode cannot change at any other point in the lifecycle.
4390 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004392 fallbackKeyCode = event.getKeyCode();
4393 } else {
4394 fallbackKeyCode = AKEYCODE_UNKNOWN;
4395 }
4396 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4397 }
4398
4399 ALOG_ASSERT(fallbackKeyCode != -1);
4400
4401 // Cancel the fallback key if the policy decides not to send it anymore.
4402 // We will continue to dispatch the key to the policy but we will no
4403 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004404 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4405 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004406#if DEBUG_OUTBOUND_EVENT_DETAILS
4407 if (fallback) {
4408 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004409 "as a fallback for %d, but on the DOWN it had requested "
4410 "to send %d instead. Fallback canceled.",
4411 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004412 } else {
4413 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004414 "but on the DOWN it had requested to send %d. "
4415 "Fallback canceled.",
4416 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004417 }
4418#endif
4419
4420 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4421 "canceling fallback, policy no longer desires it");
4422 options.keyCode = fallbackKeyCode;
4423 synthesizeCancelationEventsForConnectionLocked(connection, options);
4424
4425 fallback = false;
4426 fallbackKeyCode = AKEYCODE_UNKNOWN;
4427 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004428 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004429 }
4430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431
4432#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004433 {
4434 std::string msg;
4435 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4436 connection->inputState.getFallbackKeys();
4437 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004438 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004440 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004441 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004442 }
4443#endif
4444
4445 if (fallback) {
4446 // Restart the dispatch cycle using the fallback key.
4447 keyEntry->eventTime = event.getEventTime();
4448 keyEntry->deviceId = event.getDeviceId();
4449 keyEntry->source = event.getSource();
4450 keyEntry->displayId = event.getDisplayId();
4451 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4452 keyEntry->keyCode = fallbackKeyCode;
4453 keyEntry->scanCode = event.getScanCode();
4454 keyEntry->metaState = event.getMetaState();
4455 keyEntry->repeatCount = event.getRepeatCount();
4456 keyEntry->downTime = event.getDownTime();
4457 keyEntry->syntheticRepeat = false;
4458
4459#if DEBUG_OUTBOUND_EVENT_DETAILS
4460 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004461 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4462 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004463#endif
4464 return true; // restart the event
4465 } else {
4466#if DEBUG_OUTBOUND_EVENT_DETAILS
4467 ALOGD("Unhandled key event: No fallback key.");
4468#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004469
4470 // Report the key as unhandled, since there is no fallback key.
4471 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472 }
4473 }
4474 return false;
4475}
4476
4477bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004478 DispatchEntry* dispatchEntry,
4479 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480 return false;
4481}
4482
4483void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4484 mLock.unlock();
4485
4486 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4487
4488 mLock.lock();
4489}
4490
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004491KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4492 KeyEvent event;
4493 event.initialize(entry.deviceId, entry.source, entry.displayId, entry.action, entry.flags,
4494 entry.keyCode, entry.scanCode, entry.metaState, entry.repeatCount,
4495 entry.downTime, entry.eventTime);
4496 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497}
4498
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004499void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004500 int32_t injectionResult,
4501 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502 // TODO Write some statistics about how long we spend waiting.
4503}
4504
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004505/**
4506 * Report the touch event latency to the statsd server.
4507 * Input events are reported for statistics if:
4508 * - This is a touchscreen event
4509 * - InputFilter is not enabled
4510 * - Event is not injected or synthesized
4511 *
4512 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4513 * from getting aggregated with the "old" data.
4514 */
4515void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4516 REQUIRES(mLock) {
4517 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4518 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4519 if (!reportForStatistics) {
4520 return;
4521 }
4522
4523 if (mTouchStatistics.shouldReport()) {
4524 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4525 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4526 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4527 mTouchStatistics.reset();
4528 }
4529 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4530 mTouchStatistics.addValue(latencyMicros);
4531}
4532
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533void InputDispatcher::traceInboundQueueLengthLocked() {
4534 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004535 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536 }
4537}
4538
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004539void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540 if (ATRACE_ENABLED()) {
4541 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004542 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004543 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544 }
4545}
4546
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004547void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548 if (ATRACE_ENABLED()) {
4549 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004550 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004551 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552 }
4553}
4554
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004555void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004556 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004558 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559 dumpDispatchStateLocked(dump);
4560
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004561 if (!mLastANRState.empty()) {
4562 dump += "\nInput Dispatcher State at time of last ANR:\n";
4563 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 }
4565}
4566
4567void InputDispatcher::monitor() {
4568 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004569 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004571 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572}
4573
Garfield Tane84e6f92019-08-29 17:28:41 -07004574} // namespace android::inputdispatcher