blob: b9bec441b01f11d79fd92f51e7cd16ae3d21b94e [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Garfield Tane84e6f92019-08-29 17:28:41 -070048#include "Connection.h"
49
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <errno.h>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080051#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <limits.h>
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -050053#include <statslog.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080055#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056#include <unistd.h>
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -070057#include <queue>
58#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070059
Michael Wright2b3c3302018-03-02 17:19:13 +000060#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070062#include <binder/Binder.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070063#include <log/log.h>
64#include <powermanager/PowerManager.h>
65#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080066
67#define INDENT " "
68#define INDENT2 " "
69#define INDENT3 " "
70#define INDENT4 " "
71
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080072using android::base::StringPrintf;
73
Garfield Tane84e6f92019-08-29 17:28:41 -070074namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
76// Default input dispatching timeout if there is no focused application or paused window
77// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000078constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Amount of time to allow for all pending events to be processed when an app switch
81// key is on the way. This is used to preempt input dispatch and drop input events
82// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000083constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow for an event to be dispatched (measured since its eventTime)
86// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000087constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080088
89// Amount of time to allow touch events to be streamed out to a connection before requiring
90// that the first event be finished. This value extends the ANR timeout by the specified
91// amount. For example, if streaming is allowed to get ahead by one second relative to the
92// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000093constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
95// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000096constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
97
98// Log a warning when an interception call takes longer than this to process.
99constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100
101// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000102constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104static inline nsecs_t now() {
105 return systemTime(SYSTEM_TIME_MONOTONIC);
106}
107
108static inline const char* toString(bool value) {
109 return value ? "true" : "false";
110}
111
112static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700113 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
114 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800115}
116
117static bool isValidKeyAction(int32_t action) {
118 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700119 case AKEY_EVENT_ACTION_DOWN:
120 case AKEY_EVENT_ACTION_UP:
121 return true;
122 default:
123 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800124 }
125}
126
127static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700128 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800129 ALOGE("Key event has invalid action code 0x%x", action);
130 return false;
131 }
132 return true;
133}
134
Michael Wright7b159c92015-05-14 14:48:03 +0100135static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700137 case AMOTION_EVENT_ACTION_DOWN:
138 case AMOTION_EVENT_ACTION_UP:
139 case AMOTION_EVENT_ACTION_CANCEL:
140 case AMOTION_EVENT_ACTION_MOVE:
141 case AMOTION_EVENT_ACTION_OUTSIDE:
142 case AMOTION_EVENT_ACTION_HOVER_ENTER:
143 case AMOTION_EVENT_ACTION_HOVER_MOVE:
144 case AMOTION_EVENT_ACTION_HOVER_EXIT:
145 case AMOTION_EVENT_ACTION_SCROLL:
146 return true;
147 case AMOTION_EVENT_ACTION_POINTER_DOWN:
148 case AMOTION_EVENT_ACTION_POINTER_UP: {
149 int32_t index = getMotionEventActionPointerIndex(action);
150 return index >= 0 && index < pointerCount;
151 }
152 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
153 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
154 return actionButton != 0;
155 default:
156 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800157 }
158}
159
Michael Wright7b159c92015-05-14 14:48:03 +0100160static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700161 const PointerProperties* pointerProperties) {
162 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800163 ALOGE("Motion event has invalid action code 0x%x", action);
164 return false;
165 }
166 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000167 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700168 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800169 return false;
170 }
171 BitSet32 pointerIdBits;
172 for (size_t i = 0; i < pointerCount; i++) {
173 int32_t id = pointerProperties[i].id;
174 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700175 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
176 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 return false;
178 }
179 if (pointerIdBits.hasBit(id)) {
180 ALOGE("Motion event has duplicate pointer id %d", id);
181 return false;
182 }
183 pointerIdBits.markBit(id);
184 }
185 return true;
186}
187
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800188static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800190 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 return;
192 }
193
194 bool first = true;
195 Region::const_iterator cur = region.begin();
196 Region::const_iterator const tail = region.end();
197 while (cur != tail) {
198 if (first) {
199 first = false;
200 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800201 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800203 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 cur++;
205 }
206}
207
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700208/**
209 * Find the entry in std::unordered_map by key, and return it.
210 * If the entry is not found, return a default constructed entry.
211 *
212 * Useful when the entries are vectors, since an empty vector will be returned
213 * if the entry is not found.
214 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
215 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700216template <typename K, typename V>
217static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700218 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700219 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800220}
221
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700222/**
223 * Find the entry in std::unordered_map by value, and remove it.
224 * If more than one entry has the same value, then all matching
225 * key-value pairs will be removed.
226 *
227 * Return true if at least one value has been removed.
228 */
229template <typename K, typename V>
230static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
231 bool removed = false;
232 for (auto it = map.begin(); it != map.end();) {
233 if (it->second == value) {
234 it = map.erase(it);
235 removed = true;
236 } else {
237 it++;
238 }
239 }
240 return removed;
241}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242
243// --- InputDispatcher ---
244
Garfield Tan00f511d2019-06-12 16:55:40 -0700245InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
246 : mPolicy(policy),
247 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700248 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tan00f511d2019-06-12 16:55:40 -0700249 mAppSwitchSawKeyDown(false),
250 mAppSwitchDueTime(LONG_LONG_MAX),
251 mNextUnblockedEvent(nullptr),
252 mDispatchEnabled(false),
253 mDispatchFrozen(false),
254 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800255 // mInTouchMode will be initialized by the WindowManager to the default device config.
256 // To avoid leaking stack in case that call never comes, and for tests,
257 // initialize it here anyways.
258 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700259 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
260 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800262 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800263
Yi Kong9b14ac62018-07-17 13:48:38 -0700264 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800265
266 policy->getDispatcherConfiguration(&mConfig);
267}
268
269InputDispatcher::~InputDispatcher() {
270 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800271 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272
273 resetKeyRepeatLocked();
274 releasePendingEventLocked();
275 drainInboundQueueLocked();
276 }
277
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700278 while (!mConnectionsByFd.empty()) {
279 sp<Connection> connection = mConnectionsByFd.begin()->second;
280 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800281 }
282}
283
284void InputDispatcher::dispatchOnce() {
285 nsecs_t nextWakeupTime = LONG_LONG_MAX;
286 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800287 std::scoped_lock _l(mLock);
288 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800289
290 // Run a dispatch loop if there are no pending commands.
291 // The dispatch loop might enqueue commands to run afterwards.
292 if (!haveCommandsLocked()) {
293 dispatchOnceInnerLocked(&nextWakeupTime);
294 }
295
296 // Run all pending commands if there are any.
297 // If any commands were run then force the next poll to wake up immediately.
298 if (runCommandsLockedInterruptible()) {
299 nextWakeupTime = LONG_LONG_MIN;
300 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800301
302 // We are about to enter an infinitely long sleep, because we have no commands or
303 // pending or queued events
304 if (nextWakeupTime == LONG_LONG_MAX) {
305 mDispatcherEnteredIdle.notify_all();
306 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800307 } // release lock
308
309 // Wait for callback or timeout or wake. (make sure we round up, not down)
310 nsecs_t currentTime = now();
311 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
312 mLooper->pollOnce(timeoutMillis);
313}
314
315void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
316 nsecs_t currentTime = now();
317
Jeff Browndc5992e2014-04-11 01:27:26 -0700318 // Reset the key repeat timer whenever normal dispatch is suspended while the
319 // device is in a non-interactive state. This is to ensure that we abort a key
320 // repeat if the device is just coming out of sleep.
321 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800322 resetKeyRepeatLocked();
323 }
324
325 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
326 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100327 if (DEBUG_FOCUS) {
328 ALOGD("Dispatch frozen. Waiting some more.");
329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800330 return;
331 }
332
333 // Optimize latency of app switches.
334 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
335 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
336 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
337 if (mAppSwitchDueTime < *nextWakeupTime) {
338 *nextWakeupTime = mAppSwitchDueTime;
339 }
340
341 // Ready to start a new event.
342 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700343 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700344 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800345 if (isAppSwitchDue) {
346 // The inbound queue is empty so the app switch key we were waiting
347 // for will never arrive. Stop waiting for it.
348 resetPendingAppSwitchLocked(false);
349 isAppSwitchDue = false;
350 }
351
352 // Synthesize a key repeat if appropriate.
353 if (mKeyRepeatState.lastKeyEntry) {
354 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
355 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
356 } else {
357 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
358 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
359 }
360 }
361 }
362
363 // Nothing to do if there is no pending event.
364 if (!mPendingEvent) {
365 return;
366 }
367 } else {
368 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700369 mPendingEvent = mInboundQueue.front();
370 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800371 traceInboundQueueLengthLocked();
372 }
373
374 // Poke user activity for this event.
375 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700376 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800377 }
378
379 // Get ready to dispatch the event.
380 resetANRTimeoutsLocked();
381 }
382
383 // Now we have an event to dispatch.
384 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700385 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800386 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700387 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800388 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700389 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800390 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700391 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800392 }
393
394 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700395 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800396 }
397
398 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700399 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700400 ConfigurationChangedEntry* typedEntry =
401 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
402 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700403 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700404 break;
405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700407 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700408 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
409 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700410 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700411 break;
412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700414 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700415 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
416 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700417 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700418 resetPendingAppSwitchLocked(true);
419 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700420 } else if (dropReason == DropReason::NOT_DROPPED) {
421 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700422 }
423 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700424 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700425 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700426 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700427 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
428 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700429 }
430 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
431 break;
432 }
433
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700434 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700435 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700436 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
437 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700439 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700440 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700441 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700442 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
443 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700444 }
445 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
446 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448 }
449
450 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700451 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700452 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453 }
Michael Wright3a981722015-06-10 15:26:13 +0100454 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455
456 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700457 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458 }
459}
460
461bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700462 bool needWake = mInboundQueue.empty();
463 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464 traceInboundQueueLengthLocked();
465
466 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700467 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700468 // Optimize app switch latency.
469 // If the application takes too long to catch up then we drop all events preceding
470 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700471 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700472 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700473 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700474 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700475 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700476 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800477#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700478 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800479#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700480 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700481 mAppSwitchSawKeyDown = false;
482 needWake = true;
483 }
484 }
485 }
486 break;
487 }
488
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700489 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700490 // Optimize case where the current application is unresponsive and the user
491 // decides to touch a window in a different application.
492 // If the application takes too long to catch up then we drop all events preceding
493 // the touch into the other window.
494 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
495 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
496 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
497 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
498 mInputTargetWaitApplicationToken != nullptr) {
499 int32_t displayId = motionEntry->displayId;
500 int32_t x =
501 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
502 int32_t y =
503 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
504 sp<InputWindowHandle> touchedWindowHandle =
505 findTouchedWindowAtLocked(displayId, x, y);
506 if (touchedWindowHandle != nullptr &&
507 touchedWindowHandle->getApplicationToken() !=
508 mInputTargetWaitApplicationToken) {
509 // User touched a different application than the one we are waiting on.
510 // Flag the event, and start pruning the input queue.
511 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800512 needWake = true;
513 }
514 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700515 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700517 case EventEntry::Type::CONFIGURATION_CHANGED:
518 case EventEntry::Type::DEVICE_RESET: {
519 // nothing to do
520 break;
521 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 }
523
524 return needWake;
525}
526
527void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
528 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700529 mRecentQueue.push_back(entry);
530 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
531 mRecentQueue.front()->release();
532 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533 }
534}
535
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700536sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
537 int32_t y, bool addOutsideTargets,
538 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800540 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
541 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800542 const InputWindowInfo* windowInfo = windowHandle->getInfo();
543 if (windowInfo->displayId == displayId) {
544 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545
546 if (windowInfo->visible) {
547 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700548 bool isTouchModal = (flags &
549 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
550 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800552 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700553 if (portalToDisplayId != ADISPLAY_ID_NONE &&
554 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800555 if (addPortalWindows) {
556 // For the monitoring channels of the display.
557 mTempTouchState.addPortalWindow(windowHandle);
558 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700559 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
560 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 // Found window.
563 return windowHandle;
564 }
565 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800566
567 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700568 mTempTouchState.addOrUpdateWindow(windowHandle,
569 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
570 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800573 }
574 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700575 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576}
577
Garfield Tane84e6f92019-08-29 17:28:41 -0700578std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000579 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
580 std::vector<TouchedMonitor> touchedMonitors;
581
582 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
583 addGestureMonitors(monitors, touchedMonitors);
584 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
585 const InputWindowInfo* windowInfo = portalWindow->getInfo();
586 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700587 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
588 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000589 }
590 return touchedMonitors;
591}
592
593void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700594 std::vector<TouchedMonitor>& outTouchedMonitors,
595 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000596 if (monitors.empty()) {
597 return;
598 }
599 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
600 for (const Monitor& monitor : monitors) {
601 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
602 }
603}
604
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700605void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606 const char* reason;
607 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700608 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700610 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700612 reason = "inbound event was dropped because the policy consumed it";
613 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700614 case DropReason::DISABLED:
615 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700616 ALOGI("Dropped event because input dispatch is disabled.");
617 }
618 reason = "inbound event was dropped because input dispatch is disabled";
619 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700620 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700621 ALOGI("Dropped event because of pending overdue app switch.");
622 reason = "inbound event was dropped because of pending overdue app switch";
623 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700624 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700625 ALOGI("Dropped event because the current application is not responding and the user "
626 "has started interacting with a different application.");
627 reason = "inbound event was dropped because the current application is not responding "
628 "and the user has started interacting with a different application";
629 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700630 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700631 ALOGI("Dropped event because it is stale.");
632 reason = "inbound event was dropped because it is stale";
633 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700634 case DropReason::NOT_DROPPED: {
635 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700636 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800638 }
639
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700640 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700641 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
643 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700644 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700646 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700647 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
648 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700649 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
650 synthesizeCancelationEventsForAllConnectionsLocked(options);
651 } else {
652 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
653 synthesizeCancelationEventsForAllConnectionsLocked(options);
654 }
655 break;
656 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700657 case EventEntry::Type::CONFIGURATION_CHANGED:
658 case EventEntry::Type::DEVICE_RESET: {
659 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
660 break;
661 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800662 }
663}
664
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800665static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700666 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
667 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668}
669
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700670bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
671 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
672 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
673 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674}
675
676bool InputDispatcher::isAppSwitchPendingLocked() {
677 return mAppSwitchDueTime != LONG_LONG_MAX;
678}
679
680void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
681 mAppSwitchDueTime = LONG_LONG_MAX;
682
683#if DEBUG_APP_SWITCH
684 if (handled) {
685 ALOGD("App switch has arrived.");
686 } else {
687 ALOGD("App switch was abandoned.");
688 }
689#endif
690}
691
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700692bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
693 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694}
695
696bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700697 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698}
699
700bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700701 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 return false;
703 }
704
705 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700706 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700707 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700709 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710
711 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700712 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713 return true;
714}
715
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700716void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
717 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718}
719
720void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700721 while (!mInboundQueue.empty()) {
722 EventEntry* entry = mInboundQueue.front();
723 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 releaseInboundEventLocked(entry);
725 }
726 traceInboundQueueLengthLocked();
727}
728
729void InputDispatcher::releasePendingEventLocked() {
730 if (mPendingEvent) {
731 resetANRTimeoutsLocked();
732 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700733 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734 }
735}
736
737void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
738 InjectionState* injectionState = entry->injectionState;
739 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
740#if DEBUG_DISPATCH_CYCLE
741 ALOGD("Injected inbound event was dropped.");
742#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800743 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 }
745 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700746 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 }
748 addRecentEventLocked(entry);
749 entry->release();
750}
751
752void InputDispatcher::resetKeyRepeatLocked() {
753 if (mKeyRepeatState.lastKeyEntry) {
754 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700755 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 }
757}
758
Garfield Tane84e6f92019-08-29 17:28:41 -0700759KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
761
762 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700763 uint32_t policyFlags = entry->policyFlags &
764 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800765 if (entry->refCount == 1) {
766 entry->recycle();
767 entry->eventTime = currentTime;
768 entry->policyFlags = policyFlags;
769 entry->repeatCount += 1;
770 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700771 KeyEntry* newEntry =
772 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId,
773 entry->source, entry->displayId, policyFlags, entry->action,
774 entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
775 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776
777 mKeyRepeatState.lastKeyEntry = newEntry;
778 entry->release();
779
780 entry = newEntry;
781 }
782 entry->syntheticRepeat = true;
783
784 // Increment reference count since we keep a reference to the event in
785 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
786 entry->refCount += 1;
787
788 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
789 return entry;
790}
791
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700792bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
793 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700795 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796#endif
797
798 // Reset key repeating in case a keyboard device was added or removed or something.
799 resetKeyRepeatLocked();
800
801 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700802 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
803 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700805 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 return true;
807}
808
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700811 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813#endif
814
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700815 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816 options.deviceId = entry->deviceId;
817 synthesizeCancelationEventsForAllConnectionsLocked(options);
818 return true;
819}
820
821bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 if (!entry->dispatchInProgress) {
825 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
826 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
827 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
828 if (mKeyRepeatState.lastKeyEntry &&
829 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830 // We have seen two identical key downs in a row which indicates that the device
831 // driver is automatically generating key repeats itself. We take note of the
832 // repeat here, but we disable our own next key repeat timer since it is clear that
833 // we will not need to synthesize key repeats ourselves.
834 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
835 resetKeyRepeatLocked();
836 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
837 } else {
838 // Not a repeat. Save key down state in case we do see a repeat later.
839 resetKeyRepeatLocked();
840 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
841 }
842 mKeyRepeatState.lastKeyEntry = entry;
843 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700844 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 resetKeyRepeatLocked();
846 }
847
848 if (entry->repeatCount == 1) {
849 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
850 } else {
851 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
852 }
853
854 entry->dispatchInProgress = true;
855
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700856 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 }
858
859 // Handle case where the policy asked us to try again later last time.
860 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
861 if (currentTime < entry->interceptKeyWakeupTime) {
862 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
863 *nextWakeupTime = entry->interceptKeyWakeupTime;
864 }
865 return false; // wait until next wakeup
866 }
867 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
868 entry->interceptKeyWakeupTime = 0;
869 }
870
871 // Give the policy a chance to intercept the key.
872 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
873 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700874 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -0700875 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800876 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700877 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +0800878 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 }
881 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700882 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 entry->refCount += 1;
884 return false; // wait for the command to run
885 } else {
886 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
887 }
888 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700889 if (*dropReason == DropReason::NOT_DROPPED) {
890 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 }
892 }
893
894 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700895 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700896 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700897 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700898 : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800899 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 return true;
901 }
902
903 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800904 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700906 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
908 return false;
909 }
910
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800911 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
913 return true;
914 }
915
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800916 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700917 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800918
919 // Dispatch the key.
920 dispatchEventLocked(currentTime, entry, inputTargets);
921 return true;
922}
923
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700924void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100926 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700927 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
928 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700929 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
930 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
931 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932#endif
933}
934
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700935bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
936 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000937 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700939 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 entry->dispatchInProgress = true;
941
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700942 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 }
944
945 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700946 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700947 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700948 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700949 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 return true;
951 }
952
953 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
954
955 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800956 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957
958 bool conflictingPointerActions = false;
959 int32_t injectionResult;
960 if (isPointerEvent) {
961 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700962 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700963 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 } else {
966 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700967 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700968 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 }
970 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
971 return false;
972 }
973
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800974 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100976 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 CancelationOptions::Mode mode(isPointerEvent
978 ? CancelationOptions::CANCEL_POINTER_EVENTS
979 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100980 CancelationOptions options(mode, "input event injection failed");
981 synthesizeCancelationEventsForMonitorsLocked(options);
982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 return true;
984 }
985
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800986 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700987 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800989 if (isPointerEvent) {
990 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
991 if (stateIndex >= 0) {
992 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800993 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800994 // The event has gone through these portal windows, so we add monitoring targets of
995 // the corresponding displays as well.
996 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800997 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +0000998 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700999 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001000 }
1001 }
1002 }
1003 }
1004
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 // Dispatch the motion.
1006 if (conflictingPointerActions) {
1007 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001008 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009 synthesizeCancelationEventsForAllConnectionsLocked(options);
1010 }
1011 dispatchEventLocked(currentTime, entry, inputTargets);
1012 return true;
1013}
1014
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001015void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001017 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001018 ", policyFlags=0x%x, "
1019 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1020 "metaState=0x%x, buttonState=0x%x,"
1021 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001022 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1023 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1024 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001026 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001028 "x=%f, y=%f, pressure=%f, size=%f, "
1029 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1030 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001031 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1032 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1033 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1034 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1035 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1036 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1037 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1038 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1039 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1040 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 }
1042#endif
1043}
1044
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001045void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1046 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001047 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048#if DEBUG_DISPATCH_CYCLE
1049 ALOGD("dispatchEventToCurrentInputTargets");
1050#endif
1051
1052 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1053
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001054 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001056 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001057 sp<Connection> connection =
1058 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001059 if (connection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1061 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001062 if (DEBUG_FOCUS) {
1063 ALOGD("Dropping event delivery to target with channel '%s' because it "
1064 "is no longer registered with the input dispatcher.",
1065 inputTarget.inputChannel->getName().c_str());
1066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 }
1068 }
1069}
1070
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001071int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001072 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001074 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001075 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001077 if (DEBUG_FOCUS) {
1078 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1081 mInputTargetWaitStartTime = currentTime;
1082 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1083 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001084 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 }
1086 } else {
1087 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001088 if (DEBUG_FOCUS) {
1089 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
1090 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1091 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001093 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001095 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 timeout =
1097 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098 } else {
1099 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1100 }
1101
1102 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1103 mInputTargetWaitStartTime = currentTime;
1104 mInputTargetWaitTimeoutTime = currentTime + timeout;
1105 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001106 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107
Yi Kong9b14ac62018-07-17 13:48:38 -07001108 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001109 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110 }
Robert Carr740167f2018-10-11 19:03:41 -07001111 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1112 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113 }
1114 }
1115 }
1116
1117 if (mInputTargetWaitTimeoutExpired) {
1118 return INPUT_EVENT_INJECTION_TIMED_OUT;
1119 }
1120
1121 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001122 onANRLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001123 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124
1125 // Force poll loop to wake up immediately on next iteration once we get the
1126 // ANR response back from the policy.
1127 *nextWakeupTime = LONG_LONG_MIN;
1128 return INPUT_EVENT_INJECTION_PENDING;
1129 } else {
1130 // Force poll loop to wake up when timeout is due.
1131 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1132 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1133 }
1134 return INPUT_EVENT_INJECTION_PENDING;
1135 }
1136}
1137
Robert Carr803535b2018-08-02 16:38:15 -07001138void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1139 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1140 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1141 state.removeWindowByToken(token);
1142 }
1143}
1144
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001145void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001146 nsecs_t newTimeout, const sp<IBinder>& inputConnectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 if (newTimeout > 0) {
1148 // Extend the timeout.
1149 mInputTargetWaitTimeoutTime = now() + newTimeout;
1150 } else {
1151 // Give up.
1152 mInputTargetWaitTimeoutExpired = true;
1153
1154 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001155 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001156 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001157 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001159 if (connection->status == Connection::STATUS_NORMAL) {
1160 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1161 "application not responding");
1162 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 }
1164 }
1165 }
1166}
1167
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1170 return currentTime - mInputTargetWaitStartTime;
1171 }
1172 return 0;
1173}
1174
1175void InputDispatcher::resetANRTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001176 if (DEBUG_FOCUS) {
1177 ALOGD("Resetting ANR timeouts.");
1178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179
1180 // Reset input target wait timeout.
1181 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001182 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183}
1184
Tiger Huang721e26f2018-07-24 22:26:19 +08001185/**
1186 * Get the display id that the given event should go to. If this event specifies a valid display id,
1187 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1188 * Focused display is the display that the user most recently interacted with.
1189 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001190int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001191 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001192 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001193 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001194 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1195 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001196 break;
1197 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001198 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001199 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1200 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001201 break;
1202 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001203 case EventEntry::Type::CONFIGURATION_CHANGED:
1204 case EventEntry::Type::DEVICE_RESET: {
1205 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001206 return ADISPLAY_ID_NONE;
1207 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001208 }
1209 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1210}
1211
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001213 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 std::vector<InputTarget>& inputTargets,
1215 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001217 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218
Tiger Huang721e26f2018-07-24 22:26:19 +08001219 int32_t displayId = getTargetDisplayId(entry);
1220 sp<InputWindowHandle> focusedWindowHandle =
1221 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1222 sp<InputApplicationHandle> focusedApplicationHandle =
1223 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1224
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 // If there is no currently focused window and no focused application
1226 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001227 if (focusedWindowHandle == nullptr) {
1228 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229 injectionResult =
1230 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1231 nullptr, nextWakeupTime,
1232 "Waiting because no window has focus but there is "
1233 "a focused application that may eventually add a "
1234 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 goto Unresponsive;
1236 }
1237
Arthur Hung3b413f22018-10-26 18:05:34 +08001238 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001239 "%" PRId32 ".",
1240 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1242 goto Failed;
1243 }
1244
1245 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001246 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1248 goto Failed;
1249 }
1250
Jeff Brownffb49772014-10-10 19:01:34 -07001251 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001252 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001253 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001254 injectionResult =
1255 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1256 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 goto Unresponsive;
1258 }
1259
1260 // Success! Output targets.
1261 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001262 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001263 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1264 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265
1266 // Done.
1267Failed:
1268Unresponsive:
1269 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001270 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001271 if (DEBUG_FOCUS) {
1272 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1273 "timeSpentWaitingForApplication=%0.1fms",
1274 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1275 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 return injectionResult;
1277}
1278
1279int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001280 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001281 std::vector<InputTarget>& inputTargets,
1282 nsecs_t* nextWakeupTime,
1283 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001284 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285 enum InjectionPermission {
1286 INJECTION_PERMISSION_UNKNOWN,
1287 INJECTION_PERMISSION_GRANTED,
1288 INJECTION_PERMISSION_DENIED
1289 };
1290
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291 // For security reasons, we defer updating the touch state until we are sure that
1292 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001293 int32_t displayId = entry.displayId;
1294 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1296
1297 // Update the touch state as needed based on the properties of the touch event.
1298 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1299 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1300 sp<InputWindowHandle> newHoverWindowHandle;
1301
Jeff Brownf086ddb2014-02-11 14:28:48 -08001302 // Copy current touch state into mTempTouchState.
1303 // This state is always reset at the end of this function, so if we don't find state
1304 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001305 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001306 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1307 if (oldStateIndex >= 0) {
1308 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1309 mTempTouchState.copyFrom(*oldState);
1310 }
1311
1312 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001313 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001314 (mTempTouchState.deviceId != entry.deviceId || mTempTouchState.source != entry.source ||
1315 mTempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001316 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1317 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1318 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1319 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1320 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001321 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 bool wrongDevice = false;
1323 if (newGesture) {
1324 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001325 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001326 if (DEBUG_FOCUS) {
1327 ALOGD("Dropping event because a pointer for a different device is already down "
1328 "in display %" PRId32,
1329 displayId);
1330 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001331 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1333 switchedDevice = false;
1334 wrongDevice = true;
1335 goto Failed;
1336 }
1337 mTempTouchState.reset();
1338 mTempTouchState.down = down;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001339 mTempTouchState.deviceId = entry.deviceId;
1340 mTempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 mTempTouchState.displayId = displayId;
1342 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001343 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001344 if (DEBUG_FOCUS) {
1345 ALOGI("Dropping move event because a pointer for a different device is already active "
1346 "in display %" PRId32,
1347 displayId);
1348 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001349 // TODO: test multiple simultaneous input streams.
1350 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1351 switchedDevice = false;
1352 wrongDevice = true;
1353 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 }
1355
1356 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1357 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1358
Garfield Tan00f511d2019-06-12 16:55:40 -07001359 int32_t x;
1360 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001362 // Always dispatch mouse events to cursor position.
1363 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001364 x = int32_t(entry.xCursorPosition);
1365 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001366 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001367 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1368 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001369 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001370 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001371 sp<InputWindowHandle> newTouchedWindowHandle =
1372 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1373 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001374
1375 std::vector<TouchedMonitor> newGestureMonitors = isDown
1376 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1377 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001380 if (newTouchedWindowHandle != nullptr &&
1381 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001382 // New window supports splitting, but we should never split mouse events.
1383 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 } else if (isSplit) {
1385 // New window does not support splitting but we have already split events.
1386 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001387 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 }
1389
1390 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001391 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392 // Try to assign the pointer to the first foreground window we find, if there is one.
1393 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001394 }
1395
1396 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1397 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001398 "(%d, %d) in display %" PRId32 ".",
1399 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001400 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1401 goto Failed;
1402 }
1403
1404 if (newTouchedWindowHandle != nullptr) {
1405 // Set target flags.
1406 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1407 if (isSplit) {
1408 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001409 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001410 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1411 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1412 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1413 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1414 }
1415
1416 // Update hover state.
1417 if (isHoverAction) {
1418 newHoverWindowHandle = newTouchedWindowHandle;
1419 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1420 newHoverWindowHandle = mLastHoverWindowHandle;
1421 }
1422
1423 // Update the temporary touch state.
1424 BitSet32 pointerIds;
1425 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001426 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001427 pointerIds.markBit(pointerId);
1428 }
1429 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430 }
1431
Michael Wright3dd60e22019-03-27 22:06:44 +00001432 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433 } else {
1434 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1435
1436 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001437 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001438 if (DEBUG_FOCUS) {
1439 ALOGD("Dropping event because the pointer is not down or we previously "
1440 "dropped the pointer down event in display %" PRId32,
1441 displayId);
1442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1444 goto Failed;
1445 }
1446
1447 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001448 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001449 mTempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001450 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1451 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452
1453 sp<InputWindowHandle> oldTouchedWindowHandle =
1454 mTempTouchState.getFirstForegroundWindowHandle();
1455 sp<InputWindowHandle> newTouchedWindowHandle =
1456 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001457 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1458 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001459 if (DEBUG_FOCUS) {
1460 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1461 oldTouchedWindowHandle->getName().c_str(),
1462 newTouchedWindowHandle->getName().c_str(), displayId);
1463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 // Make a slippery exit from the old window.
1465 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001466 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1467 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468
1469 // Make a slippery entrance into the new window.
1470 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1471 isSplit = true;
1472 }
1473
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001474 int32_t targetFlags =
1475 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 if (isSplit) {
1477 targetFlags |= InputTarget::FLAG_SPLIT;
1478 }
1479 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1480 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1481 }
1482
1483 BitSet32 pointerIds;
1484 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001485 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 }
1487 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1488 }
1489 }
1490 }
1491
1492 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1493 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001494 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495#if DEBUG_HOVER
1496 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001497 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498#endif
1499 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001500 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1501 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 }
1503
1504 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001505 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506#if DEBUG_HOVER
1507 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001508 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509#endif
1510 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001511 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1512 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 }
1514 }
1515
1516 // Check permission to inject into all touched foreground windows and ensure there
1517 // is at least one touched foreground window.
1518 {
1519 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001520 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001521 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1522 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001523 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1525 injectionPermission = INJECTION_PERMISSION_DENIED;
1526 goto Failed;
1527 }
1528 }
1529 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001530 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1531 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001532 if (DEBUG_FOCUS) {
1533 ALOGD("Dropping event because there is no touched foreground window in display "
1534 "%" PRId32 " or gesture monitor to receive it.",
1535 displayId);
1536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1538 goto Failed;
1539 }
1540
1541 // Permission granted to injection into all touched foreground windows.
1542 injectionPermission = INJECTION_PERMISSION_GRANTED;
1543 }
1544
1545 // Check whether windows listening for outside touches are owned by the same UID. If it is
1546 // set the policy flag that we will not reveal coordinate information to this window.
1547 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1548 sp<InputWindowHandle> foregroundWindowHandle =
1549 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001550 if (foregroundWindowHandle) {
1551 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1552 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1553 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1554 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1555 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1556 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001557 InputTarget::FLAG_ZERO_COORDS,
1558 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 }
1561 }
1562 }
1563 }
1564
1565 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001566 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001568 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001569 std::string reason =
1570 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1571 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001572 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001573 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1574 touchedWindow.windowHandle,
1575 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 goto Unresponsive;
1577 }
1578 }
1579 }
1580
1581 // If this is the first pointer going down and the touched window has a wallpaper
1582 // then also add the touched wallpaper windows so they are locked in for the duration
1583 // of the touch gesture.
1584 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1585 // engine only supports touch events. We would need to add a mechanism similar
1586 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1587 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1588 sp<InputWindowHandle> foregroundWindowHandle =
1589 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001590 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001591 const std::vector<sp<InputWindowHandle>> windowHandles =
1592 getWindowHandlesLocked(displayId);
1593 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001595 if (info->displayId == displayId &&
1596 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1597 mTempTouchState
1598 .addOrUpdateWindow(windowHandle,
1599 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1600 InputTarget::
1601 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1602 InputTarget::FLAG_DISPATCH_AS_IS,
1603 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 }
1605 }
1606 }
1607 }
1608
1609 // Success! Output targets.
1610 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1611
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001612 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001614 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 }
1616
Michael Wright3dd60e22019-03-27 22:06:44 +00001617 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1618 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001619 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001620 }
1621
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622 // Drop the outside or hover touch windows since we will not care about them
1623 // in the next iteration.
1624 mTempTouchState.filterNonAsIsTouchWindows();
1625
1626Failed:
1627 // Check injection permission once and for all.
1628 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001629 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 injectionPermission = INJECTION_PERMISSION_GRANTED;
1631 } else {
1632 injectionPermission = INJECTION_PERMISSION_DENIED;
1633 }
1634 }
1635
1636 // Update final pieces of touch state if the injector had permission.
1637 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1638 if (!wrongDevice) {
1639 if (switchedDevice) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001640 if (DEBUG_FOCUS) {
1641 ALOGD("Conflicting pointer actions: Switched to a different device.");
1642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 *outConflictingPointerActions = true;
1644 }
1645
1646 if (isHoverAction) {
1647 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001648 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001649 if (DEBUG_FOCUS) {
1650 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1651 "down.");
1652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 *outConflictingPointerActions = true;
1654 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001655 mTempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001656 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1657 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001658 mTempTouchState.deviceId = entry.deviceId;
1659 mTempTouchState.source = entry.source;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001660 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001662 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1663 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001665 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1667 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001668 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001669 if (DEBUG_FOCUS) {
1670 ALOGD("Conflicting pointer actions: Down received while already down.");
1671 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 *outConflictingPointerActions = true;
1673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1675 // One pointer went up.
1676 if (isSplit) {
1677 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001678 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001680 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001681 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1683 touchedWindow.pointerIds.clearBit(pointerId);
1684 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001685 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 continue;
1687 }
1688 }
1689 i += 1;
1690 }
1691 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001692 }
1693
1694 // Save changes unless the action was scroll in which case the temporary touch
1695 // state was only valid for this one action.
1696 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1697 if (mTempTouchState.displayId >= 0) {
1698 if (oldStateIndex >= 0) {
1699 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1700 } else {
1701 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1702 }
1703 } else if (oldStateIndex >= 0) {
1704 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706 }
1707
1708 // Update hover state.
1709 mLastHoverWindowHandle = newHoverWindowHandle;
1710 }
1711 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001712 if (DEBUG_FOCUS) {
1713 ALOGD("Not updating touch focus because injection was denied.");
1714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715 }
1716
1717Unresponsive:
1718 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1719 mTempTouchState.reset();
1720
1721 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001722 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001723 if (DEBUG_FOCUS) {
1724 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1725 "timeSpentWaitingForApplication=%0.1fms",
1726 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 return injectionResult;
1729}
1730
1731void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001732 int32_t targetFlags, BitSet32 pointerIds,
1733 std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001734 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1735 if (inputChannel == nullptr) {
1736 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1737 return;
1738 }
1739
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001741 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001742 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 target.flags = targetFlags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001744 target.xOffset = -windowInfo->frameLeft;
1745 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001746 target.globalScaleFactor = windowInfo->globalScaleFactor;
1747 target.windowXScale = windowInfo->windowXScale;
1748 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001750 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751}
1752
Michael Wright3dd60e22019-03-27 22:06:44 +00001753void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001754 int32_t displayId, float xOffset,
1755 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001756 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1757 mGlobalMonitorsByDisplay.find(displayId);
1758
1759 if (it != mGlobalMonitorsByDisplay.end()) {
1760 const std::vector<Monitor>& monitors = it->second;
1761 for (const Monitor& monitor : monitors) {
1762 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764 }
1765}
1766
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001767void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1768 float yOffset,
1769 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001770 InputTarget target;
1771 target.inputChannel = monitor.inputChannel;
1772 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1773 target.xOffset = xOffset;
1774 target.yOffset = yOffset;
1775 target.pointerIds.clear();
1776 target.globalScaleFactor = 1.0f;
1777 inputTargets.push_back(target);
1778}
1779
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001781 const InjectionState* injectionState) {
1782 if (injectionState &&
1783 (windowHandle == nullptr ||
1784 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1785 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001786 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001788 "owned by uid %d",
1789 injectionState->injectorPid, injectionState->injectorUid,
1790 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 } else {
1792 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001793 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
1795 return false;
1796 }
1797 return true;
1798}
1799
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001800bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1801 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001803 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1804 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805 if (otherHandle == windowHandle) {
1806 break;
1807 }
1808
1809 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001810 if (otherInfo->displayId == displayId && otherInfo->visible &&
1811 !otherInfo->isTrustedOverlay() && otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 return true;
1813 }
1814 }
1815 return false;
1816}
1817
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001818bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1819 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001820 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001821 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001822 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001823 if (otherHandle == windowHandle) {
1824 break;
1825 }
1826
1827 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001828 if (otherInfo->displayId == displayId && otherInfo->visible &&
1829 !otherInfo->isTrustedOverlay() && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001830 return true;
1831 }
1832 }
1833 return false;
1834}
1835
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001836std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
1837 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001838 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07001839 // If the window is paused then keep waiting.
1840 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001841 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001842 }
1843
1844 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001845 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001846 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001847 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001848 "registered with the input dispatcher. The window may be in the "
1849 "process of being removed.",
1850 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001851 }
1852
1853 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07001854 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001855 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001856 "The window may be in the process of being removed.",
1857 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07001858 }
1859
1860 // If the connection is backed up then keep waiting.
1861 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001862 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001863 "Outbound queue length: %zu. Wait queue length: %zu.",
1864 targetType, connection->outboundQueue.size(),
1865 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07001866 }
1867
1868 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001869 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07001870 // If the event is a key event, then we must wait for all previous events to
1871 // complete before delivering it because previous events may have the
1872 // side-effect of transferring focus to a different window and we want to
1873 // ensure that the following keys are sent to the new window.
1874 //
1875 // Suppose the user touches a button in a window then immediately presses "A".
1876 // If the button causes a pop-up window to appear then we want to ensure that
1877 // the "A" key is delivered to the new pop-up window. This is because users
1878 // often anticipate pending UI changes when typing on a keyboard.
1879 // To obtain this behavior, we must serialize key events with respect to all
1880 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001881 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001882 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001883 "finished processing all of the input events that were previously "
1884 "delivered to it. Outbound queue length: %zu. Wait queue length: "
1885 "%zu.",
1886 targetType, connection->outboundQueue.size(),
1887 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 }
Jeff Brownffb49772014-10-10 19:01:34 -07001889 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 // Touch events can always be sent to a window immediately because the user intended
1891 // to touch whatever was visible at the time. Even if focus changes or a new
1892 // window appears moments later, the touch event was meant to be delivered to
1893 // whatever window happened to be on screen at the time.
1894 //
1895 // Generic motion events, such as trackball or joystick events are a little trickier.
1896 // Like key events, generic motion events are delivered to the focused window.
1897 // Unlike key events, generic motion events don't tend to transfer focus to other
1898 // windows and it is not important for them to be serialized. So we prefer to deliver
1899 // generic motion events as soon as possible to improve efficiency and reduce lag
1900 // through batching.
1901 //
1902 // The one case where we pause input event delivery is when the wait queue is piling
1903 // up with lots of events because the application is not responding.
1904 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001905 if (!connection->waitQueue.empty() &&
1906 currentTime >=
1907 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001908 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001909 "finished processing certain input events that were delivered to "
1910 "it over "
1911 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
1912 "%0.1fms.",
1913 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1914 connection->waitQueue.size(),
1915 (currentTime - connection->waitQueue.front()->deliveryTime) *
1916 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 }
1918 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001919 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920}
1921
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001922std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 const sp<InputApplicationHandle>& applicationHandle,
1924 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001925 if (applicationHandle != nullptr) {
1926 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001927 std::string label(applicationHandle->getName());
1928 label += " - ";
1929 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 return label;
1931 } else {
1932 return applicationHandle->getName();
1933 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001934 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 return windowHandle->getName();
1936 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001937 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938 }
1939}
1940
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001941void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001942 int32_t displayId = getTargetDisplayId(eventEntry);
1943 sp<InputWindowHandle> focusedWindowHandle =
1944 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1945 if (focusedWindowHandle != nullptr) {
1946 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1948#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001949 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950#endif
1951 return;
1952 }
1953 }
1954
1955 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001956 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001957 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001958 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
1959 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001960 return;
1961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001963 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001964 eventType = USER_ACTIVITY_EVENT_TOUCH;
1965 }
1966 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001968 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001969 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
1970 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001971 return;
1972 }
1973 eventType = USER_ACTIVITY_EVENT_BUTTON;
1974 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001976 case EventEntry::Type::CONFIGURATION_CHANGED:
1977 case EventEntry::Type::DEVICE_RESET: {
1978 LOG_ALWAYS_FATAL("%s events are not user activity",
1979 EventEntry::typeToString(eventEntry.type));
1980 break;
1981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 }
1983
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001984 std::unique_ptr<CommandEntry> commandEntry =
1985 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001986 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001988 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989}
1990
1991void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001992 const sp<Connection>& connection,
1993 EventEntry* eventEntry,
1994 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001995 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001996 std::string message =
1997 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
1998 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00001999 ATRACE_NAME(message.c_str());
2000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001#if DEBUG_DISPATCH_CYCLE
2002 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002003 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
2004 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
2005 connection->getInputChannelName().c_str(), inputTarget->flags, inputTarget->xOffset,
2006 inputTarget->yOffset, inputTarget->globalScaleFactor, inputTarget->windowXScale,
2007 inputTarget->windowYScale, inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008#endif
2009
2010 // Skip this event if the connection status is not normal.
2011 // We don't want to enqueue additional outbound events if the connection is broken.
2012 if (connection->status != Connection::STATUS_NORMAL) {
2013#if DEBUG_DISPATCH_CYCLE
2014 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002015 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016#endif
2017 return;
2018 }
2019
2020 // Split a motion event if needed.
2021 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002022 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002024 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
2025 if (inputTarget->pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002026 MotionEntry* splitMotionEntry =
2027 splitMotionEvent(originalMotionEntry, inputTarget->pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 if (!splitMotionEntry) {
2029 return; // split event was dropped
2030 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002031 if (DEBUG_FOCUS) {
2032 ALOGD("channel '%s' ~ Split motion event.",
2033 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002034 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002035 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002036 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 splitMotionEntry->release();
2038 return;
2039 }
2040 }
2041
2042 // Not splitting. Enqueue dispatch entries for the event as is.
2043 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2044}
2045
2046void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002047 const sp<Connection>& connection,
2048 EventEntry* eventEntry,
2049 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002050 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002051 std::string message =
2052 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32
2053 ")",
2054 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002055 ATRACE_NAME(message.c_str());
2056 }
2057
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002058 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059
2060 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002061 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002062 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002063 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002064 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002065 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002066 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002067 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002068 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002069 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002070 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002071 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002072 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073
2074 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002075 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 startDispatchCycleLocked(currentTime, connection);
2077 }
2078}
2079
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002080void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2081 EventEntry* eventEntry,
2082 const InputTarget* inputTarget,
2083 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002084 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002085 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2086 connection->getInputChannelName().c_str(),
2087 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002088 ATRACE_NAME(message.c_str());
2089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 int32_t inputTargetFlags = inputTarget->flags;
2091 if (!(inputTargetFlags & dispatchMode)) {
2092 return;
2093 }
2094 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2095
2096 // This is a new event.
2097 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002098 DispatchEntry* dispatchEntry =
2099 new DispatchEntry(eventEntry, // increments ref
2100 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
2101 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2102 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103
2104 // Apply target flags and update the connection's input state.
2105 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002106 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002107 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
2108 dispatchEntry->resolvedAction = keyEntry.action;
2109 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002111 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2112 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002114 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2115 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002117 delete dispatchEntry;
2118 return; // skip the inconsistent event
2119 }
2120 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002123 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002124 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002125 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2126 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2127 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2128 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2129 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2130 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2131 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2132 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2133 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2134 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2135 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002136 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002137 }
2138 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002139 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2140 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002142 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2143 "event",
2144 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002146 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002149 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002150 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2151 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2152 }
2153 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2154 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2155 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002157 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2158 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002160 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2161 "event",
2162 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002164 delete dispatchEntry;
2165 return; // skip the inconsistent event
2166 }
2167
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002168 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002169 inputTarget->inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002170
2171 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002173 case EventEntry::Type::CONFIGURATION_CHANGED:
2174 case EventEntry::Type::DEVICE_RESET: {
2175 LOG_ALWAYS_FATAL("%s events should not go to apps",
2176 EventEntry::typeToString(eventEntry->type));
2177 break;
2178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002179 }
2180
2181 // Remember that we are waiting for this dispatch to complete.
2182 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002183 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184 }
2185
2186 // Enqueue the dispatch entry.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002187 connection->outboundQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002188 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002189}
2190
chaviwfd6d3512019-03-25 13:23:49 -07002191void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002192 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002193 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002194 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2195 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002196 return;
2197 }
2198
2199 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2200 if (inputWindowHandle == nullptr) {
2201 return;
2202 }
2203
chaviw8c9cf542019-03-25 13:02:48 -07002204 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002205 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002206
2207 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2208
2209 if (!hasFocusChanged) {
2210 return;
2211 }
2212
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002213 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2214 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002215 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002216 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217}
2218
2219void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002220 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002221 if (ATRACE_ENABLED()) {
2222 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002223 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002224 ATRACE_NAME(message.c_str());
2225 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002227 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228#endif
2229
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002230 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2231 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 dispatchEntry->deliveryTime = currentTime;
2233
2234 // Publish the event.
2235 status_t status;
2236 EventEntry* eventEntry = dispatchEntry->eventEntry;
2237 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002238 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002239 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002241 // Publish the key event.
2242 status = connection->inputPublisher
2243 .publishKeyEvent(dispatchEntry->seq, keyEntry->deviceId,
2244 keyEntry->source, keyEntry->displayId,
2245 dispatchEntry->resolvedAction,
2246 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2247 keyEntry->scanCode, keyEntry->metaState,
2248 keyEntry->repeatCount, keyEntry->downTime,
2249 keyEntry->eventTime);
2250 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 }
2252
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002253 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002256 PointerCoords scaledCoords[MAX_POINTERS];
2257 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2258
2259 // Set the X and Y offset depending on the input source.
2260 float xOffset, yOffset;
2261 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2262 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2263 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2264 float wxs = dispatchEntry->windowXScale;
2265 float wys = dispatchEntry->windowYScale;
2266 xOffset = dispatchEntry->xOffset * wxs;
2267 yOffset = dispatchEntry->yOffset * wys;
2268 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
2269 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2270 scaledCoords[i] = motionEntry->pointerCoords[i];
2271 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
2272 }
2273 usingCoords = scaledCoords;
2274 }
2275 } else {
2276 xOffset = 0.0f;
2277 yOffset = 0.0f;
2278
2279 // We don't want the dispatch target to know.
2280 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2281 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2282 scaledCoords[i].clear();
2283 }
2284 usingCoords = scaledCoords;
2285 }
2286 }
2287
2288 // Publish the motion event.
2289 status = connection->inputPublisher
2290 .publishMotionEvent(dispatchEntry->seq, motionEntry->deviceId,
2291 motionEntry->source, motionEntry->displayId,
2292 dispatchEntry->resolvedAction,
2293 motionEntry->actionButton,
2294 dispatchEntry->resolvedFlags,
2295 motionEntry->edgeFlags, motionEntry->metaState,
2296 motionEntry->buttonState,
2297 motionEntry->classification, xOffset, yOffset,
2298 motionEntry->xPrecision,
2299 motionEntry->yPrecision,
2300 motionEntry->xCursorPosition,
2301 motionEntry->yCursorPosition,
2302 motionEntry->downTime, motionEntry->eventTime,
2303 motionEntry->pointerCount,
2304 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002305 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002306 break;
2307 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002308 case EventEntry::Type::CONFIGURATION_CHANGED:
2309 case EventEntry::Type::DEVICE_RESET: {
2310 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2311 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002312 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
2315
2316 // Check the result.
2317 if (status) {
2318 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002319 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002321 "This is unexpected because the wait queue is empty, so the pipe "
2322 "should be empty and we shouldn't have any problems writing an "
2323 "event to it, status=%d",
2324 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2326 } else {
2327 // Pipe is full and we are waiting for the app to finish process some events
2328 // before sending more events to it.
2329#if DEBUG_DISPATCH_CYCLE
2330 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002331 "waiting for the application to catch up",
2332 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333#endif
2334 connection->inputPublisherBlocked = true;
2335 }
2336 } else {
2337 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002338 "status=%d",
2339 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2341 }
2342 return;
2343 }
2344
2345 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002346 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2347 connection->outboundQueue.end(),
2348 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002349 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002350 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002351 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 }
2353}
2354
2355void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002356 const sp<Connection>& connection, uint32_t seq,
2357 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358#if DEBUG_DISPATCH_CYCLE
2359 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002360 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361#endif
2362
2363 connection->inputPublisherBlocked = false;
2364
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002365 if (connection->status == Connection::STATUS_BROKEN ||
2366 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367 return;
2368 }
2369
2370 // Notify other system components and prepare to start the next dispatch cycle.
2371 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2372}
2373
2374void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002375 const sp<Connection>& connection,
2376 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377#if DEBUG_DISPATCH_CYCLE
2378 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002379 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380#endif
2381
2382 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002383 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002384 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002385 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002386 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387
2388 // The connection appears to be unrecoverably broken.
2389 // Ignore already broken or zombie connections.
2390 if (connection->status == Connection::STATUS_NORMAL) {
2391 connection->status = Connection::STATUS_BROKEN;
2392
2393 if (notify) {
2394 // Notify other system components.
2395 onDispatchCycleBrokenLocked(currentTime, connection);
2396 }
2397 }
2398}
2399
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002400void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2401 while (!queue.empty()) {
2402 DispatchEntry* dispatchEntry = queue.front();
2403 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002404 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405 }
2406}
2407
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002408void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002410 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002411 }
2412 delete dispatchEntry;
2413}
2414
2415int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2416 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2417
2418 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002419 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002421 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002423 "fd=%d, events=0x%x",
2424 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 return 0; // remove the callback
2426 }
2427
2428 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002429 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2431 if (!(events & ALOOPER_EVENT_INPUT)) {
2432 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002433 "events=0x%x",
2434 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435 return 1;
2436 }
2437
2438 nsecs_t currentTime = now();
2439 bool gotOne = false;
2440 status_t status;
2441 for (;;) {
2442 uint32_t seq;
2443 bool handled;
2444 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2445 if (status) {
2446 break;
2447 }
2448 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2449 gotOne = true;
2450 }
2451 if (gotOne) {
2452 d->runCommandsLockedInterruptible();
2453 if (status == WOULD_BLOCK) {
2454 return 1;
2455 }
2456 }
2457
2458 notify = status != DEAD_OBJECT || !connection->monitor;
2459 if (notify) {
2460 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002461 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 }
2463 } else {
2464 // Monitor channels are never explicitly unregistered.
2465 // We do it automatically when the remote endpoint is closed so don't warn
2466 // about them.
2467 notify = !connection->monitor;
2468 if (notify) {
2469 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002470 "events=0x%x",
2471 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 }
2473 }
2474
2475 // Unregister the channel.
2476 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2477 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002478 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479}
2480
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002481void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002483 for (const auto& pair : mConnectionsByFd) {
2484 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485 }
2486}
2487
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002488void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002489 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002490 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2491 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2492}
2493
2494void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2495 const CancelationOptions& options,
2496 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2497 for (const auto& it : monitorsByDisplay) {
2498 const std::vector<Monitor>& monitors = it.second;
2499 for (const Monitor& monitor : monitors) {
2500 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002501 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002502 }
2503}
2504
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2506 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002507 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002508 if (connection == nullptr) {
2509 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002511
2512 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513}
2514
2515void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2516 const sp<Connection>& connection, const CancelationOptions& options) {
2517 if (connection->status == Connection::STATUS_BROKEN) {
2518 return;
2519 }
2520
2521 nsecs_t currentTime = now();
2522
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002523 std::vector<EventEntry*> cancelationEvents =
2524 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002526 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002528 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002529 "with reality: %s, mode=%d.",
2530 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2531 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532#endif
2533 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002534 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 switch (cancelationEventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002536 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002537 logOutboundKeyDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002538 static_cast<const KeyEntry&>(*cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002539 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002540 }
2541 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002542 logOutboundMotionDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002543 static_cast<const MotionEntry&>(
2544 *cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002545 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002546 }
2547 case EventEntry::Type::CONFIGURATION_CHANGED:
2548 case EventEntry::Type::DEVICE_RESET: {
2549 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2550 EventEntry::typeToString(cancelationEventEntry->type));
2551 break;
2552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 }
2554
2555 InputTarget target;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002556 sp<InputWindowHandle> windowHandle =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002557 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002558 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2560 target.xOffset = -windowInfo->frameLeft;
2561 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002562 target.globalScaleFactor = windowInfo->globalScaleFactor;
2563 target.windowXScale = windowInfo->windowXScale;
2564 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 } else {
2566 target.xOffset = 0;
2567 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002568 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 }
2570 target.inputChannel = connection->inputChannel;
2571 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2572
chaviw8c9cf542019-03-25 13:02:48 -07002573 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002574 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575
2576 cancelationEventEntry->release();
2577 }
2578
2579 startDispatchCycleLocked(currentTime, connection);
2580 }
2581}
2582
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002583MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002584 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 ALOG_ASSERT(pointerIds.value != 0);
2586
2587 uint32_t splitPointerIndexMap[MAX_POINTERS];
2588 PointerProperties splitPointerProperties[MAX_POINTERS];
2589 PointerCoords splitPointerCoords[MAX_POINTERS];
2590
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002591 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002592 uint32_t splitPointerCount = 0;
2593
2594 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002595 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002597 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 uint32_t pointerId = uint32_t(pointerProperties.id);
2599 if (pointerIds.hasBit(pointerId)) {
2600 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2601 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2602 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002603 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604 splitPointerCount += 1;
2605 }
2606 }
2607
2608 if (splitPointerCount != pointerIds.count()) {
2609 // This is bad. We are missing some of the pointers that we expected to deliver.
2610 // Most likely this indicates that we received an ACTION_MOVE events that has
2611 // different pointer ids than we expected based on the previous ACTION_DOWN
2612 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2613 // in this way.
2614 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002615 "we expected there to be %d pointers. This probably means we received "
2616 "a broken sequence of pointer ids from the input device.",
2617 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002618 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 }
2620
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002621 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002623 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2624 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2626 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002627 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628 uint32_t pointerId = uint32_t(pointerProperties.id);
2629 if (pointerIds.hasBit(pointerId)) {
2630 if (pointerIds.count() == 1) {
2631 // The first/last pointer went down/up.
2632 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002633 ? AMOTION_EVENT_ACTION_DOWN
2634 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002635 } else {
2636 // A secondary pointer went down/up.
2637 uint32_t splitPointerIndex = 0;
2638 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2639 splitPointerIndex += 1;
2640 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002641 action = maskedAction |
2642 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 }
2644 } else {
2645 // An unrelated pointer changed.
2646 action = AMOTION_EVENT_ACTION_MOVE;
2647 }
2648 }
2649
Garfield Tan00f511d2019-06-12 16:55:40 -07002650 MotionEntry* splitMotionEntry =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002651 new MotionEntry(originalMotionEntry.sequenceNum, originalMotionEntry.eventTime,
2652 originalMotionEntry.deviceId, originalMotionEntry.source,
2653 originalMotionEntry.displayId, originalMotionEntry.policyFlags, action,
2654 originalMotionEntry.actionButton, originalMotionEntry.flags,
2655 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2656 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2657 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2658 originalMotionEntry.xCursorPosition,
2659 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002660 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002662 if (originalMotionEntry.injectionState) {
2663 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664 splitMotionEntry->injectionState->refCount += 1;
2665 }
2666
2667 return splitMotionEntry;
2668}
2669
2670void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2671#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002672 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673#endif
2674
2675 bool needWake;
2676 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002677 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678
Prabir Pradhan42611e02018-11-27 14:04:02 -08002679 ConfigurationChangedEntry* newEntry =
2680 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681 needWake = enqueueInboundEventLocked(newEntry);
2682 } // release lock
2683
2684 if (needWake) {
2685 mLooper->wake();
2686 }
2687}
2688
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002689/**
2690 * If one of the meta shortcuts is detected, process them here:
2691 * Meta + Backspace -> generate BACK
2692 * Meta + Enter -> generate HOME
2693 * This will potentially overwrite keyCode and metaState.
2694 */
2695void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002696 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002697 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2698 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2699 if (keyCode == AKEYCODE_DEL) {
2700 newKeyCode = AKEYCODE_BACK;
2701 } else if (keyCode == AKEYCODE_ENTER) {
2702 newKeyCode = AKEYCODE_HOME;
2703 }
2704 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002705 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002706 struct KeyReplacement replacement = {keyCode, deviceId};
2707 mReplacedKeys.add(replacement, newKeyCode);
2708 keyCode = newKeyCode;
2709 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2710 }
2711 } else if (action == AKEY_EVENT_ACTION_UP) {
2712 // In order to maintain a consistent stream of up and down events, check to see if the key
2713 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2714 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002715 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002716 struct KeyReplacement replacement = {keyCode, deviceId};
2717 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2718 if (index >= 0) {
2719 keyCode = mReplacedKeys.valueAt(index);
2720 mReplacedKeys.removeItemsAt(index);
2721 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2722 }
2723 }
2724}
2725
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2727#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002728 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2729 "policyFlags=0x%x, action=0x%x, "
2730 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2731 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2732 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2733 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734#endif
2735 if (!validateKeyEvent(args->action)) {
2736 return;
2737 }
2738
2739 uint32_t policyFlags = args->policyFlags;
2740 int32_t flags = args->flags;
2741 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002742 // InputDispatcher tracks and generates key repeats on behalf of
2743 // whatever notifies it, so repeatCount should always be set to 0
2744 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2746 policyFlags |= POLICY_FLAG_VIRTUAL;
2747 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2748 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749 if (policyFlags & POLICY_FLAG_FUNCTION) {
2750 metaState |= AMETA_FUNCTION_ON;
2751 }
2752
2753 policyFlags |= POLICY_FLAG_TRUSTED;
2754
Michael Wright78f24442014-08-06 15:55:28 -07002755 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002756 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002757
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 KeyEvent event;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002759 event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2760 args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761
Michael Wright2b3c3302018-03-02 17:19:13 +00002762 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002764 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2765 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002766 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 bool needWake;
2770 { // acquire lock
2771 mLock.lock();
2772
2773 if (shouldSendKeyToInputFilterLocked(args)) {
2774 mLock.unlock();
2775
2776 policyFlags |= POLICY_FLAG_FILTERED;
2777 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2778 return; // event was consumed by the filter
2779 }
2780
2781 mLock.lock();
2782 }
2783
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002784 KeyEntry* newEntry =
2785 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2786 args->displayId, policyFlags, args->action, flags, keyCode,
2787 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788
2789 needWake = enqueueInboundEventLocked(newEntry);
2790 mLock.unlock();
2791 } // release lock
2792
2793 if (needWake) {
2794 mLooper->wake();
2795 }
2796}
2797
2798bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2799 return mInputFilterEnabled;
2800}
2801
2802void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2803#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002804 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan00f511d2019-06-12 16:55:40 -07002805 ", policyFlags=0x%x, "
2806 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
2807 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07002808 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan00f511d2019-06-12 16:55:40 -07002809 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2810 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Jaewan Kim372fbe42019-10-02 10:58:46 +09002811 args->edgeFlags, args->xPrecision, args->yPrecision, args->xCursorPosition,
Garfield Tan00f511d2019-06-12 16:55:40 -07002812 args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813 for (uint32_t i = 0; i < args->pointerCount; i++) {
2814 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002815 "x=%f, y=%f, pressure=%f, size=%f, "
2816 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2817 "orientation=%f",
2818 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2819 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2820 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2821 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2822 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2823 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2824 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2825 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2826 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2827 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 }
2829#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002830 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2831 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832 return;
2833 }
2834
2835 uint32_t policyFlags = args->policyFlags;
2836 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002837
2838 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002839 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002840 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2841 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002842 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002843 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844
2845 bool needWake;
2846 { // acquire lock
2847 mLock.lock();
2848
2849 if (shouldSendMotionToInputFilterLocked(args)) {
2850 mLock.unlock();
2851
2852 MotionEvent event;
Garfield Tan00f511d2019-06-12 16:55:40 -07002853 event.initialize(args->deviceId, args->source, args->displayId, args->action,
2854 args->actionButton, args->flags, args->edgeFlags, args->metaState,
2855 args->buttonState, args->classification, 0, 0, args->xPrecision,
2856 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2857 args->downTime, args->eventTime, args->pointerCount,
2858 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859
2860 policyFlags |= POLICY_FLAG_FILTERED;
2861 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2862 return; // event was consumed by the filter
2863 }
2864
2865 mLock.lock();
2866 }
2867
2868 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07002869 MotionEntry* newEntry =
2870 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2871 args->displayId, policyFlags, args->action, args->actionButton,
2872 args->flags, args->metaState, args->buttonState,
2873 args->classification, args->edgeFlags, args->xPrecision,
2874 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2875 args->downTime, args->pointerCount, args->pointerProperties,
2876 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877
2878 needWake = enqueueInboundEventLocked(newEntry);
2879 mLock.unlock();
2880 } // release lock
2881
2882 if (needWake) {
2883 mLooper->wake();
2884 }
2885}
2886
2887bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002888 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889}
2890
2891void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2892#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002893 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002894 "switchMask=0x%08x",
2895 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002896#endif
2897
2898 uint32_t policyFlags = args->policyFlags;
2899 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002900 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901}
2902
2903void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2904#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002905 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
2906 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907#endif
2908
2909 bool needWake;
2910 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002911 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912
Prabir Pradhan42611e02018-11-27 14:04:02 -08002913 DeviceResetEntry* newEntry =
2914 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915 needWake = enqueueInboundEventLocked(newEntry);
2916 } // release lock
2917
2918 if (needWake) {
2919 mLooper->wake();
2920 }
2921}
2922
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002923int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
2924 int32_t injectorUid, int32_t syncMode,
2925 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926#if DEBUG_INBOUND_EVENT_DETAILS
2927 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002928 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2929 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930#endif
2931
2932 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2933
2934 policyFlags |= POLICY_FLAG_INJECTED;
2935 if (hasInjectionPermission(injectorPid, injectorUid)) {
2936 policyFlags |= POLICY_FLAG_TRUSTED;
2937 }
2938
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07002939 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002941 case AINPUT_EVENT_TYPE_KEY: {
2942 KeyEvent keyEvent;
2943 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2944 int32_t action = keyEvent.getAction();
2945 if (!validateKeyEvent(action)) {
2946 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002949 int32_t flags = keyEvent.getFlags();
2950 int32_t keyCode = keyEvent.getKeyCode();
2951 int32_t metaState = keyEvent.getMetaState();
2952 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2953 /*byref*/ keyCode, /*byref*/ metaState);
2954 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
2955 keyEvent.getDisplayId(), action, flags, keyCode,
2956 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
2957 keyEvent.getDownTime(), keyEvent.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2960 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00002961 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002962
2963 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2964 android::base::Timer t;
2965 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
2966 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2967 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2968 std::to_string(t.duration().count()).c_str());
2969 }
2970 }
2971
2972 mLock.lock();
2973 KeyEntry* injectedEntry =
2974 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
2975 keyEvent.getDeviceId(), keyEvent.getSource(),
2976 keyEvent.getDisplayId(), policyFlags, action, flags,
2977 keyEvent.getKeyCode(), keyEvent.getScanCode(),
2978 keyEvent.getMetaState(), keyEvent.getRepeatCount(),
2979 keyEvent.getDownTime());
2980 injectedEntries.push(injectedEntry);
2981 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002982 }
2983
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002984 case AINPUT_EVENT_TYPE_MOTION: {
2985 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2986 int32_t action = motionEvent->getAction();
2987 size_t pointerCount = motionEvent->getPointerCount();
2988 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2989 int32_t actionButton = motionEvent->getActionButton();
2990 int32_t displayId = motionEvent->getDisplayId();
2991 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
2992 return INPUT_EVENT_INJECTION_FAILED;
2993 }
2994
2995 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2996 nsecs_t eventTime = motionEvent->getEventTime();
2997 android::base::Timer t;
2998 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
2999 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3000 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3001 std::to_string(t.duration().count()).c_str());
3002 }
3003 }
3004
3005 mLock.lock();
3006 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3007 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3008 MotionEntry* injectedEntry =
Garfield Tan00f511d2019-06-12 16:55:40 -07003009 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3010 motionEvent->getDeviceId(), motionEvent->getSource(),
3011 motionEvent->getDisplayId(), policyFlags, action, actionButton,
3012 motionEvent->getFlags(), motionEvent->getMetaState(),
3013 motionEvent->getButtonState(), motionEvent->getClassification(),
3014 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3015 motionEvent->getYPrecision(),
3016 motionEvent->getRawXCursorPosition(),
3017 motionEvent->getRawYCursorPosition(),
3018 motionEvent->getDownTime(), uint32_t(pointerCount),
3019 pointerProperties, samplePointerCoords,
3020 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003021 injectedEntries.push(injectedEntry);
3022 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3023 sampleEventTimes += 1;
3024 samplePointerCoords += pointerCount;
3025 MotionEntry* nextInjectedEntry =
3026 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3027 motionEvent->getDeviceId(), motionEvent->getSource(),
3028 motionEvent->getDisplayId(), policyFlags, action,
3029 actionButton, motionEvent->getFlags(),
3030 motionEvent->getMetaState(), motionEvent->getButtonState(),
3031 motionEvent->getClassification(),
3032 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3033 motionEvent->getYPrecision(),
3034 motionEvent->getRawXCursorPosition(),
3035 motionEvent->getRawYCursorPosition(),
3036 motionEvent->getDownTime(), uint32_t(pointerCount),
3037 pointerProperties, samplePointerCoords,
3038 motionEvent->getXOffset(), motionEvent->getYOffset());
3039 injectedEntries.push(nextInjectedEntry);
3040 }
3041 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003044 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003045 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 }
3048
3049 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3050 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3051 injectionState->injectionIsAsync = true;
3052 }
3053
3054 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003055 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056
3057 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003058 while (!injectedEntries.empty()) {
3059 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3060 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003061 }
3062
3063 mLock.unlock();
3064
3065 if (needWake) {
3066 mLooper->wake();
3067 }
3068
3069 int32_t injectionResult;
3070 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003071 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003072
3073 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3074 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3075 } else {
3076 for (;;) {
3077 injectionResult = injectionState->injectionResult;
3078 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3079 break;
3080 }
3081
3082 nsecs_t remainingTimeout = endTime - now();
3083 if (remainingTimeout <= 0) {
3084#if DEBUG_INJECTION
3085 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087#endif
3088 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3089 break;
3090 }
3091
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003092 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093 }
3094
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003095 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3096 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097 while (injectionState->pendingForegroundDispatches != 0) {
3098#if DEBUG_INJECTION
3099 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101#endif
3102 nsecs_t remainingTimeout = endTime - now();
3103 if (remainingTimeout <= 0) {
3104#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003105 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3106 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107#endif
3108 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3109 break;
3110 }
3111
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003112 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 }
3114 }
3115 }
3116
3117 injectionState->release();
3118 } // release lock
3119
3120#if DEBUG_INJECTION
3121 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122 "injectorPid=%d, injectorUid=%d",
3123 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124#endif
3125
3126 return injectionResult;
3127}
3128
3129bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003130 return injectorUid == 0 ||
3131 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132}
3133
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003134void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135 InjectionState* injectionState = entry->injectionState;
3136 if (injectionState) {
3137#if DEBUG_INJECTION
3138 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003139 "injectorPid=%d, injectorUid=%d",
3140 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141#endif
3142
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003143 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003144 // Log the outcome since the injector did not wait for the injection result.
3145 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003146 case INPUT_EVENT_INJECTION_SUCCEEDED:
3147 ALOGV("Asynchronous input event injection succeeded.");
3148 break;
3149 case INPUT_EVENT_INJECTION_FAILED:
3150 ALOGW("Asynchronous input event injection failed.");
3151 break;
3152 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3153 ALOGW("Asynchronous input event injection permission denied.");
3154 break;
3155 case INPUT_EVENT_INJECTION_TIMED_OUT:
3156 ALOGW("Asynchronous input event injection timed out.");
3157 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158 }
3159 }
3160
3161 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003162 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 }
3164}
3165
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003166void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167 InjectionState* injectionState = entry->injectionState;
3168 if (injectionState) {
3169 injectionState->pendingForegroundDispatches += 1;
3170 }
3171}
3172
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003173void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 InjectionState* injectionState = entry->injectionState;
3175 if (injectionState) {
3176 injectionState->pendingForegroundDispatches -= 1;
3177
3178 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003179 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 }
3181 }
3182}
3183
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003184std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3185 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003186 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003187}
3188
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003190 const sp<IBinder>& windowHandleToken) 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>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003194 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003195 return windowHandle;
3196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 }
3198 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003199 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200}
3201
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003202bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003203 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003204 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3205 for (const sp<InputWindowHandle>& handle : windowHandles) {
3206 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003207 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003208 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 ", but it should belong to display %" PRId32,
3210 windowHandle->getName().c_str(), it.first,
3211 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003212 }
3213 return true;
3214 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215 }
3216 }
3217 return false;
3218}
3219
Robert Carr5c8a0262018-10-03 16:30:44 -07003220sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3221 size_t count = mInputChannelsByToken.count(token);
3222 if (count == 0) {
3223 return nullptr;
3224 }
3225 return mInputChannelsByToken.at(token);
3226}
3227
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003228void InputDispatcher::updateWindowHandlesForDisplayLocked(
3229 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3230 if (inputWindowHandles.empty()) {
3231 // Remove all handles on a display if there are no windows left.
3232 mWindowHandlesByDisplay.erase(displayId);
3233 return;
3234 }
3235
3236 // Since we compare the pointer of input window handles across window updates, we need
3237 // to make sure the handle object for the same window stays unchanged across updates.
3238 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
3239 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3240 for (const sp<InputWindowHandle>& handle : oldHandles) {
3241 oldHandlesByTokens[handle->getToken()] = handle;
3242 }
3243
3244 std::vector<sp<InputWindowHandle>> newHandles;
3245 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3246 if (!handle->updateInfo()) {
3247 // handle no longer valid
3248 continue;
3249 }
3250
3251 const InputWindowInfo* info = handle->getInfo();
3252 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3253 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3254 const bool noInputChannel =
3255 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3256 const bool canReceiveInput =
3257 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3258 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3259 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003260 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003261 handle->getName().c_str());
3262 }
3263 continue;
3264 }
3265
3266 if (info->displayId != displayId) {
3267 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3268 handle->getName().c_str(), displayId, info->displayId);
3269 continue;
3270 }
3271
3272 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3273 const sp<InputWindowHandle> oldHandle = oldHandlesByTokens.at(handle->getToken());
3274 oldHandle->updateFrom(handle);
3275 newHandles.push_back(oldHandle);
3276 } else {
3277 newHandles.push_back(handle);
3278 }
3279 }
3280
3281 // Insert or replace
3282 mWindowHandlesByDisplay[displayId] = newHandles;
3283}
3284
Arthur Hungb92218b2018-08-14 12:00:21 +08003285/**
3286 * Called from InputManagerService, update window handle list by displayId that can receive input.
3287 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3288 * If set an empty list, remove all handles from the specific display.
3289 * For focused handle, check if need to change and send a cancel event to previous one.
3290 * For removed handle, check if need to send a cancel event if already in touch.
3291 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003292void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003293 int32_t displayId,
3294 const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003295 if (DEBUG_FOCUS) {
3296 std::string windowList;
3297 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3298 windowList += iwh->getName() + " ";
3299 }
3300 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003303 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304
Arthur Hungb92218b2018-08-14 12:00:21 +08003305 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003306 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3307 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003309 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
3310
Tiger Huang721e26f2018-07-24 22:26:19 +08003311 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 bool foundHoveredWindow = false;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003313 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3314 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3315 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3316 windowHandle->getInfo()->visible) {
3317 newFocusedWindowHandle = windowHandle;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003318 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003319 if (windowHandle == mLastHoverWindowHandle) {
3320 foundHoveredWindow = true;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322 }
3323
3324 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003325 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326 }
3327
Tiger Huang721e26f2018-07-24 22:26:19 +08003328 sp<InputWindowHandle> oldFocusedWindowHandle =
3329 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3330
3331 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3332 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003333 if (DEBUG_FOCUS) {
3334 ALOGD("Focus left window: %s in display %" PRId32,
3335 oldFocusedWindowHandle->getName().c_str(), displayId);
3336 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 sp<InputChannel> focusedInputChannel =
3338 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003339 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 "focus left window");
3342 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003344 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003346 if (newFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003347 if (DEBUG_FOCUS) {
3348 ALOGD("Focus entered window: %s in display %" PRId32,
3349 newFocusedWindowHandle->getName().c_str(), displayId);
3350 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003351 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352 }
Robert Carrf759f162018-11-13 12:57:11 -08003353
3354 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003355 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 }
3358
Arthur Hungb92218b2018-08-14 12:00:21 +08003359 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3360 if (stateIndex >= 0) {
3361 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003362 for (size_t i = 0; i < state.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003363 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003364 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003365 if (DEBUG_FOCUS) {
3366 ALOGD("Touched window was removed: %s in display %" PRId32,
3367 touchedWindow.windowHandle->getName().c_str(), displayId);
3368 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003369 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003370 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003371 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003372 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003373 "touched window was removed");
3374 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3375 options);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003376 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003377 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003378 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 }
3382 }
3383
3384 // Release information for windows that are no longer present.
3385 // This ensures that unused input channels are released promptly.
3386 // Otherwise, they might stick around until the window handle is destroyed
3387 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003388 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003389 if (!hasWindowHandleLocked(oldWindowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003390 if (DEBUG_FOCUS) {
3391 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
3392 }
Arthur Hung3b413f22018-10-26 18:05:34 +08003393 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 }
3395 }
3396 } // release lock
3397
3398 // Wake up poll loop since it may need to make new input dispatching choices.
3399 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003400
3401 if (setInputWindowsListener) {
3402 setInputWindowsListener->onSetInputWindowsFinished();
3403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404}
3405
3406void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003407 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003408 if (DEBUG_FOCUS) {
3409 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3410 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003413 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414
Tiger Huang721e26f2018-07-24 22:26:19 +08003415 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3416 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003417 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003418 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3419 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003422 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003424 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003426 oldFocusedApplicationHandle.clear();
3427 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429 } // release lock
3430
3431 // Wake up poll loop since it may need to make new input dispatching choices.
3432 mLooper->wake();
3433}
3434
Tiger Huang721e26f2018-07-24 22:26:19 +08003435/**
3436 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3437 * the display not specified.
3438 *
3439 * We track any unreleased events for each window. If a window loses the ability to receive the
3440 * released event, we will send a cancel event to it. So when the focused display is changed, we
3441 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3442 * display. The display-specified events won't be affected.
3443 */
3444void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003445 if (DEBUG_FOCUS) {
3446 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3447 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003448 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003449 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003450
3451 if (mFocusedDisplayId != displayId) {
3452 sp<InputWindowHandle> oldFocusedWindowHandle =
3453 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3454 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003455 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003456 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003457 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003458 CancelationOptions
3459 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3460 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003461 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003462 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3463 }
3464 }
3465 mFocusedDisplayId = displayId;
3466
3467 // Sanity check
3468 sp<InputWindowHandle> newFocusedWindowHandle =
3469 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003470 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003471
Tiger Huang721e26f2018-07-24 22:26:19 +08003472 if (newFocusedWindowHandle == nullptr) {
3473 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3474 if (!mFocusedWindowHandlesByDisplay.empty()) {
3475 ALOGE("But another display has a focused window:");
3476 for (auto& it : mFocusedWindowHandlesByDisplay) {
3477 const int32_t displayId = it.first;
3478 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003479 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3480 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003481 }
3482 }
3483 }
3484 }
3485
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003486 if (DEBUG_FOCUS) {
3487 logDispatchStateLocked();
3488 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003489 } // release lock
3490
3491 // Wake up poll loop since it may need to make new input dispatching choices.
3492 mLooper->wake();
3493}
3494
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003496 if (DEBUG_FOCUS) {
3497 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499
3500 bool changed;
3501 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003502 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503
3504 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3505 if (mDispatchFrozen && !frozen) {
3506 resetANRTimeoutsLocked();
3507 }
3508
3509 if (mDispatchEnabled && !enabled) {
3510 resetAndDropEverythingLocked("dispatcher is being disabled");
3511 }
3512
3513 mDispatchEnabled = enabled;
3514 mDispatchFrozen = frozen;
3515 changed = true;
3516 } else {
3517 changed = false;
3518 }
3519
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003520 if (DEBUG_FOCUS) {
3521 logDispatchStateLocked();
3522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523 } // release lock
3524
3525 if (changed) {
3526 // Wake up poll loop since it may need to make new input dispatching choices.
3527 mLooper->wake();
3528 }
3529}
3530
3531void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003532 if (DEBUG_FOCUS) {
3533 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535
3536 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003537 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538
3539 if (mInputFilterEnabled == enabled) {
3540 return;
3541 }
3542
3543 mInputFilterEnabled = enabled;
3544 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3545 } // release lock
3546
3547 // Wake up poll loop since there might be work to do to drop everything.
3548 mLooper->wake();
3549}
3550
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003551void InputDispatcher::setInTouchMode(bool inTouchMode) {
3552 std::scoped_lock lock(mLock);
3553 mInTouchMode = inTouchMode;
3554}
3555
chaviwfbe5d9c2018-12-26 12:23:37 -08003556bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3557 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003558 if (DEBUG_FOCUS) {
3559 ALOGD("Trivial transfer to same window.");
3560 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003561 return true;
3562 }
3563
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003565 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566
chaviwfbe5d9c2018-12-26 12:23:37 -08003567 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3568 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003569 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003570 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571 return false;
3572 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003573 if (DEBUG_FOCUS) {
3574 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3575 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003578 if (DEBUG_FOCUS) {
3579 ALOGD("Cannot transfer focus because windows are on different displays.");
3580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581 return false;
3582 }
3583
3584 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003585 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3586 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3587 for (size_t i = 0; i < state.windows.size(); i++) {
3588 const TouchedWindow& touchedWindow = state.windows[i];
3589 if (touchedWindow.windowHandle == fromWindowHandle) {
3590 int32_t oldTargetFlags = touchedWindow.targetFlags;
3591 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003593 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003595 int32_t newTargetFlags = oldTargetFlags &
3596 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3597 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003598 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599
Jeff Brownf086ddb2014-02-11 14:28:48 -08003600 found = true;
3601 goto Found;
3602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 }
3604 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003605 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003607 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003608 if (DEBUG_FOCUS) {
3609 ALOGD("Focus transfer failed because from window did not have focus.");
3610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 return false;
3612 }
3613
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003614 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3615 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003616 if (fromConnection != nullptr && toConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003618 CancelationOptions
3619 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3620 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3622 }
3623
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003624 if (DEBUG_FOCUS) {
3625 logDispatchStateLocked();
3626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627 } // release lock
3628
3629 // Wake up poll loop since it may need to make new input dispatching choices.
3630 mLooper->wake();
3631 return true;
3632}
3633
3634void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003635 if (DEBUG_FOCUS) {
3636 ALOGD("Resetting and dropping all events (%s).", reason);
3637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638
3639 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3640 synthesizeCancelationEventsForAllConnectionsLocked(options);
3641
3642 resetKeyRepeatLocked();
3643 releasePendingEventLocked();
3644 drainInboundQueueLocked();
3645 resetANRTimeoutsLocked();
3646
Jeff Brownf086ddb2014-02-11 14:28:48 -08003647 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003649 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650}
3651
3652void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003653 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 dumpDispatchStateLocked(dump);
3655
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003656 std::istringstream stream(dump);
3657 std::string line;
3658
3659 while (std::getline(stream, line, '\n')) {
3660 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 }
3662}
3663
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003664void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003665 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3666 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3667 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003668 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669
Tiger Huang721e26f2018-07-24 22:26:19 +08003670 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3671 dump += StringPrintf(INDENT "FocusedApplications:\n");
3672 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3673 const int32_t displayId = it.first;
3674 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003675 dump += StringPrintf(INDENT2 "displayId=%" PRId32
3676 ", name='%s', dispatchingTimeout=%0.3fms\n",
3677 displayId, applicationHandle->getName().c_str(),
3678 applicationHandle->getDispatchingTimeout(
3679 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3680 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08003681 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003683 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003685
3686 if (!mFocusedWindowHandlesByDisplay.empty()) {
3687 dump += StringPrintf(INDENT "FocusedWindows:\n");
3688 for (auto& it : mFocusedWindowHandlesByDisplay) {
3689 const int32_t displayId = it.first;
3690 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003691 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3692 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003693 }
3694 } else {
3695 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697
Jeff Brownf086ddb2014-02-11 14:28:48 -08003698 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003699 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003700 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3701 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003702 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003703 state.displayId, toString(state.down), toString(state.split),
3704 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003705 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003706 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003707 for (size_t i = 0; i < state.windows.size(); i++) {
3708 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003709 dump += StringPrintf(INDENT4
3710 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3711 i, touchedWindow.windowHandle->getName().c_str(),
3712 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003713 }
3714 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003715 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003716 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003717 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003718 dump += INDENT3 "Portal windows:\n";
3719 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003720 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003721 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3722 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003723 }
3724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003725 }
3726 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003727 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 }
3729
Arthur Hungb92218b2018-08-14 12:00:21 +08003730 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003731 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003732 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003733 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003734 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003735 dump += INDENT2 "Windows:\n";
3736 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003737 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003738 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739
Arthur Hungb92218b2018-08-14 12:00:21 +08003740 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003741 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
3742 "hasWallpaper=%s, "
3743 "visible=%s, canReceiveKeys=%s, flags=0x%08x, "
3744 "type=0x%08x, layer=%d, "
3745 "frame=[%d,%d][%d,%d], globalScale=%f, "
3746 "windowScale=(%f,%f), "
3747 "touchableRegion=",
3748 i, windowInfo->name.c_str(), windowInfo->displayId,
3749 windowInfo->portalToDisplayId,
3750 toString(windowInfo->paused),
3751 toString(windowInfo->hasFocus),
3752 toString(windowInfo->hasWallpaper),
3753 toString(windowInfo->visible),
3754 toString(windowInfo->canReceiveKeys),
3755 windowInfo->layoutParamsFlags,
3756 windowInfo->layoutParamsType, windowInfo->layer,
3757 windowInfo->frameLeft, windowInfo->frameTop,
3758 windowInfo->frameRight, windowInfo->frameBottom,
3759 windowInfo->globalScaleFactor, windowInfo->windowXScale,
3760 windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003761 dumpRegion(dump, windowInfo->touchableRegion);
3762 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3763 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003764 windowInfo->ownerPid, windowInfo->ownerUid,
3765 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08003766 }
3767 } else {
3768 dump += INDENT2 "Windows: <none>\n";
3769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 }
3771 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003772 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 }
3774
Michael Wright3dd60e22019-03-27 22:06:44 +00003775 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003776 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003777 const std::vector<Monitor>& monitors = it.second;
3778 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3779 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003780 }
3781 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003782 const std::vector<Monitor>& monitors = it.second;
3783 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3784 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003785 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003787 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 }
3789
3790 nsecs_t currentTime = now();
3791
3792 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003793 if (!mRecentQueue.empty()) {
3794 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
3795 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003796 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003798 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 }
3800 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003801 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802 }
3803
3804 // Dump event currently being dispatched.
3805 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003806 dump += INDENT "PendingEvent:\n";
3807 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003809 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003810 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003812 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 }
3814
3815 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003816 if (!mInboundQueue.empty()) {
3817 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
3818 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003819 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003821 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 }
3823 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003824 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 }
3826
Michael Wright78f24442014-08-06 15:55:28 -07003827 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003828 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003829 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3830 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3831 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003832 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3833 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07003834 }
3835 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003836 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003837 }
3838
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003839 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003840 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003841 for (const auto& pair : mConnectionsByFd) {
3842 const sp<Connection>& connection = pair.second;
3843 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
3844 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3845 pair.first, connection->getInputChannelName().c_str(),
3846 connection->getWindowName().c_str(), connection->getStatusLabel(),
3847 toString(connection->monitor),
3848 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003850 if (!connection->outboundQueue.empty()) {
3851 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
3852 connection->outboundQueue.size());
3853 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 dump.append(INDENT4);
3855 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003856 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003857 entry->targetFlags, entry->resolvedAction,
3858 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859 }
3860 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003861 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862 }
3863
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003864 if (!connection->waitQueue.empty()) {
3865 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
3866 connection->waitQueue.size());
3867 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003868 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003870 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003871 "age=%0.1fms, wait=%0.1fms\n",
3872 entry->targetFlags, entry->resolvedAction,
3873 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3874 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875 }
3876 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003877 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878 }
3879 }
3880 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003881 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882 }
3883
3884 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003885 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003886 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003888 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889 }
3890
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003891 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003892 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003893 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003894 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895}
3896
Michael Wright3dd60e22019-03-27 22:06:44 +00003897void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3898 const size_t numMonitors = monitors.size();
3899 for (size_t i = 0; i < numMonitors; i++) {
3900 const Monitor& monitor = monitors[i];
3901 const sp<InputChannel>& channel = monitor.inputChannel;
3902 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3903 dump += "\n";
3904 }
3905}
3906
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003907status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003909 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910#endif
3911
3912 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003913 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003914 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003915 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003917 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918 return BAD_VALUE;
3919 }
3920
Michael Wright3dd60e22019-03-27 22:06:44 +00003921 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922
3923 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003924 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003925 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3928 } // release lock
3929
3930 // Wake the looper because some connections have changed.
3931 mLooper->wake();
3932 return OK;
3933}
3934
Michael Wright3dd60e22019-03-27 22:06:44 +00003935status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003936 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003937 { // acquire lock
3938 std::scoped_lock _l(mLock);
3939
3940 if (displayId < 0) {
3941 ALOGW("Attempted to register input monitor without a specified display.");
3942 return BAD_VALUE;
3943 }
3944
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003945 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003946 ALOGW("Attempted to register input monitor without an identifying token.");
3947 return BAD_VALUE;
3948 }
3949
3950 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3951
3952 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003953 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003954 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00003955
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003956 auto& monitorsByDisplay =
3957 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00003958 monitorsByDisplay[displayId].emplace_back(inputChannel);
3959
3960 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00003961 }
3962 // Wake the looper because some connections have changed.
3963 mLooper->wake();
3964 return OK;
3965}
3966
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3968#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003969 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970#endif
3971
3972 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003973 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974
3975 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3976 if (status) {
3977 return status;
3978 }
3979 } // release lock
3980
3981 // Wake the poll loop because removing the connection may have changed the current
3982 // synchronization state.
3983 mLooper->wake();
3984 return OK;
3985}
3986
3987status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003988 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003989 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003990 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003992 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 return BAD_VALUE;
3994 }
3995
John Recke0710582019-09-26 13:46:12 -07003996 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003997 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003998 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07003999
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000 if (connection->monitor) {
4001 removeMonitorChannelLocked(inputChannel);
4002 }
4003
4004 mLooper->removeFd(inputChannel->getFd());
4005
4006 nsecs_t currentTime = now();
4007 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4008
4009 connection->status = Connection::STATUS_ZOMBIE;
4010 return OK;
4011}
4012
4013void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004014 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4015 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4016}
4017
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004018void InputDispatcher::removeMonitorChannelLocked(
4019 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004020 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004021 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004022 std::vector<Monitor>& monitors = it->second;
4023 const size_t numMonitors = monitors.size();
4024 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004025 if (monitors[i].inputChannel == inputChannel) {
4026 monitors.erase(monitors.begin() + i);
4027 break;
4028 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004029 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004030 if (monitors.empty()) {
4031 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004032 } else {
4033 ++it;
4034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035 }
4036}
4037
Michael Wright3dd60e22019-03-27 22:06:44 +00004038status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4039 { // acquire lock
4040 std::scoped_lock _l(mLock);
4041 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4042
4043 if (!foundDisplayId) {
4044 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4045 return BAD_VALUE;
4046 }
4047 int32_t displayId = foundDisplayId.value();
4048
4049 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4050 if (stateIndex < 0) {
4051 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4052 return BAD_VALUE;
4053 }
4054
4055 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4056 std::optional<int32_t> foundDeviceId;
4057 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004058 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004059 foundDeviceId = state.deviceId;
4060 }
4061 }
4062 if (!foundDeviceId || !state.down) {
4063 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004064 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004065 return BAD_VALUE;
4066 }
4067 int32_t deviceId = foundDeviceId.value();
4068
4069 // Send cancel events to all the input channels we're stealing from.
4070 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004071 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004072 options.deviceId = deviceId;
4073 options.displayId = displayId;
4074 for (const TouchedWindow& window : state.windows) {
4075 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
4076 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4077 }
4078 // Then clear the current touch state so we stop dispatching to them as well.
4079 state.filterNonMonitors();
4080 }
4081 return OK;
4082}
4083
Michael Wright3dd60e22019-03-27 22:06:44 +00004084std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4085 const sp<IBinder>& token) {
4086 for (const auto& it : mGestureMonitorsByDisplay) {
4087 const std::vector<Monitor>& monitors = it.second;
4088 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004089 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004090 return it.first;
4091 }
4092 }
4093 }
4094 return std::nullopt;
4095}
4096
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004097sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4098 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004099 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004100 }
4101
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004102 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004103 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004104 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004105 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 }
4107 }
Robert Carr4e670e52018-08-15 13:26:12 -07004108
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004109 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110}
4111
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004112void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4113 const sp<Connection>& connection, uint32_t seq,
4114 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004115 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4116 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 commandEntry->connection = connection;
4118 commandEntry->eventTime = currentTime;
4119 commandEntry->seq = seq;
4120 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004121 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122}
4123
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004124void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4125 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004127 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004129 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4130 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004132 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133}
4134
chaviw0c06c6e2019-01-09 13:27:07 -08004135void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004136 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004137 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4138 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004139 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4140 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004141 commandEntry->oldToken = oldToken;
4142 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004143 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004144}
4145
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004146void InputDispatcher::onANRLocked(nsecs_t currentTime,
4147 const sp<InputApplicationHandle>& applicationHandle,
4148 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4149 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4151 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4152 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004153 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4154 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4155 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156
4157 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004158 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159 struct tm tm;
4160 localtime_r(&t, &tm);
4161 char timestr[64];
4162 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4163 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004164 mLastANRState += INDENT "ANR:\n";
4165 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004166 mLastANRState +=
4167 StringPrintf(INDENT2 "Window: %s\n",
4168 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004169 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4170 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4171 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 dumpDispatchStateLocked(mLastANRState);
4173
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004174 std::unique_ptr<CommandEntry> commandEntry =
4175 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004177 commandEntry->inputChannel =
4178 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004180 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181}
4182
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004183void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 mLock.unlock();
4185
4186 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4187
4188 mLock.lock();
4189}
4190
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004191void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 sp<Connection> connection = commandEntry->connection;
4193
4194 if (connection->status != Connection::STATUS_ZOMBIE) {
4195 mLock.unlock();
4196
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004197 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198
4199 mLock.lock();
4200 }
4201}
4202
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004203void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004204 sp<IBinder> oldToken = commandEntry->oldToken;
4205 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004206 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004207 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004208 mLock.lock();
4209}
4210
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004211void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004212 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004213 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 mLock.unlock();
4215
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004216 nsecs_t newTimeout =
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004217 mPolicy->notifyANR(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218
4219 mLock.lock();
4220
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004221 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222}
4223
4224void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4225 CommandEntry* commandEntry) {
4226 KeyEntry* entry = commandEntry->keyEntry;
4227
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004228 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229
4230 mLock.unlock();
4231
Michael Wright2b3c3302018-03-02 17:19:13 +00004232 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004234 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004235 : nullptr;
4236 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004237 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4238 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004239 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004240 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241
4242 mLock.lock();
4243
4244 if (delay < 0) {
4245 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4246 } else if (!delay) {
4247 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4248 } else {
4249 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4250 entry->interceptKeyWakeupTime = now() + delay;
4251 }
4252 entry->release();
4253}
4254
chaviwfd6d3512019-03-25 13:23:49 -07004255void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4256 mLock.unlock();
4257 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4258 mLock.lock();
4259}
4260
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004263 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004265 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266
4267 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004268 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004269 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004270 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004272 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004273
4274 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4275 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4276 std::string msg =
4277 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4278 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4279 dispatchEntry->eventEntry->appendDescription(msg);
4280 ALOGI("%s", msg.c_str());
4281 }
4282
4283 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004284 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004285 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4286 restartEvent =
4287 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004288 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004289 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4290 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4291 handled);
4292 } else {
4293 restartEvent = false;
4294 }
4295
4296 // Dequeue the event and start the next cycle.
4297 // Note that because the lock might have been released, it is possible that the
4298 // contents of the wait queue to have been drained, so we need to double-check
4299 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004300 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4301 if (dispatchEntryIt != connection->waitQueue.end()) {
4302 dispatchEntry = *dispatchEntryIt;
4303 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004304 traceWaitQueueLength(connection);
4305 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004306 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004307 traceOutboundQueueLength(connection);
4308 } else {
4309 releaseDispatchEntry(dispatchEntry);
4310 }
4311 }
4312
4313 // Start the next dispatch cycle for this connection.
4314 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315}
4316
4317bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004318 DispatchEntry* dispatchEntry,
4319 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004320 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004321 if (!handled) {
4322 // Report the key as unhandled, since the fallback was not handled.
4323 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4324 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004325 return false;
4326 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004328 // Get the fallback key state.
4329 // Clear it out after dispatching the UP.
4330 int32_t originalKeyCode = keyEntry->keyCode;
4331 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4332 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4333 connection->inputState.removeFallbackKey(originalKeyCode);
4334 }
4335
4336 if (handled || !dispatchEntry->hasForegroundTarget()) {
4337 // If the application handles the original key for which we previously
4338 // generated a fallback or if the window is not a foreground window,
4339 // then cancel the associated fallback key, if any.
4340 if (fallbackKeyCode != -1) {
4341 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004343 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004344 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4345 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4346 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004348 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004349 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350
4351 mLock.unlock();
4352
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004353 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004354 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355
4356 mLock.lock();
4357
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004358 // Cancel the fallback key.
4359 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004361 "application handled the original non-fallback key "
4362 "or is no longer a foreground target, "
4363 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 options.keyCode = fallbackKeyCode;
4365 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004367 connection->inputState.removeFallbackKey(originalKeyCode);
4368 }
4369 } else {
4370 // If the application did not handle a non-fallback key, first check
4371 // that we are in a good state to perform unhandled key event processing
4372 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004373 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004374 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004376 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004377 "since this is not an initial down. "
4378 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4379 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004381 return false;
4382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004384 // Dispatch the unhandled key to the policy.
4385#if DEBUG_OUTBOUND_EVENT_DETAILS
4386 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004387 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4388 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004389#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004390 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004391
4392 mLock.unlock();
4393
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004394 bool fallback =
4395 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4396 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004397
4398 mLock.lock();
4399
4400 if (connection->status != Connection::STATUS_NORMAL) {
4401 connection->inputState.removeFallbackKey(originalKeyCode);
4402 return false;
4403 }
4404
4405 // Latch the fallback keycode for this key on an initial down.
4406 // The fallback keycode cannot change at any other point in the lifecycle.
4407 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004409 fallbackKeyCode = event.getKeyCode();
4410 } else {
4411 fallbackKeyCode = AKEYCODE_UNKNOWN;
4412 }
4413 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4414 }
4415
4416 ALOG_ASSERT(fallbackKeyCode != -1);
4417
4418 // Cancel the fallback key if the policy decides not to send it anymore.
4419 // We will continue to dispatch the key to the policy but we will no
4420 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004421 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4422 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004423#if DEBUG_OUTBOUND_EVENT_DETAILS
4424 if (fallback) {
4425 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004426 "as a fallback for %d, but on the DOWN it had requested "
4427 "to send %d instead. Fallback canceled.",
4428 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004429 } else {
4430 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004431 "but on the DOWN it had requested to send %d. "
4432 "Fallback canceled.",
4433 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004434 }
4435#endif
4436
4437 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4438 "canceling fallback, policy no longer desires it");
4439 options.keyCode = fallbackKeyCode;
4440 synthesizeCancelationEventsForConnectionLocked(connection, options);
4441
4442 fallback = false;
4443 fallbackKeyCode = AKEYCODE_UNKNOWN;
4444 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004445 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004446 }
4447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448
4449#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004450 {
4451 std::string msg;
4452 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4453 connection->inputState.getFallbackKeys();
4454 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004455 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004457 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004458 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004459 }
4460#endif
4461
4462 if (fallback) {
4463 // Restart the dispatch cycle using the fallback key.
4464 keyEntry->eventTime = event.getEventTime();
4465 keyEntry->deviceId = event.getDeviceId();
4466 keyEntry->source = event.getSource();
4467 keyEntry->displayId = event.getDisplayId();
4468 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4469 keyEntry->keyCode = fallbackKeyCode;
4470 keyEntry->scanCode = event.getScanCode();
4471 keyEntry->metaState = event.getMetaState();
4472 keyEntry->repeatCount = event.getRepeatCount();
4473 keyEntry->downTime = event.getDownTime();
4474 keyEntry->syntheticRepeat = false;
4475
4476#if DEBUG_OUTBOUND_EVENT_DETAILS
4477 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004478 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4479 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004480#endif
4481 return true; // restart the event
4482 } else {
4483#if DEBUG_OUTBOUND_EVENT_DETAILS
4484 ALOGD("Unhandled key event: No fallback key.");
4485#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004486
4487 // Report the key as unhandled, since there is no fallback key.
4488 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 }
4490 }
4491 return false;
4492}
4493
4494bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004495 DispatchEntry* dispatchEntry,
4496 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497 return false;
4498}
4499
4500void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4501 mLock.unlock();
4502
4503 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4504
4505 mLock.lock();
4506}
4507
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004508KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4509 KeyEvent event;
4510 event.initialize(entry.deviceId, entry.source, entry.displayId, entry.action, entry.flags,
4511 entry.keyCode, entry.scanCode, entry.metaState, entry.repeatCount,
4512 entry.downTime, entry.eventTime);
4513 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514}
4515
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004516void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004517 int32_t injectionResult,
4518 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 // TODO Write some statistics about how long we spend waiting.
4520}
4521
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004522/**
4523 * Report the touch event latency to the statsd server.
4524 * Input events are reported for statistics if:
4525 * - This is a touchscreen event
4526 * - InputFilter is not enabled
4527 * - Event is not injected or synthesized
4528 *
4529 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4530 * from getting aggregated with the "old" data.
4531 */
4532void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4533 REQUIRES(mLock) {
4534 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4535 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4536 if (!reportForStatistics) {
4537 return;
4538 }
4539
4540 if (mTouchStatistics.shouldReport()) {
4541 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4542 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4543 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4544 mTouchStatistics.reset();
4545 }
4546 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4547 mTouchStatistics.addValue(latencyMicros);
4548}
4549
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550void InputDispatcher::traceInboundQueueLengthLocked() {
4551 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004552 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 }
4554}
4555
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004556void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 if (ATRACE_ENABLED()) {
4558 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004559 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004560 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561 }
4562}
4563
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004564void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 if (ATRACE_ENABLED()) {
4566 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004567 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004568 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 }
4570}
4571
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004572void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004573 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004575 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576 dumpDispatchStateLocked(dump);
4577
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004578 if (!mLastANRState.empty()) {
4579 dump += "\nInput Dispatcher State at time of last ANR:\n";
4580 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 }
4582}
4583
4584void InputDispatcher::monitor() {
4585 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004586 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004588 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589}
4590
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004591/**
4592 * Wake up the dispatcher and wait until it processes all events and commands.
4593 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4594 * this method can be safely called from any thread, as long as you've ensured that
4595 * the work you are interested in completing has already been queued.
4596 */
4597bool InputDispatcher::waitForIdle() {
4598 /**
4599 * Timeout should represent the longest possible time that a device might spend processing
4600 * events and commands.
4601 */
4602 constexpr std::chrono::duration TIMEOUT = 100ms;
4603 std::unique_lock lock(mLock);
4604 mLooper->wake();
4605 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4606 return result == std::cv_status::no_timeout;
4607}
4608
Garfield Tane84e6f92019-08-29 17:28:41 -07004609} // namespace android::inputdispatcher