blob: 5a49b5e16a73e69e16ae227dc19628fad1e5152b [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
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700243// --- InputDispatcherThread ---
244
245class InputDispatcher::InputDispatcherThread : public Thread {
246public:
247 explicit InputDispatcherThread(InputDispatcher* dispatcher)
248 : Thread(/* canCallJava */ true), mDispatcher(dispatcher) {}
249
250 ~InputDispatcherThread() {}
251
252private:
253 InputDispatcher* mDispatcher;
254
255 virtual bool threadLoop() override {
256 mDispatcher->dispatchOnce();
257 return true;
258 }
259};
260
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261// --- InputDispatcher ---
262
Garfield Tan00f511d2019-06-12 16:55:40 -0700263InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
264 : mPolicy(policy),
265 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700266 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tan00f511d2019-06-12 16:55:40 -0700267 mAppSwitchSawKeyDown(false),
268 mAppSwitchDueTime(LONG_LONG_MAX),
269 mNextUnblockedEvent(nullptr),
270 mDispatchEnabled(false),
271 mDispatchFrozen(false),
272 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800273 // mInTouchMode will be initialized by the WindowManager to the default device config.
274 // To avoid leaking stack in case that call never comes, and for tests,
275 // initialize it here anyways.
276 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700277 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
278 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800279 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800280 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800281
Yi Kong9b14ac62018-07-17 13:48:38 -0700282 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800283
284 policy->getDispatcherConfiguration(&mConfig);
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700285
286 mThread = new InputDispatcherThread(this);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800287}
288
289InputDispatcher::~InputDispatcher() {
290 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800291 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800292
293 resetKeyRepeatLocked();
294 releasePendingEventLocked();
295 drainInboundQueueLocked();
296 }
297
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700298 while (!mConnectionsByFd.empty()) {
299 sp<Connection> connection = mConnectionsByFd.begin()->second;
300 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800301 }
302}
303
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700304status_t InputDispatcher::start() {
305 if (mThread->isRunning()) {
306 return ALREADY_EXISTS;
307 }
308 return mThread->run("InputDispatcher", PRIORITY_URGENT_DISPLAY);
309}
310
311status_t InputDispatcher::stop() {
312 if (!mThread->isRunning()) {
313 return OK;
314 }
315 if (gettid() == mThread->getTid()) {
316 ALOGE("InputDispatcher can only be stopped from outside of the InputDispatcherThread!");
317 return INVALID_OPERATION;
318 }
319 // Directly calling requestExitAndWait() causes the thread to not exit
320 // if mLooper is waiting for a long timeout.
321 mThread->requestExit();
322 mLooper->wake();
323 return mThread->requestExitAndWait();
324}
325
Michael Wrightd02c5b62014-02-10 15:10:22 -0800326void InputDispatcher::dispatchOnce() {
327 nsecs_t nextWakeupTime = LONG_LONG_MAX;
328 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800329 std::scoped_lock _l(mLock);
330 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800331
332 // Run a dispatch loop if there are no pending commands.
333 // The dispatch loop might enqueue commands to run afterwards.
334 if (!haveCommandsLocked()) {
335 dispatchOnceInnerLocked(&nextWakeupTime);
336 }
337
338 // Run all pending commands if there are any.
339 // If any commands were run then force the next poll to wake up immediately.
340 if (runCommandsLockedInterruptible()) {
341 nextWakeupTime = LONG_LONG_MIN;
342 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800343
344 // We are about to enter an infinitely long sleep, because we have no commands or
345 // pending or queued events
346 if (nextWakeupTime == LONG_LONG_MAX) {
347 mDispatcherEnteredIdle.notify_all();
348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800349 } // release lock
350
351 // Wait for callback or timeout or wake. (make sure we round up, not down)
352 nsecs_t currentTime = now();
353 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
354 mLooper->pollOnce(timeoutMillis);
355}
356
357void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
358 nsecs_t currentTime = now();
359
Jeff Browndc5992e2014-04-11 01:27:26 -0700360 // Reset the key repeat timer whenever normal dispatch is suspended while the
361 // device is in a non-interactive state. This is to ensure that we abort a key
362 // repeat if the device is just coming out of sleep.
363 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800364 resetKeyRepeatLocked();
365 }
366
367 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
368 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100369 if (DEBUG_FOCUS) {
370 ALOGD("Dispatch frozen. Waiting some more.");
371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800372 return;
373 }
374
375 // Optimize latency of app switches.
376 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
377 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
378 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
379 if (mAppSwitchDueTime < *nextWakeupTime) {
380 *nextWakeupTime = mAppSwitchDueTime;
381 }
382
383 // Ready to start a new event.
384 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700385 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700386 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800387 if (isAppSwitchDue) {
388 // The inbound queue is empty so the app switch key we were waiting
389 // for will never arrive. Stop waiting for it.
390 resetPendingAppSwitchLocked(false);
391 isAppSwitchDue = false;
392 }
393
394 // Synthesize a key repeat if appropriate.
395 if (mKeyRepeatState.lastKeyEntry) {
396 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
397 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
398 } else {
399 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
400 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
401 }
402 }
403 }
404
405 // Nothing to do if there is no pending event.
406 if (!mPendingEvent) {
407 return;
408 }
409 } else {
410 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700411 mPendingEvent = mInboundQueue.front();
412 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413 traceInboundQueueLengthLocked();
414 }
415
416 // Poke user activity for this event.
417 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700418 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419 }
420
421 // Get ready to dispatch the event.
422 resetANRTimeoutsLocked();
423 }
424
425 // Now we have an event to dispatch.
426 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700427 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800428 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700429 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800430 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700431 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800432 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700433 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800434 }
435
436 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700437 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438 }
439
440 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700441 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700442 ConfigurationChangedEntry* typedEntry =
443 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
444 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700445 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700446 break;
447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700449 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700450 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
451 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700452 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700453 break;
454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700456 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700457 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
458 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700459 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700460 resetPendingAppSwitchLocked(true);
461 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700462 } else if (dropReason == DropReason::NOT_DROPPED) {
463 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700464 }
465 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700466 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700467 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700468 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700469 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
470 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700471 }
472 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
473 break;
474 }
475
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700476 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700477 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700478 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
479 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800480 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700481 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700482 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700483 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700484 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
485 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700486 }
487 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
488 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490 }
491
492 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700493 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700494 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800495 }
Michael Wright3a981722015-06-10 15:26:13 +0100496 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800497
498 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700499 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500 }
501}
502
503bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700504 bool needWake = mInboundQueue.empty();
505 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 traceInboundQueueLengthLocked();
507
508 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700509 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700510 // Optimize app switch latency.
511 // If the application takes too long to catch up then we drop all events preceding
512 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700513 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700514 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700515 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700516 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700517 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700518 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700520 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700522 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700523 mAppSwitchSawKeyDown = false;
524 needWake = true;
525 }
526 }
527 }
528 break;
529 }
530
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700531 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700532 // Optimize case where the current application is unresponsive and the user
533 // decides to touch a window in a different application.
534 // If the application takes too long to catch up then we drop all events preceding
535 // the touch into the other window.
536 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
537 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
538 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
539 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
540 mInputTargetWaitApplicationToken != nullptr) {
541 int32_t displayId = motionEntry->displayId;
542 int32_t x =
543 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
544 int32_t y =
545 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
546 sp<InputWindowHandle> touchedWindowHandle =
547 findTouchedWindowAtLocked(displayId, x, y);
548 if (touchedWindowHandle != nullptr &&
549 touchedWindowHandle->getApplicationToken() !=
550 mInputTargetWaitApplicationToken) {
551 // User touched a different application than the one we are waiting on.
552 // Flag the event, and start pruning the input queue.
553 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 needWake = true;
555 }
556 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700557 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700559 case EventEntry::Type::CONFIGURATION_CHANGED:
560 case EventEntry::Type::DEVICE_RESET: {
561 // nothing to do
562 break;
563 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564 }
565
566 return needWake;
567}
568
569void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
570 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700571 mRecentQueue.push_back(entry);
572 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
573 mRecentQueue.front()->release();
574 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575 }
576}
577
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700578sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
579 int32_t y, bool addOutsideTargets,
580 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800582 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
583 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800584 const InputWindowInfo* windowInfo = windowHandle->getInfo();
585 if (windowInfo->displayId == displayId) {
586 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800587
588 if (windowInfo->visible) {
589 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700590 bool isTouchModal = (flags &
591 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
592 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800594 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700595 if (portalToDisplayId != ADISPLAY_ID_NONE &&
596 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800597 if (addPortalWindows) {
598 // For the monitoring channels of the display.
599 mTempTouchState.addPortalWindow(windowHandle);
600 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700601 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
602 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800604 // Found window.
605 return windowHandle;
606 }
607 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800608
609 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700610 mTempTouchState.addOrUpdateWindow(windowHandle,
611 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
612 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800615 }
616 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700617 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618}
619
Garfield Tane84e6f92019-08-29 17:28:41 -0700620std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000621 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
622 std::vector<TouchedMonitor> touchedMonitors;
623
624 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
625 addGestureMonitors(monitors, touchedMonitors);
626 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
627 const InputWindowInfo* windowInfo = portalWindow->getInfo();
628 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700629 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
630 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000631 }
632 return touchedMonitors;
633}
634
635void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700636 std::vector<TouchedMonitor>& outTouchedMonitors,
637 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000638 if (monitors.empty()) {
639 return;
640 }
641 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
642 for (const Monitor& monitor : monitors) {
643 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
644 }
645}
646
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700647void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648 const char* reason;
649 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700650 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700652 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700654 reason = "inbound event was dropped because the policy consumed it";
655 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700656 case DropReason::DISABLED:
657 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700658 ALOGI("Dropped event because input dispatch is disabled.");
659 }
660 reason = "inbound event was dropped because input dispatch is disabled";
661 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700662 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700663 ALOGI("Dropped event because of pending overdue app switch.");
664 reason = "inbound event was dropped because of pending overdue app switch";
665 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700666 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700667 ALOGI("Dropped event because the current application is not responding and the user "
668 "has started interacting with a different application.");
669 reason = "inbound event was dropped because the current application is not responding "
670 "and the user has started interacting with a different application";
671 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700672 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700673 ALOGI("Dropped event because it is stale.");
674 reason = "inbound event was dropped because it is stale";
675 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700676 case DropReason::NOT_DROPPED: {
677 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700678 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700679 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 }
681
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700682 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700683 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
685 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700686 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800687 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700688 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700689 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
690 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700691 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
692 synthesizeCancelationEventsForAllConnectionsLocked(options);
693 } else {
694 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
695 synthesizeCancelationEventsForAllConnectionsLocked(options);
696 }
697 break;
698 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700699 case EventEntry::Type::CONFIGURATION_CHANGED:
700 case EventEntry::Type::DEVICE_RESET: {
701 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
702 break;
703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 }
705}
706
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800707static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700708 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
709 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710}
711
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700712bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
713 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
714 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
715 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716}
717
718bool InputDispatcher::isAppSwitchPendingLocked() {
719 return mAppSwitchDueTime != LONG_LONG_MAX;
720}
721
722void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
723 mAppSwitchDueTime = LONG_LONG_MAX;
724
725#if DEBUG_APP_SWITCH
726 if (handled) {
727 ALOGD("App switch has arrived.");
728 } else {
729 ALOGD("App switch was abandoned.");
730 }
731#endif
732}
733
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700734bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
735 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736}
737
738bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700739 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740}
741
742bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700743 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 return false;
745 }
746
747 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700748 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700749 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700751 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752
753 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700754 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 return true;
756}
757
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700758void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
759 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760}
761
762void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700763 while (!mInboundQueue.empty()) {
764 EventEntry* entry = mInboundQueue.front();
765 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 releaseInboundEventLocked(entry);
767 }
768 traceInboundQueueLengthLocked();
769}
770
771void InputDispatcher::releasePendingEventLocked() {
772 if (mPendingEvent) {
773 resetANRTimeoutsLocked();
774 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700775 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776 }
777}
778
779void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
780 InjectionState* injectionState = entry->injectionState;
781 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
782#if DEBUG_DISPATCH_CYCLE
783 ALOGD("Injected inbound event was dropped.");
784#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800785 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 }
787 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700788 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789 }
790 addRecentEventLocked(entry);
791 entry->release();
792}
793
794void InputDispatcher::resetKeyRepeatLocked() {
795 if (mKeyRepeatState.lastKeyEntry) {
796 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700797 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 }
799}
800
Garfield Tane84e6f92019-08-29 17:28:41 -0700801KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
803
804 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700805 uint32_t policyFlags = entry->policyFlags &
806 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807 if (entry->refCount == 1) {
808 entry->recycle();
809 entry->eventTime = currentTime;
810 entry->policyFlags = policyFlags;
811 entry->repeatCount += 1;
812 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700813 KeyEntry* newEntry =
814 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId,
815 entry->source, entry->displayId, policyFlags, entry->action,
816 entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
817 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818
819 mKeyRepeatState.lastKeyEntry = newEntry;
820 entry->release();
821
822 entry = newEntry;
823 }
824 entry->syntheticRepeat = true;
825
826 // Increment reference count since we keep a reference to the event in
827 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
828 entry->refCount += 1;
829
830 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
831 return entry;
832}
833
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700834bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
835 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700837 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838#endif
839
840 // Reset key repeating in case a keyboard device was added or removed or something.
841 resetKeyRepeatLocked();
842
843 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700844 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
845 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700847 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 return true;
849}
850
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700851bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700853 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700854 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855#endif
856
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 options.deviceId = entry->deviceId;
859 synthesizeCancelationEventsForAllConnectionsLocked(options);
860 return true;
861}
862
863bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700864 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700866 if (!entry->dispatchInProgress) {
867 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
868 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
869 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
870 if (mKeyRepeatState.lastKeyEntry &&
871 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872 // We have seen two identical key downs in a row which indicates that the device
873 // driver is automatically generating key repeats itself. We take note of the
874 // repeat here, but we disable our own next key repeat timer since it is clear that
875 // we will not need to synthesize key repeats ourselves.
876 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
877 resetKeyRepeatLocked();
878 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
879 } else {
880 // Not a repeat. Save key down state in case we do see a repeat later.
881 resetKeyRepeatLocked();
882 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
883 }
884 mKeyRepeatState.lastKeyEntry = entry;
885 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700886 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 resetKeyRepeatLocked();
888 }
889
890 if (entry->repeatCount == 1) {
891 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
892 } else {
893 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
894 }
895
896 entry->dispatchInProgress = true;
897
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700898 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 }
900
901 // Handle case where the policy asked us to try again later last time.
902 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
903 if (currentTime < entry->interceptKeyWakeupTime) {
904 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
905 *nextWakeupTime = entry->interceptKeyWakeupTime;
906 }
907 return false; // wait until next wakeup
908 }
909 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
910 entry->interceptKeyWakeupTime = 0;
911 }
912
913 // Give the policy a chance to intercept the key.
914 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
915 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700916 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -0700917 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800918 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700919 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +0800920 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700921 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 }
923 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700924 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 entry->refCount += 1;
926 return false; // wait for the command to run
927 } else {
928 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
929 }
930 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700931 if (*dropReason == DropReason::NOT_DROPPED) {
932 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 }
934 }
935
936 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700937 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700938 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700939 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700940 : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800941 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 return true;
943 }
944
945 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800946 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700947 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700948 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
950 return false;
951 }
952
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800953 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
955 return true;
956 }
957
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800958 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700959 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960
961 // Dispatch the key.
962 dispatchEventLocked(currentTime, entry, inputTargets);
963 return true;
964}
965
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700966void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100968 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700969 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
970 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700971 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
972 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
973 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974#endif
975}
976
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
978 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000979 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 entry->dispatchInProgress = true;
983
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700984 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985 }
986
987 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700988 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700990 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700991 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 return true;
993 }
994
995 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
996
997 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800998 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999
1000 bool conflictingPointerActions = false;
1001 int32_t injectionResult;
1002 if (isPointerEvent) {
1003 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001004 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001005 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001006 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 } else {
1008 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001009 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001010 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 }
1012 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1013 return false;
1014 }
1015
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001016 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001018 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001019 CancelationOptions::Mode mode(isPointerEvent
1020 ? CancelationOptions::CANCEL_POINTER_EVENTS
1021 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001022 CancelationOptions options(mode, "input event injection failed");
1023 synthesizeCancelationEventsForMonitorsLocked(options);
1024 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 return true;
1026 }
1027
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001028 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001029 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001031 if (isPointerEvent) {
1032 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
1033 if (stateIndex >= 0) {
1034 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001035 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001036 // The event has gone through these portal windows, so we add monitoring targets of
1037 // the corresponding displays as well.
1038 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001039 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001040 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001041 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001042 }
1043 }
1044 }
1045 }
1046
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 // Dispatch the motion.
1048 if (conflictingPointerActions) {
1049 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001050 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 synthesizeCancelationEventsForAllConnectionsLocked(options);
1052 }
1053 dispatchEventLocked(currentTime, entry, inputTargets);
1054 return true;
1055}
1056
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001057void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001059 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001060 ", policyFlags=0x%x, "
1061 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1062 "metaState=0x%x, buttonState=0x%x,"
1063 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001064 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1065 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1066 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001068 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070 "x=%f, y=%f, pressure=%f, size=%f, "
1071 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1072 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001073 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1074 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1075 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1076 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1077 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1078 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1079 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1080 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1081 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1082 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083 }
1084#endif
1085}
1086
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001087void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1088 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001089 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090#if DEBUG_DISPATCH_CYCLE
1091 ALOGD("dispatchEventToCurrentInputTargets");
1092#endif
1093
1094 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1095
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001096 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001098 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001099 sp<Connection> connection =
1100 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001101 if (connection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1103 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001104 if (DEBUG_FOCUS) {
1105 ALOGD("Dropping event delivery to target with channel '%s' because it "
1106 "is no longer registered with the input dispatcher.",
1107 inputTarget.inputChannel->getName().c_str());
1108 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109 }
1110 }
1111}
1112
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001113int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001114 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001116 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001117 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001119 if (DEBUG_FOCUS) {
1120 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1121 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1123 mInputTargetWaitStartTime = currentTime;
1124 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1125 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001126 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 }
1128 } else {
1129 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001130 if (DEBUG_FOCUS) {
1131 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
1132 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1133 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001134 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001135 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001137 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001138 timeout =
1139 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 } else {
1141 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1142 }
1143
1144 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1145 mInputTargetWaitStartTime = currentTime;
1146 mInputTargetWaitTimeoutTime = currentTime + timeout;
1147 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001148 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149
Yi Kong9b14ac62018-07-17 13:48:38 -07001150 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001151 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 }
Robert Carr740167f2018-10-11 19:03:41 -07001153 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1154 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 }
1156 }
1157 }
1158
1159 if (mInputTargetWaitTimeoutExpired) {
1160 return INPUT_EVENT_INJECTION_TIMED_OUT;
1161 }
1162
1163 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001164 onANRLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001165 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166
1167 // Force poll loop to wake up immediately on next iteration once we get the
1168 // ANR response back from the policy.
1169 *nextWakeupTime = LONG_LONG_MIN;
1170 return INPUT_EVENT_INJECTION_PENDING;
1171 } else {
1172 // Force poll loop to wake up when timeout is due.
1173 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1174 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1175 }
1176 return INPUT_EVENT_INJECTION_PENDING;
1177 }
1178}
1179
Robert Carr803535b2018-08-02 16:38:15 -07001180void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1181 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1182 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1183 state.removeWindowByToken(token);
1184 }
1185}
1186
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001187void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001188 nsecs_t newTimeout, const sp<IBinder>& inputConnectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 if (newTimeout > 0) {
1190 // Extend the timeout.
1191 mInputTargetWaitTimeoutTime = now() + newTimeout;
1192 } else {
1193 // Give up.
1194 mInputTargetWaitTimeoutExpired = true;
1195
1196 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001197 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001198 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001199 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001201 if (connection->status == Connection::STATUS_NORMAL) {
1202 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1203 "application not responding");
1204 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 }
1206 }
1207 }
1208}
1209
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1212 return currentTime - mInputTargetWaitStartTime;
1213 }
1214 return 0;
1215}
1216
1217void InputDispatcher::resetANRTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001218 if (DEBUG_FOCUS) {
1219 ALOGD("Resetting ANR timeouts.");
1220 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221
1222 // Reset input target wait timeout.
1223 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001224 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225}
1226
Tiger Huang721e26f2018-07-24 22:26:19 +08001227/**
1228 * Get the display id that the given event should go to. If this event specifies a valid display id,
1229 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1230 * Focused display is the display that the user most recently interacted with.
1231 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001232int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001233 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001234 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001235 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001236 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1237 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001238 break;
1239 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001240 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001241 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1242 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001243 break;
1244 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001245 case EventEntry::Type::CONFIGURATION_CHANGED:
1246 case EventEntry::Type::DEVICE_RESET: {
1247 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001248 return ADISPLAY_ID_NONE;
1249 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001250 }
1251 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1252}
1253
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001255 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001256 std::vector<InputTarget>& inputTargets,
1257 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001259 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260
Tiger Huang721e26f2018-07-24 22:26:19 +08001261 int32_t displayId = getTargetDisplayId(entry);
1262 sp<InputWindowHandle> focusedWindowHandle =
1263 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1264 sp<InputApplicationHandle> focusedApplicationHandle =
1265 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1266
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 // If there is no currently focused window and no focused application
1268 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001269 if (focusedWindowHandle == nullptr) {
1270 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001271 injectionResult =
1272 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1273 nullptr, nextWakeupTime,
1274 "Waiting because no window has focus but there is "
1275 "a focused application that may eventually add a "
1276 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 goto Unresponsive;
1278 }
1279
Arthur Hung3b413f22018-10-26 18:05:34 +08001280 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001281 "%" PRId32 ".",
1282 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1284 goto Failed;
1285 }
1286
1287 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001288 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1290 goto Failed;
1291 }
1292
Jeff Brownffb49772014-10-10 19:01:34 -07001293 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001294 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001295 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001296 injectionResult =
1297 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1298 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 goto Unresponsive;
1300 }
1301
1302 // Success! Output targets.
1303 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001304 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001305 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1306 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307
1308 // Done.
1309Failed:
1310Unresponsive:
1311 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001312 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001313 if (DEBUG_FOCUS) {
1314 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1315 "timeSpentWaitingForApplication=%0.1fms",
1316 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 return injectionResult;
1319}
1320
1321int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001322 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001323 std::vector<InputTarget>& inputTargets,
1324 nsecs_t* nextWakeupTime,
1325 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001326 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 enum InjectionPermission {
1328 INJECTION_PERMISSION_UNKNOWN,
1329 INJECTION_PERMISSION_GRANTED,
1330 INJECTION_PERMISSION_DENIED
1331 };
1332
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333 // For security reasons, we defer updating the touch state until we are sure that
1334 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001335 int32_t displayId = entry.displayId;
1336 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1338
1339 // Update the touch state as needed based on the properties of the touch event.
1340 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1341 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1342 sp<InputWindowHandle> newHoverWindowHandle;
1343
Jeff Brownf086ddb2014-02-11 14:28:48 -08001344 // Copy current touch state into mTempTouchState.
1345 // This state is always reset at the end of this function, so if we don't find state
1346 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001347 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001348 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1349 if (oldStateIndex >= 0) {
1350 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1351 mTempTouchState.copyFrom(*oldState);
1352 }
1353
1354 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001355 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001356 (mTempTouchState.deviceId != entry.deviceId || mTempTouchState.source != entry.source ||
1357 mTempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001358 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1359 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1360 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1361 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1362 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001363 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 bool wrongDevice = false;
1365 if (newGesture) {
1366 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001367 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001368 if (DEBUG_FOCUS) {
1369 ALOGD("Dropping event because a pointer for a different device is already down "
1370 "in display %" PRId32,
1371 displayId);
1372 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001373 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1375 switchedDevice = false;
1376 wrongDevice = true;
1377 goto Failed;
1378 }
1379 mTempTouchState.reset();
1380 mTempTouchState.down = down;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001381 mTempTouchState.deviceId = entry.deviceId;
1382 mTempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383 mTempTouchState.displayId = displayId;
1384 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001385 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001386 if (DEBUG_FOCUS) {
1387 ALOGI("Dropping move event because a pointer for a different device is already active "
1388 "in display %" PRId32,
1389 displayId);
1390 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001391 // TODO: test multiple simultaneous input streams.
1392 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1393 switchedDevice = false;
1394 wrongDevice = true;
1395 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396 }
1397
1398 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1399 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1400
Garfield Tan00f511d2019-06-12 16:55:40 -07001401 int32_t x;
1402 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001404 // Always dispatch mouse events to cursor position.
1405 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001406 x = int32_t(entry.xCursorPosition);
1407 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001408 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001409 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1410 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001411 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001412 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001413 sp<InputWindowHandle> newTouchedWindowHandle =
1414 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1415 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001416
1417 std::vector<TouchedMonitor> newGestureMonitors = isDown
1418 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1419 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001422 if (newTouchedWindowHandle != nullptr &&
1423 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001424 // New window supports splitting, but we should never split mouse events.
1425 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426 } else if (isSplit) {
1427 // New window does not support splitting but we have already split events.
1428 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001429 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430 }
1431
1432 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001433 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 // Try to assign the pointer to the first foreground window we find, if there is one.
1435 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001436 }
1437
1438 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1439 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001440 "(%d, %d) in display %" PRId32 ".",
1441 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001442 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1443 goto Failed;
1444 }
1445
1446 if (newTouchedWindowHandle != nullptr) {
1447 // Set target flags.
1448 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1449 if (isSplit) {
1450 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001452 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1453 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1454 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1455 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1456 }
1457
1458 // Update hover state.
1459 if (isHoverAction) {
1460 newHoverWindowHandle = newTouchedWindowHandle;
1461 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1462 newHoverWindowHandle = mLastHoverWindowHandle;
1463 }
1464
1465 // Update the temporary touch state.
1466 BitSet32 pointerIds;
1467 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001468 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001469 pointerIds.markBit(pointerId);
1470 }
1471 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 }
1473
Michael Wright3dd60e22019-03-27 22:06:44 +00001474 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 } else {
1476 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1477
1478 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001479 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001480 if (DEBUG_FOCUS) {
1481 ALOGD("Dropping event because the pointer is not down or we previously "
1482 "dropped the pointer down event in display %" PRId32,
1483 displayId);
1484 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1486 goto Failed;
1487 }
1488
1489 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001490 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001491 mTempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001492 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1493 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494
1495 sp<InputWindowHandle> oldTouchedWindowHandle =
1496 mTempTouchState.getFirstForegroundWindowHandle();
1497 sp<InputWindowHandle> newTouchedWindowHandle =
1498 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001499 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1500 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001501 if (DEBUG_FOCUS) {
1502 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1503 oldTouchedWindowHandle->getName().c_str(),
1504 newTouchedWindowHandle->getName().c_str(), displayId);
1505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 // Make a slippery exit from the old window.
1507 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001508 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1509 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510
1511 // Make a slippery entrance into the new window.
1512 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1513 isSplit = true;
1514 }
1515
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001516 int32_t targetFlags =
1517 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 if (isSplit) {
1519 targetFlags |= InputTarget::FLAG_SPLIT;
1520 }
1521 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1522 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1523 }
1524
1525 BitSet32 pointerIds;
1526 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001527 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528 }
1529 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1530 }
1531 }
1532 }
1533
1534 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1535 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001536 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537#if DEBUG_HOVER
1538 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001539 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540#endif
1541 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001542 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1543 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 }
1545
1546 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001547 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548#if DEBUG_HOVER
1549 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001550 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551#endif
1552 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001553 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1554 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 }
1556 }
1557
1558 // Check permission to inject into all touched foreground windows and ensure there
1559 // is at least one touched foreground window.
1560 {
1561 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001562 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1564 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001565 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1567 injectionPermission = INJECTION_PERMISSION_DENIED;
1568 goto Failed;
1569 }
1570 }
1571 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001572 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1573 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001574 if (DEBUG_FOCUS) {
1575 ALOGD("Dropping event because there is no touched foreground window in display "
1576 "%" PRId32 " or gesture monitor to receive it.",
1577 displayId);
1578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1580 goto Failed;
1581 }
1582
1583 // Permission granted to injection into all touched foreground windows.
1584 injectionPermission = INJECTION_PERMISSION_GRANTED;
1585 }
1586
1587 // Check whether windows listening for outside touches are owned by the same UID. If it is
1588 // set the policy flag that we will not reveal coordinate information to this window.
1589 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1590 sp<InputWindowHandle> foregroundWindowHandle =
1591 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001592 if (foregroundWindowHandle) {
1593 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1594 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1595 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1596 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1597 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1598 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001599 InputTarget::FLAG_ZERO_COORDS,
1600 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602 }
1603 }
1604 }
1605 }
1606
1607 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001608 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001610 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001611 std::string reason =
1612 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1613 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001614 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001615 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1616 touchedWindow.windowHandle,
1617 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618 goto Unresponsive;
1619 }
1620 }
1621 }
1622
1623 // If this is the first pointer going down and the touched window has a wallpaper
1624 // then also add the touched wallpaper windows so they are locked in for the duration
1625 // of the touch gesture.
1626 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1627 // engine only supports touch events. We would need to add a mechanism similar
1628 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1629 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1630 sp<InputWindowHandle> foregroundWindowHandle =
1631 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001632 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001633 const std::vector<sp<InputWindowHandle>> windowHandles =
1634 getWindowHandlesLocked(displayId);
1635 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001637 if (info->displayId == displayId &&
1638 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1639 mTempTouchState
1640 .addOrUpdateWindow(windowHandle,
1641 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1642 InputTarget::
1643 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1644 InputTarget::FLAG_DISPATCH_AS_IS,
1645 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 }
1647 }
1648 }
1649 }
1650
1651 // Success! Output targets.
1652 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1653
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001654 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001656 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 }
1658
Michael Wright3dd60e22019-03-27 22:06:44 +00001659 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1660 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001661 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001662 }
1663
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 // Drop the outside or hover touch windows since we will not care about them
1665 // in the next iteration.
1666 mTempTouchState.filterNonAsIsTouchWindows();
1667
1668Failed:
1669 // Check injection permission once and for all.
1670 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001671 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 injectionPermission = INJECTION_PERMISSION_GRANTED;
1673 } else {
1674 injectionPermission = INJECTION_PERMISSION_DENIED;
1675 }
1676 }
1677
1678 // Update final pieces of touch state if the injector had permission.
1679 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1680 if (!wrongDevice) {
1681 if (switchedDevice) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001682 if (DEBUG_FOCUS) {
1683 ALOGD("Conflicting pointer actions: Switched to a different device.");
1684 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 *outConflictingPointerActions = true;
1686 }
1687
1688 if (isHoverAction) {
1689 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001690 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001691 if (DEBUG_FOCUS) {
1692 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1693 "down.");
1694 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 *outConflictingPointerActions = true;
1696 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001697 mTempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001698 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1699 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001700 mTempTouchState.deviceId = entry.deviceId;
1701 mTempTouchState.source = entry.source;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001702 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001704 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1705 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001707 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1709 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001710 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001711 if (DEBUG_FOCUS) {
1712 ALOGD("Conflicting pointer actions: Down received while already down.");
1713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 *outConflictingPointerActions = true;
1715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1717 // One pointer went up.
1718 if (isSplit) {
1719 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001720 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001722 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001723 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1725 touchedWindow.pointerIds.clearBit(pointerId);
1726 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001727 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 continue;
1729 }
1730 }
1731 i += 1;
1732 }
1733 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001734 }
1735
1736 // Save changes unless the action was scroll in which case the temporary touch
1737 // state was only valid for this one action.
1738 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1739 if (mTempTouchState.displayId >= 0) {
1740 if (oldStateIndex >= 0) {
1741 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1742 } else {
1743 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1744 }
1745 } else if (oldStateIndex >= 0) {
1746 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 }
1749
1750 // Update hover state.
1751 mLastHoverWindowHandle = newHoverWindowHandle;
1752 }
1753 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001754 if (DEBUG_FOCUS) {
1755 ALOGD("Not updating touch focus because injection was denied.");
1756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 }
1758
1759Unresponsive:
1760 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1761 mTempTouchState.reset();
1762
1763 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001764 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001765 if (DEBUG_FOCUS) {
1766 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1767 "timeSpentWaitingForApplication=%0.1fms",
1768 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 return injectionResult;
1771}
1772
1773void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001774 int32_t targetFlags, BitSet32 pointerIds,
1775 std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001776 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1777 if (inputChannel == nullptr) {
1778 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1779 return;
1780 }
1781
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001783 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001784 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 target.flags = targetFlags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001786 target.xOffset = -windowInfo->frameLeft;
1787 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001788 target.globalScaleFactor = windowInfo->globalScaleFactor;
1789 target.windowXScale = windowInfo->windowXScale;
1790 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001792 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793}
1794
Michael Wright3dd60e22019-03-27 22:06:44 +00001795void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001796 int32_t displayId, float xOffset,
1797 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001798 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1799 mGlobalMonitorsByDisplay.find(displayId);
1800
1801 if (it != mGlobalMonitorsByDisplay.end()) {
1802 const std::vector<Monitor>& monitors = it->second;
1803 for (const Monitor& monitor : monitors) {
1804 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 }
1807}
1808
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001809void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1810 float yOffset,
1811 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001812 InputTarget target;
1813 target.inputChannel = monitor.inputChannel;
1814 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1815 target.xOffset = xOffset;
1816 target.yOffset = yOffset;
1817 target.pointerIds.clear();
1818 target.globalScaleFactor = 1.0f;
1819 inputTargets.push_back(target);
1820}
1821
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001823 const InjectionState* injectionState) {
1824 if (injectionState &&
1825 (windowHandle == nullptr ||
1826 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1827 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001828 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001830 "owned by uid %d",
1831 injectionState->injectorPid, injectionState->injectorUid,
1832 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 } else {
1834 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001835 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 }
1837 return false;
1838 }
1839 return true;
1840}
1841
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001842bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1843 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001845 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1846 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 if (otherHandle == windowHandle) {
1848 break;
1849 }
1850
1851 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001852 if (otherInfo->displayId == displayId && otherInfo->visible &&
1853 !otherInfo->isTrustedOverlay() && otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 return true;
1855 }
1856 }
1857 return false;
1858}
1859
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001860bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1861 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001862 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001863 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001864 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001865 if (otherHandle == windowHandle) {
1866 break;
1867 }
1868
1869 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001870 if (otherInfo->displayId == displayId && otherInfo->visible &&
1871 !otherInfo->isTrustedOverlay() && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001872 return true;
1873 }
1874 }
1875 return false;
1876}
1877
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001878std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
1879 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001880 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07001881 // If the window is paused then keep waiting.
1882 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001883 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001884 }
1885
1886 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001887 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001888 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001889 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001890 "registered with the input dispatcher. The window may be in the "
1891 "process of being removed.",
1892 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001893 }
1894
1895 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07001896 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001897 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001898 "The window may be in the process of being removed.",
1899 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07001900 }
1901
1902 // If the connection is backed up then keep waiting.
1903 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001904 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001905 "Outbound queue length: %zu. Wait queue length: %zu.",
1906 targetType, connection->outboundQueue.size(),
1907 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07001908 }
1909
1910 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001911 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07001912 // If the event is a key event, then we must wait for all previous events to
1913 // complete before delivering it because previous events may have the
1914 // side-effect of transferring focus to a different window and we want to
1915 // ensure that the following keys are sent to the new window.
1916 //
1917 // Suppose the user touches a button in a window then immediately presses "A".
1918 // If the button causes a pop-up window to appear then we want to ensure that
1919 // the "A" key is delivered to the new pop-up window. This is because users
1920 // often anticipate pending UI changes when typing on a keyboard.
1921 // To obtain this behavior, we must serialize key events with respect to all
1922 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001923 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001924 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001925 "finished processing all of the input events that were previously "
1926 "delivered to it. Outbound queue length: %zu. Wait queue length: "
1927 "%zu.",
1928 targetType, connection->outboundQueue.size(),
1929 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 }
Jeff Brownffb49772014-10-10 19:01:34 -07001931 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 // Touch events can always be sent to a window immediately because the user intended
1933 // to touch whatever was visible at the time. Even if focus changes or a new
1934 // window appears moments later, the touch event was meant to be delivered to
1935 // whatever window happened to be on screen at the time.
1936 //
1937 // Generic motion events, such as trackball or joystick events are a little trickier.
1938 // Like key events, generic motion events are delivered to the focused window.
1939 // Unlike key events, generic motion events don't tend to transfer focus to other
1940 // windows and it is not important for them to be serialized. So we prefer to deliver
1941 // generic motion events as soon as possible to improve efficiency and reduce lag
1942 // through batching.
1943 //
1944 // The one case where we pause input event delivery is when the wait queue is piling
1945 // up with lots of events because the application is not responding.
1946 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001947 if (!connection->waitQueue.empty() &&
1948 currentTime >=
1949 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001950 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001951 "finished processing certain input events that were delivered to "
1952 "it over "
1953 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
1954 "%0.1fms.",
1955 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1956 connection->waitQueue.size(),
1957 (currentTime - connection->waitQueue.front()->deliveryTime) *
1958 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 }
1960 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001961 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962}
1963
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001964std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 const sp<InputApplicationHandle>& applicationHandle,
1966 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001967 if (applicationHandle != nullptr) {
1968 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001969 std::string label(applicationHandle->getName());
1970 label += " - ";
1971 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 return label;
1973 } else {
1974 return applicationHandle->getName();
1975 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001976 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 return windowHandle->getName();
1978 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001979 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 }
1981}
1982
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001983void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001984 int32_t displayId = getTargetDisplayId(eventEntry);
1985 sp<InputWindowHandle> focusedWindowHandle =
1986 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1987 if (focusedWindowHandle != nullptr) {
1988 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1990#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001991 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992#endif
1993 return;
1994 }
1995 }
1996
1997 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001998 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001999 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002000 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2001 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002002 return;
2003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002005 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002006 eventType = USER_ACTIVITY_EVENT_TOUCH;
2007 }
2008 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002010 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002011 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2012 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002013 return;
2014 }
2015 eventType = USER_ACTIVITY_EVENT_BUTTON;
2016 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002018 case EventEntry::Type::CONFIGURATION_CHANGED:
2019 case EventEntry::Type::DEVICE_RESET: {
2020 LOG_ALWAYS_FATAL("%s events are not user activity",
2021 EventEntry::typeToString(eventEntry.type));
2022 break;
2023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 }
2025
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002026 std::unique_ptr<CommandEntry> commandEntry =
2027 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002028 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002030 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031}
2032
2033void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002034 const sp<Connection>& connection,
2035 EventEntry* eventEntry,
2036 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002037 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002038 std::string message =
2039 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
2040 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002041 ATRACE_NAME(message.c_str());
2042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043#if DEBUG_DISPATCH_CYCLE
2044 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002045 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
2046 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
2047 connection->getInputChannelName().c_str(), inputTarget->flags, inputTarget->xOffset,
2048 inputTarget->yOffset, inputTarget->globalScaleFactor, inputTarget->windowXScale,
2049 inputTarget->windowYScale, inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050#endif
2051
2052 // Skip this event if the connection status is not normal.
2053 // We don't want to enqueue additional outbound events if the connection is broken.
2054 if (connection->status != Connection::STATUS_NORMAL) {
2055#if DEBUG_DISPATCH_CYCLE
2056 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002057 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058#endif
2059 return;
2060 }
2061
2062 // Split a motion event if needed.
2063 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002064 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002066 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
2067 if (inputTarget->pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002068 MotionEntry* splitMotionEntry =
2069 splitMotionEvent(originalMotionEntry, inputTarget->pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 if (!splitMotionEntry) {
2071 return; // split event was dropped
2072 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002073 if (DEBUG_FOCUS) {
2074 ALOGD("channel '%s' ~ Split motion event.",
2075 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002076 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002077 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002078 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 splitMotionEntry->release();
2080 return;
2081 }
2082 }
2083
2084 // Not splitting. Enqueue dispatch entries for the event as is.
2085 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2086}
2087
2088void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002089 const sp<Connection>& connection,
2090 EventEntry* eventEntry,
2091 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002092 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002093 std::string message =
2094 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32
2095 ")",
2096 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002097 ATRACE_NAME(message.c_str());
2098 }
2099
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002100 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101
2102 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002103 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002104 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002105 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002106 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002107 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002108 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002109 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002110 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002111 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002112 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002113 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002114 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115
2116 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002117 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118 startDispatchCycleLocked(currentTime, connection);
2119 }
2120}
2121
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002122void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2123 EventEntry* eventEntry,
2124 const InputTarget* inputTarget,
2125 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002126 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002127 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2128 connection->getInputChannelName().c_str(),
2129 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002130 ATRACE_NAME(message.c_str());
2131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 int32_t inputTargetFlags = inputTarget->flags;
2133 if (!(inputTargetFlags & dispatchMode)) {
2134 return;
2135 }
2136 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2137
2138 // This is a new event.
2139 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002140 DispatchEntry* dispatchEntry =
2141 new DispatchEntry(eventEntry, // increments ref
2142 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
2143 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2144 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145
2146 // Apply target flags and update the connection's input state.
2147 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002148 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002149 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
2150 dispatchEntry->resolvedAction = keyEntry.action;
2151 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002153 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2154 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002156 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2157 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002159 delete dispatchEntry;
2160 return; // skip the inconsistent event
2161 }
2162 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002165 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002166 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002167 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2168 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2169 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2170 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2171 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2172 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2173 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2174 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2175 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2176 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2177 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002178 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002179 }
2180 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002181 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2182 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002184 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2185 "event",
2186 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002188 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2189 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002191 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002192 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2193 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2194 }
2195 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2196 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2197 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002199 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2200 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002202 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2203 "event",
2204 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002206 delete dispatchEntry;
2207 return; // skip the inconsistent event
2208 }
2209
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002210 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002211 inputTarget->inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002212
2213 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002215 case EventEntry::Type::CONFIGURATION_CHANGED:
2216 case EventEntry::Type::DEVICE_RESET: {
2217 LOG_ALWAYS_FATAL("%s events should not go to apps",
2218 EventEntry::typeToString(eventEntry->type));
2219 break;
2220 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 }
2222
2223 // Remember that we are waiting for this dispatch to complete.
2224 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002225 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 }
2227
2228 // Enqueue the dispatch entry.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002229 connection->outboundQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002230 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002231}
2232
chaviwfd6d3512019-03-25 13:23:49 -07002233void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002234 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002235 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002236 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2237 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002238 return;
2239 }
2240
2241 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2242 if (inputWindowHandle == nullptr) {
2243 return;
2244 }
2245
chaviw8c9cf542019-03-25 13:02:48 -07002246 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002247 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002248
2249 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2250
2251 if (!hasFocusChanged) {
2252 return;
2253 }
2254
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002255 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2256 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002257 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002258 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259}
2260
2261void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002262 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002263 if (ATRACE_ENABLED()) {
2264 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002265 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002266 ATRACE_NAME(message.c_str());
2267 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002269 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270#endif
2271
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002272 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2273 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 dispatchEntry->deliveryTime = currentTime;
2275
2276 // Publish the event.
2277 status_t status;
2278 EventEntry* eventEntry = dispatchEntry->eventEntry;
2279 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002280 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002281 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002283 // Publish the key event.
2284 status = connection->inputPublisher
2285 .publishKeyEvent(dispatchEntry->seq, keyEntry->deviceId,
2286 keyEntry->source, keyEntry->displayId,
2287 dispatchEntry->resolvedAction,
2288 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2289 keyEntry->scanCode, keyEntry->metaState,
2290 keyEntry->repeatCount, keyEntry->downTime,
2291 keyEntry->eventTime);
2292 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 }
2294
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002295 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002296 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002298 PointerCoords scaledCoords[MAX_POINTERS];
2299 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2300
2301 // Set the X and Y offset depending on the input source.
2302 float xOffset, yOffset;
2303 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2304 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2305 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2306 float wxs = dispatchEntry->windowXScale;
2307 float wys = dispatchEntry->windowYScale;
2308 xOffset = dispatchEntry->xOffset * wxs;
2309 yOffset = dispatchEntry->yOffset * wys;
2310 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
2311 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2312 scaledCoords[i] = motionEntry->pointerCoords[i];
2313 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
2314 }
2315 usingCoords = scaledCoords;
2316 }
2317 } else {
2318 xOffset = 0.0f;
2319 yOffset = 0.0f;
2320
2321 // We don't want the dispatch target to know.
2322 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2323 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2324 scaledCoords[i].clear();
2325 }
2326 usingCoords = scaledCoords;
2327 }
2328 }
2329
2330 // Publish the motion event.
2331 status = connection->inputPublisher
2332 .publishMotionEvent(dispatchEntry->seq, motionEntry->deviceId,
2333 motionEntry->source, motionEntry->displayId,
2334 dispatchEntry->resolvedAction,
2335 motionEntry->actionButton,
2336 dispatchEntry->resolvedFlags,
2337 motionEntry->edgeFlags, motionEntry->metaState,
2338 motionEntry->buttonState,
2339 motionEntry->classification, xOffset, yOffset,
2340 motionEntry->xPrecision,
2341 motionEntry->yPrecision,
2342 motionEntry->xCursorPosition,
2343 motionEntry->yCursorPosition,
2344 motionEntry->downTime, motionEntry->eventTime,
2345 motionEntry->pointerCount,
2346 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002347 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002348 break;
2349 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002350 case EventEntry::Type::CONFIGURATION_CHANGED:
2351 case EventEntry::Type::DEVICE_RESET: {
2352 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2353 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002354 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
2357
2358 // Check the result.
2359 if (status) {
2360 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002361 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002363 "This is unexpected because the wait queue is empty, so the pipe "
2364 "should be empty and we shouldn't have any problems writing an "
2365 "event to it, status=%d",
2366 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2368 } else {
2369 // Pipe is full and we are waiting for the app to finish process some events
2370 // before sending more events to it.
2371#if DEBUG_DISPATCH_CYCLE
2372 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002373 "waiting for the application to catch up",
2374 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375#endif
2376 connection->inputPublisherBlocked = true;
2377 }
2378 } else {
2379 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002380 "status=%d",
2381 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2383 }
2384 return;
2385 }
2386
2387 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002388 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2389 connection->outboundQueue.end(),
2390 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002391 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002392 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002393 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 }
2395}
2396
2397void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002398 const sp<Connection>& connection, uint32_t seq,
2399 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400#if DEBUG_DISPATCH_CYCLE
2401 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002402 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403#endif
2404
2405 connection->inputPublisherBlocked = false;
2406
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002407 if (connection->status == Connection::STATUS_BROKEN ||
2408 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 return;
2410 }
2411
2412 // Notify other system components and prepare to start the next dispatch cycle.
2413 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2414}
2415
2416void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002417 const sp<Connection>& connection,
2418 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419#if DEBUG_DISPATCH_CYCLE
2420 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002421 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422#endif
2423
2424 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002425 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002426 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002427 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002428 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429
2430 // The connection appears to be unrecoverably broken.
2431 // Ignore already broken or zombie connections.
2432 if (connection->status == Connection::STATUS_NORMAL) {
2433 connection->status = Connection::STATUS_BROKEN;
2434
2435 if (notify) {
2436 // Notify other system components.
2437 onDispatchCycleBrokenLocked(currentTime, connection);
2438 }
2439 }
2440}
2441
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002442void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2443 while (!queue.empty()) {
2444 DispatchEntry* dispatchEntry = queue.front();
2445 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002446 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 }
2448}
2449
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002450void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002452 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 }
2454 delete dispatchEntry;
2455}
2456
2457int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2458 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2459
2460 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002461 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002463 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002465 "fd=%d, events=0x%x",
2466 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 return 0; // remove the callback
2468 }
2469
2470 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002471 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2473 if (!(events & ALOOPER_EVENT_INPUT)) {
2474 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002475 "events=0x%x",
2476 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477 return 1;
2478 }
2479
2480 nsecs_t currentTime = now();
2481 bool gotOne = false;
2482 status_t status;
2483 for (;;) {
2484 uint32_t seq;
2485 bool handled;
2486 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2487 if (status) {
2488 break;
2489 }
2490 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2491 gotOne = true;
2492 }
2493 if (gotOne) {
2494 d->runCommandsLockedInterruptible();
2495 if (status == WOULD_BLOCK) {
2496 return 1;
2497 }
2498 }
2499
2500 notify = status != DEAD_OBJECT || !connection->monitor;
2501 if (notify) {
2502 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002503 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 }
2505 } else {
2506 // Monitor channels are never explicitly unregistered.
2507 // We do it automatically when the remote endpoint is closed so don't warn
2508 // about them.
2509 notify = !connection->monitor;
2510 if (notify) {
2511 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002512 "events=0x%x",
2513 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514 }
2515 }
2516
2517 // Unregister the channel.
2518 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2519 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002520 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521}
2522
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002523void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002524 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002525 for (const auto& pair : mConnectionsByFd) {
2526 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527 }
2528}
2529
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002530void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002531 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002532 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2533 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2534}
2535
2536void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2537 const CancelationOptions& options,
2538 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2539 for (const auto& it : monitorsByDisplay) {
2540 const std::vector<Monitor>& monitors = it.second;
2541 for (const Monitor& monitor : monitors) {
2542 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002543 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002544 }
2545}
2546
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2548 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002549 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002550 if (connection == nullptr) {
2551 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002553
2554 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555}
2556
2557void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2558 const sp<Connection>& connection, const CancelationOptions& options) {
2559 if (connection->status == Connection::STATUS_BROKEN) {
2560 return;
2561 }
2562
2563 nsecs_t currentTime = now();
2564
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002565 std::vector<EventEntry*> cancelationEvents =
2566 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002568 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002570 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002571 "with reality: %s, mode=%d.",
2572 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2573 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574#endif
2575 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002576 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577 switch (cancelationEventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002578 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002579 logOutboundKeyDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002580 static_cast<const KeyEntry&>(*cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002581 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002582 }
2583 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002584 logOutboundMotionDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002585 static_cast<const MotionEntry&>(
2586 *cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002587 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002588 }
2589 case EventEntry::Type::CONFIGURATION_CHANGED:
2590 case EventEntry::Type::DEVICE_RESET: {
2591 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2592 EventEntry::typeToString(cancelationEventEntry->type));
2593 break;
2594 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595 }
2596
2597 InputTarget target;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002598 sp<InputWindowHandle> windowHandle =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002599 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002600 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2602 target.xOffset = -windowInfo->frameLeft;
2603 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002604 target.globalScaleFactor = windowInfo->globalScaleFactor;
2605 target.windowXScale = windowInfo->windowXScale;
2606 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 } else {
2608 target.xOffset = 0;
2609 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002610 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002611 }
2612 target.inputChannel = connection->inputChannel;
2613 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2614
chaviw8c9cf542019-03-25 13:02:48 -07002615 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002616 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617
2618 cancelationEventEntry->release();
2619 }
2620
2621 startDispatchCycleLocked(currentTime, connection);
2622 }
2623}
2624
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002625MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002626 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627 ALOG_ASSERT(pointerIds.value != 0);
2628
2629 uint32_t splitPointerIndexMap[MAX_POINTERS];
2630 PointerProperties splitPointerProperties[MAX_POINTERS];
2631 PointerCoords splitPointerCoords[MAX_POINTERS];
2632
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002633 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634 uint32_t splitPointerCount = 0;
2635
2636 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002637 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002639 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002640 uint32_t pointerId = uint32_t(pointerProperties.id);
2641 if (pointerIds.hasBit(pointerId)) {
2642 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2643 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2644 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002645 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 splitPointerCount += 1;
2647 }
2648 }
2649
2650 if (splitPointerCount != pointerIds.count()) {
2651 // This is bad. We are missing some of the pointers that we expected to deliver.
2652 // Most likely this indicates that we received an ACTION_MOVE events that has
2653 // different pointer ids than we expected based on the previous ACTION_DOWN
2654 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2655 // in this way.
2656 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002657 "we expected there to be %d pointers. This probably means we received "
2658 "a broken sequence of pointer ids from the input device.",
2659 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002660 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661 }
2662
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002663 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002665 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2666 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2668 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002669 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 uint32_t pointerId = uint32_t(pointerProperties.id);
2671 if (pointerIds.hasBit(pointerId)) {
2672 if (pointerIds.count() == 1) {
2673 // The first/last pointer went down/up.
2674 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002675 ? AMOTION_EVENT_ACTION_DOWN
2676 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677 } else {
2678 // A secondary pointer went down/up.
2679 uint32_t splitPointerIndex = 0;
2680 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2681 splitPointerIndex += 1;
2682 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002683 action = maskedAction |
2684 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 }
2686 } else {
2687 // An unrelated pointer changed.
2688 action = AMOTION_EVENT_ACTION_MOVE;
2689 }
2690 }
2691
Garfield Tan00f511d2019-06-12 16:55:40 -07002692 MotionEntry* splitMotionEntry =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002693 new MotionEntry(originalMotionEntry.sequenceNum, originalMotionEntry.eventTime,
2694 originalMotionEntry.deviceId, originalMotionEntry.source,
2695 originalMotionEntry.displayId, originalMotionEntry.policyFlags, action,
2696 originalMotionEntry.actionButton, originalMotionEntry.flags,
2697 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2698 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2699 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2700 originalMotionEntry.xCursorPosition,
2701 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002702 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002704 if (originalMotionEntry.injectionState) {
2705 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 splitMotionEntry->injectionState->refCount += 1;
2707 }
2708
2709 return splitMotionEntry;
2710}
2711
2712void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2713#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002714 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715#endif
2716
2717 bool needWake;
2718 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002719 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720
Prabir Pradhan42611e02018-11-27 14:04:02 -08002721 ConfigurationChangedEntry* newEntry =
2722 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723 needWake = enqueueInboundEventLocked(newEntry);
2724 } // release lock
2725
2726 if (needWake) {
2727 mLooper->wake();
2728 }
2729}
2730
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002731/**
2732 * If one of the meta shortcuts is detected, process them here:
2733 * Meta + Backspace -> generate BACK
2734 * Meta + Enter -> generate HOME
2735 * This will potentially overwrite keyCode and metaState.
2736 */
2737void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002738 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002739 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2740 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2741 if (keyCode == AKEYCODE_DEL) {
2742 newKeyCode = AKEYCODE_BACK;
2743 } else if (keyCode == AKEYCODE_ENTER) {
2744 newKeyCode = AKEYCODE_HOME;
2745 }
2746 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002747 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002748 struct KeyReplacement replacement = {keyCode, deviceId};
2749 mReplacedKeys.add(replacement, newKeyCode);
2750 keyCode = newKeyCode;
2751 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2752 }
2753 } else if (action == AKEY_EVENT_ACTION_UP) {
2754 // In order to maintain a consistent stream of up and down events, check to see if the key
2755 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2756 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002757 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002758 struct KeyReplacement replacement = {keyCode, deviceId};
2759 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2760 if (index >= 0) {
2761 keyCode = mReplacedKeys.valueAt(index);
2762 mReplacedKeys.removeItemsAt(index);
2763 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2764 }
2765 }
2766}
2767
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2769#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002770 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2771 "policyFlags=0x%x, action=0x%x, "
2772 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2773 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2774 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2775 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776#endif
2777 if (!validateKeyEvent(args->action)) {
2778 return;
2779 }
2780
2781 uint32_t policyFlags = args->policyFlags;
2782 int32_t flags = args->flags;
2783 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002784 // InputDispatcher tracks and generates key repeats on behalf of
2785 // whatever notifies it, so repeatCount should always be set to 0
2786 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2788 policyFlags |= POLICY_FLAG_VIRTUAL;
2789 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791 if (policyFlags & POLICY_FLAG_FUNCTION) {
2792 metaState |= AMETA_FUNCTION_ON;
2793 }
2794
2795 policyFlags |= POLICY_FLAG_TRUSTED;
2796
Michael Wright78f24442014-08-06 15:55:28 -07002797 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002798 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002799
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800 KeyEvent event;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002801 event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2802 args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803
Michael Wright2b3c3302018-03-02 17:19:13 +00002804 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002806 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2807 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002808 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811 bool needWake;
2812 { // acquire lock
2813 mLock.lock();
2814
2815 if (shouldSendKeyToInputFilterLocked(args)) {
2816 mLock.unlock();
2817
2818 policyFlags |= POLICY_FLAG_FILTERED;
2819 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2820 return; // event was consumed by the filter
2821 }
2822
2823 mLock.lock();
2824 }
2825
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002826 KeyEntry* newEntry =
2827 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2828 args->displayId, policyFlags, args->action, flags, keyCode,
2829 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830
2831 needWake = enqueueInboundEventLocked(newEntry);
2832 mLock.unlock();
2833 } // release lock
2834
2835 if (needWake) {
2836 mLooper->wake();
2837 }
2838}
2839
2840bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2841 return mInputFilterEnabled;
2842}
2843
2844void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2845#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002846 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan00f511d2019-06-12 16:55:40 -07002847 ", policyFlags=0x%x, "
2848 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
2849 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07002850 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan00f511d2019-06-12 16:55:40 -07002851 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2852 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Jaewan Kim372fbe42019-10-02 10:58:46 +09002853 args->edgeFlags, args->xPrecision, args->yPrecision, args->xCursorPosition,
Garfield Tan00f511d2019-06-12 16:55:40 -07002854 args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855 for (uint32_t i = 0; i < args->pointerCount; i++) {
2856 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002857 "x=%f, y=%f, pressure=%f, size=%f, "
2858 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2859 "orientation=%f",
2860 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2861 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2862 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2863 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2864 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2865 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2866 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2867 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2868 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2869 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870 }
2871#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002872 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2873 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874 return;
2875 }
2876
2877 uint32_t policyFlags = args->policyFlags;
2878 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002879
2880 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002881 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002882 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2883 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002884 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002885 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886
2887 bool needWake;
2888 { // acquire lock
2889 mLock.lock();
2890
2891 if (shouldSendMotionToInputFilterLocked(args)) {
2892 mLock.unlock();
2893
2894 MotionEvent event;
Garfield Tan00f511d2019-06-12 16:55:40 -07002895 event.initialize(args->deviceId, args->source, args->displayId, args->action,
2896 args->actionButton, args->flags, args->edgeFlags, args->metaState,
2897 args->buttonState, args->classification, 0, 0, args->xPrecision,
2898 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2899 args->downTime, args->eventTime, args->pointerCount,
2900 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901
2902 policyFlags |= POLICY_FLAG_FILTERED;
2903 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2904 return; // event was consumed by the filter
2905 }
2906
2907 mLock.lock();
2908 }
2909
2910 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07002911 MotionEntry* newEntry =
2912 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2913 args->displayId, policyFlags, args->action, args->actionButton,
2914 args->flags, args->metaState, args->buttonState,
2915 args->classification, args->edgeFlags, args->xPrecision,
2916 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2917 args->downTime, args->pointerCount, args->pointerProperties,
2918 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919
2920 needWake = enqueueInboundEventLocked(newEntry);
2921 mLock.unlock();
2922 } // release lock
2923
2924 if (needWake) {
2925 mLooper->wake();
2926 }
2927}
2928
2929bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002930 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931}
2932
2933void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2934#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002935 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002936 "switchMask=0x%08x",
2937 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938#endif
2939
2940 uint32_t policyFlags = args->policyFlags;
2941 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002942 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943}
2944
2945void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2946#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002947 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
2948 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949#endif
2950
2951 bool needWake;
2952 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002953 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954
Prabir Pradhan42611e02018-11-27 14:04:02 -08002955 DeviceResetEntry* newEntry =
2956 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957 needWake = enqueueInboundEventLocked(newEntry);
2958 } // release lock
2959
2960 if (needWake) {
2961 mLooper->wake();
2962 }
2963}
2964
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002965int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
2966 int32_t injectorUid, int32_t syncMode,
2967 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968#if DEBUG_INBOUND_EVENT_DETAILS
2969 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002970 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2971 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972#endif
2973
2974 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2975
2976 policyFlags |= POLICY_FLAG_INJECTED;
2977 if (hasInjectionPermission(injectorPid, injectorUid)) {
2978 policyFlags |= POLICY_FLAG_TRUSTED;
2979 }
2980
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07002981 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002982 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 case AINPUT_EVENT_TYPE_KEY: {
2984 KeyEvent keyEvent;
2985 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2986 int32_t action = keyEvent.getAction();
2987 if (!validateKeyEvent(action)) {
2988 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002990
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002991 int32_t flags = keyEvent.getFlags();
2992 int32_t keyCode = keyEvent.getKeyCode();
2993 int32_t metaState = keyEvent.getMetaState();
2994 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2995 /*byref*/ keyCode, /*byref*/ metaState);
2996 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
2997 keyEvent.getDisplayId(), action, flags, keyCode,
2998 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
2999 keyEvent.getDownTime(), keyEvent.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003001 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3002 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003003 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003004
3005 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3006 android::base::Timer t;
3007 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3008 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3009 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3010 std::to_string(t.duration().count()).c_str());
3011 }
3012 }
3013
3014 mLock.lock();
3015 KeyEntry* injectedEntry =
3016 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
3017 keyEvent.getDeviceId(), keyEvent.getSource(),
3018 keyEvent.getDisplayId(), policyFlags, action, flags,
3019 keyEvent.getKeyCode(), keyEvent.getScanCode(),
3020 keyEvent.getMetaState(), keyEvent.getRepeatCount(),
3021 keyEvent.getDownTime());
3022 injectedEntries.push(injectedEntry);
3023 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024 }
3025
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003026 case AINPUT_EVENT_TYPE_MOTION: {
3027 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3028 int32_t action = motionEvent->getAction();
3029 size_t pointerCount = motionEvent->getPointerCount();
3030 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3031 int32_t actionButton = motionEvent->getActionButton();
3032 int32_t displayId = motionEvent->getDisplayId();
3033 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3034 return INPUT_EVENT_INJECTION_FAILED;
3035 }
3036
3037 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3038 nsecs_t eventTime = motionEvent->getEventTime();
3039 android::base::Timer t;
3040 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3041 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3042 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3043 std::to_string(t.duration().count()).c_str());
3044 }
3045 }
3046
3047 mLock.lock();
3048 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3049 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3050 MotionEntry* injectedEntry =
Garfield Tan00f511d2019-06-12 16:55:40 -07003051 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3052 motionEvent->getDeviceId(), motionEvent->getSource(),
3053 motionEvent->getDisplayId(), policyFlags, action, actionButton,
3054 motionEvent->getFlags(), motionEvent->getMetaState(),
3055 motionEvent->getButtonState(), motionEvent->getClassification(),
3056 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3057 motionEvent->getYPrecision(),
3058 motionEvent->getRawXCursorPosition(),
3059 motionEvent->getRawYCursorPosition(),
3060 motionEvent->getDownTime(), uint32_t(pointerCount),
3061 pointerProperties, samplePointerCoords,
3062 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003063 injectedEntries.push(injectedEntry);
3064 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3065 sampleEventTimes += 1;
3066 samplePointerCoords += pointerCount;
3067 MotionEntry* nextInjectedEntry =
3068 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3069 motionEvent->getDeviceId(), motionEvent->getSource(),
3070 motionEvent->getDisplayId(), policyFlags, action,
3071 actionButton, motionEvent->getFlags(),
3072 motionEvent->getMetaState(), motionEvent->getButtonState(),
3073 motionEvent->getClassification(),
3074 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3075 motionEvent->getYPrecision(),
3076 motionEvent->getRawXCursorPosition(),
3077 motionEvent->getRawYCursorPosition(),
3078 motionEvent->getDownTime(), uint32_t(pointerCount),
3079 pointerProperties, samplePointerCoords,
3080 motionEvent->getXOffset(), motionEvent->getYOffset());
3081 injectedEntries.push(nextInjectedEntry);
3082 }
3083 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003087 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089 }
3090
3091 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3092 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3093 injectionState->injectionIsAsync = true;
3094 }
3095
3096 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003097 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098
3099 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003100 while (!injectedEntries.empty()) {
3101 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3102 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 }
3104
3105 mLock.unlock();
3106
3107 if (needWake) {
3108 mLooper->wake();
3109 }
3110
3111 int32_t injectionResult;
3112 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003113 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114
3115 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3116 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3117 } else {
3118 for (;;) {
3119 injectionResult = injectionState->injectionResult;
3120 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3121 break;
3122 }
3123
3124 nsecs_t remainingTimeout = endTime - now();
3125 if (remainingTimeout <= 0) {
3126#if DEBUG_INJECTION
3127 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003128 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129#endif
3130 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3131 break;
3132 }
3133
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003134 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135 }
3136
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003137 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3138 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139 while (injectionState->pendingForegroundDispatches != 0) {
3140#if DEBUG_INJECTION
3141 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003142 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143#endif
3144 nsecs_t remainingTimeout = endTime - now();
3145 if (remainingTimeout <= 0) {
3146#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003147 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3148 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149#endif
3150 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3151 break;
3152 }
3153
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003154 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155 }
3156 }
3157 }
3158
3159 injectionState->release();
3160 } // release lock
3161
3162#if DEBUG_INJECTION
3163 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003164 "injectorPid=%d, injectorUid=%d",
3165 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166#endif
3167
3168 return injectionResult;
3169}
3170
3171bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003172 return injectorUid == 0 ||
3173 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174}
3175
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003176void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 InjectionState* injectionState = entry->injectionState;
3178 if (injectionState) {
3179#if DEBUG_INJECTION
3180 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003181 "injectorPid=%d, injectorUid=%d",
3182 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183#endif
3184
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003185 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 // Log the outcome since the injector did not wait for the injection result.
3187 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003188 case INPUT_EVENT_INJECTION_SUCCEEDED:
3189 ALOGV("Asynchronous input event injection succeeded.");
3190 break;
3191 case INPUT_EVENT_INJECTION_FAILED:
3192 ALOGW("Asynchronous input event injection failed.");
3193 break;
3194 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3195 ALOGW("Asynchronous input event injection permission denied.");
3196 break;
3197 case INPUT_EVENT_INJECTION_TIMED_OUT:
3198 ALOGW("Asynchronous input event injection timed out.");
3199 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200 }
3201 }
3202
3203 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003204 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 }
3206}
3207
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003208void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 InjectionState* injectionState = entry->injectionState;
3210 if (injectionState) {
3211 injectionState->pendingForegroundDispatches += 1;
3212 }
3213}
3214
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003215void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 InjectionState* injectionState = entry->injectionState;
3217 if (injectionState) {
3218 injectionState->pendingForegroundDispatches -= 1;
3219
3220 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003221 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 }
3223 }
3224}
3225
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003226std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3227 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003228 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003229}
3230
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003232 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003233 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003234 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3235 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003236 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003237 return windowHandle;
3238 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 }
3240 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003241 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242}
3243
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003244bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003245 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003246 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3247 for (const sp<InputWindowHandle>& handle : windowHandles) {
3248 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003249 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003250 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003251 ", but it should belong to display %" PRId32,
3252 windowHandle->getName().c_str(), it.first,
3253 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003254 }
3255 return true;
3256 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257 }
3258 }
3259 return false;
3260}
3261
Robert Carr5c8a0262018-10-03 16:30:44 -07003262sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3263 size_t count = mInputChannelsByToken.count(token);
3264 if (count == 0) {
3265 return nullptr;
3266 }
3267 return mInputChannelsByToken.at(token);
3268}
3269
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003270void InputDispatcher::updateWindowHandlesForDisplayLocked(
3271 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3272 if (inputWindowHandles.empty()) {
3273 // Remove all handles on a display if there are no windows left.
3274 mWindowHandlesByDisplay.erase(displayId);
3275 return;
3276 }
3277
3278 // Since we compare the pointer of input window handles across window updates, we need
3279 // to make sure the handle object for the same window stays unchanged across updates.
3280 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
3281 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3282 for (const sp<InputWindowHandle>& handle : oldHandles) {
3283 oldHandlesByTokens[handle->getToken()] = handle;
3284 }
3285
3286 std::vector<sp<InputWindowHandle>> newHandles;
3287 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3288 if (!handle->updateInfo()) {
3289 // handle no longer valid
3290 continue;
3291 }
3292
3293 const InputWindowInfo* info = handle->getInfo();
3294 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3295 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3296 const bool noInputChannel =
3297 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3298 const bool canReceiveInput =
3299 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3300 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3301 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003302 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003303 handle->getName().c_str());
3304 }
3305 continue;
3306 }
3307
3308 if (info->displayId != displayId) {
3309 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3310 handle->getName().c_str(), displayId, info->displayId);
3311 continue;
3312 }
3313
3314 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3315 const sp<InputWindowHandle> oldHandle = oldHandlesByTokens.at(handle->getToken());
3316 oldHandle->updateFrom(handle);
3317 newHandles.push_back(oldHandle);
3318 } else {
3319 newHandles.push_back(handle);
3320 }
3321 }
3322
3323 // Insert or replace
3324 mWindowHandlesByDisplay[displayId] = newHandles;
3325}
3326
Arthur Hungb92218b2018-08-14 12:00:21 +08003327/**
3328 * Called from InputManagerService, update window handle list by displayId that can receive input.
3329 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3330 * If set an empty list, remove all handles from the specific display.
3331 * For focused handle, check if need to change and send a cancel event to previous one.
3332 * For removed handle, check if need to send a cancel event if already in touch.
3333 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003334void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003335 int32_t displayId,
3336 const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003337 if (DEBUG_FOCUS) {
3338 std::string windowList;
3339 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3340 windowList += iwh->getName() + " ";
3341 }
3342 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003345 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346
Arthur Hungb92218b2018-08-14 12:00:21 +08003347 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003348 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3349 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003351 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
3352
Tiger Huang721e26f2018-07-24 22:26:19 +08003353 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354 bool foundHoveredWindow = false;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003355 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3356 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3357 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3358 windowHandle->getInfo()->visible) {
3359 newFocusedWindowHandle = windowHandle;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003360 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003361 if (windowHandle == mLastHoverWindowHandle) {
3362 foundHoveredWindow = true;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364 }
3365
3366 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003367 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 }
3369
Tiger Huang721e26f2018-07-24 22:26:19 +08003370 sp<InputWindowHandle> oldFocusedWindowHandle =
3371 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3372
3373 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3374 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003375 if (DEBUG_FOCUS) {
3376 ALOGD("Focus left window: %s in display %" PRId32,
3377 oldFocusedWindowHandle->getName().c_str(), displayId);
3378 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379 sp<InputChannel> focusedInputChannel =
3380 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003381 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003383 "focus left window");
3384 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003386 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003388 if (newFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003389 if (DEBUG_FOCUS) {
3390 ALOGD("Focus entered window: %s in display %" PRId32,
3391 newFocusedWindowHandle->getName().c_str(), displayId);
3392 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003393 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 }
Robert Carrf759f162018-11-13 12:57:11 -08003395
3396 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003397 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 }
3400
Arthur Hungb92218b2018-08-14 12:00:21 +08003401 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3402 if (stateIndex >= 0) {
3403 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003404 for (size_t i = 0; i < state.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003405 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003406 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003407 if (DEBUG_FOCUS) {
3408 ALOGD("Touched window was removed: %s in display %" PRId32,
3409 touchedWindow.windowHandle->getName().c_str(), displayId);
3410 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003411 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003412 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003413 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003414 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003415 "touched window was removed");
3416 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3417 options);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003418 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003419 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003420 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003421 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 }
3424 }
3425
3426 // Release information for windows that are no longer present.
3427 // This ensures that unused input channels are released promptly.
3428 // Otherwise, they might stick around until the window handle is destroyed
3429 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003430 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003431 if (!hasWindowHandleLocked(oldWindowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003432 if (DEBUG_FOCUS) {
3433 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
3434 }
Arthur Hung3b413f22018-10-26 18:05:34 +08003435 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 }
3437 }
3438 } // release lock
3439
3440 // Wake up poll loop since it may need to make new input dispatching choices.
3441 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003442
3443 if (setInputWindowsListener) {
3444 setInputWindowsListener->onSetInputWindowsFinished();
3445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446}
3447
3448void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003449 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003450 if (DEBUG_FOCUS) {
3451 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3452 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3453 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003455 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456
Tiger Huang721e26f2018-07-24 22:26:19 +08003457 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3458 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003459 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003460 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3461 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003464 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003466 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003468 oldFocusedApplicationHandle.clear();
3469 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 } // release lock
3472
3473 // Wake up poll loop since it may need to make new input dispatching choices.
3474 mLooper->wake();
3475}
3476
Tiger Huang721e26f2018-07-24 22:26:19 +08003477/**
3478 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3479 * the display not specified.
3480 *
3481 * We track any unreleased events for each window. If a window loses the ability to receive the
3482 * released event, we will send a cancel event to it. So when the focused display is changed, we
3483 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3484 * display. The display-specified events won't be affected.
3485 */
3486void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003487 if (DEBUG_FOCUS) {
3488 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3489 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003490 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003491 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003492
3493 if (mFocusedDisplayId != displayId) {
3494 sp<InputWindowHandle> oldFocusedWindowHandle =
3495 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3496 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003497 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003498 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003499 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003500 CancelationOptions
3501 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3502 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003503 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003504 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3505 }
3506 }
3507 mFocusedDisplayId = displayId;
3508
3509 // Sanity check
3510 sp<InputWindowHandle> newFocusedWindowHandle =
3511 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003512 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003513
Tiger Huang721e26f2018-07-24 22:26:19 +08003514 if (newFocusedWindowHandle == nullptr) {
3515 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3516 if (!mFocusedWindowHandlesByDisplay.empty()) {
3517 ALOGE("But another display has a focused window:");
3518 for (auto& it : mFocusedWindowHandlesByDisplay) {
3519 const int32_t displayId = it.first;
3520 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003521 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3522 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003523 }
3524 }
3525 }
3526 }
3527
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003528 if (DEBUG_FOCUS) {
3529 logDispatchStateLocked();
3530 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003531 } // release lock
3532
3533 // Wake up poll loop since it may need to make new input dispatching choices.
3534 mLooper->wake();
3535}
3536
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003538 if (DEBUG_FOCUS) {
3539 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003541
3542 bool changed;
3543 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003544 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545
3546 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3547 if (mDispatchFrozen && !frozen) {
3548 resetANRTimeoutsLocked();
3549 }
3550
3551 if (mDispatchEnabled && !enabled) {
3552 resetAndDropEverythingLocked("dispatcher is being disabled");
3553 }
3554
3555 mDispatchEnabled = enabled;
3556 mDispatchFrozen = frozen;
3557 changed = true;
3558 } else {
3559 changed = false;
3560 }
3561
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003562 if (DEBUG_FOCUS) {
3563 logDispatchStateLocked();
3564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 } // release lock
3566
3567 if (changed) {
3568 // Wake up poll loop since it may need to make new input dispatching choices.
3569 mLooper->wake();
3570 }
3571}
3572
3573void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003574 if (DEBUG_FOCUS) {
3575 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577
3578 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003579 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580
3581 if (mInputFilterEnabled == enabled) {
3582 return;
3583 }
3584
3585 mInputFilterEnabled = enabled;
3586 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3587 } // release lock
3588
3589 // Wake up poll loop since there might be work to do to drop everything.
3590 mLooper->wake();
3591}
3592
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003593void InputDispatcher::setInTouchMode(bool inTouchMode) {
3594 std::scoped_lock lock(mLock);
3595 mInTouchMode = inTouchMode;
3596}
3597
chaviwfbe5d9c2018-12-26 12:23:37 -08003598bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3599 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003600 if (DEBUG_FOCUS) {
3601 ALOGD("Trivial transfer to same window.");
3602 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003603 return true;
3604 }
3605
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003607 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608
chaviwfbe5d9c2018-12-26 12:23:37 -08003609 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3610 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003611 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003612 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 return false;
3614 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003615 if (DEBUG_FOCUS) {
3616 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3617 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003620 if (DEBUG_FOCUS) {
3621 ALOGD("Cannot transfer focus because windows are on different displays.");
3622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 return false;
3624 }
3625
3626 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003627 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3628 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3629 for (size_t i = 0; i < state.windows.size(); i++) {
3630 const TouchedWindow& touchedWindow = state.windows[i];
3631 if (touchedWindow.windowHandle == fromWindowHandle) {
3632 int32_t oldTargetFlags = touchedWindow.targetFlags;
3633 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003635 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003637 int32_t newTargetFlags = oldTargetFlags &
3638 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3639 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003640 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641
Jeff Brownf086ddb2014-02-11 14:28:48 -08003642 found = true;
3643 goto Found;
3644 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 }
3646 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003647 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003649 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003650 if (DEBUG_FOCUS) {
3651 ALOGD("Focus transfer failed because from window did not have focus.");
3652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653 return false;
3654 }
3655
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003656 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3657 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003658 if (fromConnection != nullptr && toConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003660 CancelationOptions
3661 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3662 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3664 }
3665
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003666 if (DEBUG_FOCUS) {
3667 logDispatchStateLocked();
3668 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 } // release lock
3670
3671 // Wake up poll loop since it may need to make new input dispatching choices.
3672 mLooper->wake();
3673 return true;
3674}
3675
3676void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003677 if (DEBUG_FOCUS) {
3678 ALOGD("Resetting and dropping all events (%s).", reason);
3679 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680
3681 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3682 synthesizeCancelationEventsForAllConnectionsLocked(options);
3683
3684 resetKeyRepeatLocked();
3685 releasePendingEventLocked();
3686 drainInboundQueueLocked();
3687 resetANRTimeoutsLocked();
3688
Jeff Brownf086ddb2014-02-11 14:28:48 -08003689 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003691 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692}
3693
3694void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003695 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 dumpDispatchStateLocked(dump);
3697
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003698 std::istringstream stream(dump);
3699 std::string line;
3700
3701 while (std::getline(stream, line, '\n')) {
3702 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703 }
3704}
3705
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003706void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003707 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3708 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3709 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003710 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711
Tiger Huang721e26f2018-07-24 22:26:19 +08003712 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3713 dump += StringPrintf(INDENT "FocusedApplications:\n");
3714 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3715 const int32_t displayId = it.first;
3716 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003717 dump += StringPrintf(INDENT2 "displayId=%" PRId32
3718 ", name='%s', dispatchingTimeout=%0.3fms\n",
3719 displayId, applicationHandle->getName().c_str(),
3720 applicationHandle->getDispatchingTimeout(
3721 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3722 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08003723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003725 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003727
3728 if (!mFocusedWindowHandlesByDisplay.empty()) {
3729 dump += StringPrintf(INDENT "FocusedWindows:\n");
3730 for (auto& it : mFocusedWindowHandlesByDisplay) {
3731 const int32_t displayId = it.first;
3732 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003733 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3734 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003735 }
3736 } else {
3737 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739
Jeff Brownf086ddb2014-02-11 14:28:48 -08003740 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003741 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003742 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3743 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003744 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003745 state.displayId, toString(state.down), toString(state.split),
3746 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003747 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003748 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003749 for (size_t i = 0; i < state.windows.size(); i++) {
3750 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003751 dump += StringPrintf(INDENT4
3752 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3753 i, touchedWindow.windowHandle->getName().c_str(),
3754 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003755 }
3756 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003757 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003758 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003759 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003760 dump += INDENT3 "Portal windows:\n";
3761 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003762 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003763 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3764 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003765 }
3766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 }
3768 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003769 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 }
3771
Arthur Hungb92218b2018-08-14 12:00:21 +08003772 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003773 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003774 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003775 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003776 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003777 dump += INDENT2 "Windows:\n";
3778 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003779 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003780 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781
Arthur Hungb92218b2018-08-14 12:00:21 +08003782 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003783 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
3784 "hasWallpaper=%s, "
3785 "visible=%s, canReceiveKeys=%s, flags=0x%08x, "
3786 "type=0x%08x, layer=%d, "
3787 "frame=[%d,%d][%d,%d], globalScale=%f, "
3788 "windowScale=(%f,%f), "
3789 "touchableRegion=",
3790 i, windowInfo->name.c_str(), windowInfo->displayId,
3791 windowInfo->portalToDisplayId,
3792 toString(windowInfo->paused),
3793 toString(windowInfo->hasFocus),
3794 toString(windowInfo->hasWallpaper),
3795 toString(windowInfo->visible),
3796 toString(windowInfo->canReceiveKeys),
3797 windowInfo->layoutParamsFlags,
3798 windowInfo->layoutParamsType, windowInfo->layer,
3799 windowInfo->frameLeft, windowInfo->frameTop,
3800 windowInfo->frameRight, windowInfo->frameBottom,
3801 windowInfo->globalScaleFactor, windowInfo->windowXScale,
3802 windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003803 dumpRegion(dump, windowInfo->touchableRegion);
3804 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3805 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003806 windowInfo->ownerPid, windowInfo->ownerUid,
3807 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08003808 }
3809 } else {
3810 dump += INDENT2 "Windows: <none>\n";
3811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 }
3813 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003814 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 }
3816
Michael Wright3dd60e22019-03-27 22:06:44 +00003817 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003818 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003819 const std::vector<Monitor>& monitors = it.second;
3820 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3821 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003822 }
3823 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003824 const std::vector<Monitor>& monitors = it.second;
3825 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3826 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003829 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 }
3831
3832 nsecs_t currentTime = now();
3833
3834 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003835 if (!mRecentQueue.empty()) {
3836 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
3837 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003838 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003840 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 }
3842 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003843 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844 }
3845
3846 // Dump event currently being dispatched.
3847 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003848 dump += INDENT "PendingEvent:\n";
3849 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003851 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003852 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003854 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 }
3856
3857 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003858 if (!mInboundQueue.empty()) {
3859 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
3860 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003861 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003863 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864 }
3865 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003866 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 }
3868
Michael Wright78f24442014-08-06 15:55:28 -07003869 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003870 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003871 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3872 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3873 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003874 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3875 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07003876 }
3877 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003878 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003879 }
3880
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003881 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003882 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003883 for (const auto& pair : mConnectionsByFd) {
3884 const sp<Connection>& connection = pair.second;
3885 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
3886 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3887 pair.first, connection->getInputChannelName().c_str(),
3888 connection->getWindowName().c_str(), connection->getStatusLabel(),
3889 toString(connection->monitor),
3890 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003892 if (!connection->outboundQueue.empty()) {
3893 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
3894 connection->outboundQueue.size());
3895 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 dump.append(INDENT4);
3897 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003898 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003899 entry->targetFlags, entry->resolvedAction,
3900 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901 }
3902 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003903 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904 }
3905
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003906 if (!connection->waitQueue.empty()) {
3907 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
3908 connection->waitQueue.size());
3909 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003910 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003912 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003913 "age=%0.1fms, wait=%0.1fms\n",
3914 entry->targetFlags, entry->resolvedAction,
3915 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3916 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 }
3918 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003919 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920 }
3921 }
3922 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003923 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 }
3925
3926 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003927 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003928 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003930 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 }
3932
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003933 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003934 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003935 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003936 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937}
3938
Michael Wright3dd60e22019-03-27 22:06:44 +00003939void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3940 const size_t numMonitors = monitors.size();
3941 for (size_t i = 0; i < numMonitors; i++) {
3942 const Monitor& monitor = monitors[i];
3943 const sp<InputChannel>& channel = monitor.inputChannel;
3944 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3945 dump += "\n";
3946 }
3947}
3948
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003949status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003951 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952#endif
3953
3954 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003955 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003956 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003957 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003959 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960 return BAD_VALUE;
3961 }
3962
Michael Wright3dd60e22019-03-27 22:06:44 +00003963 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964
3965 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003966 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003967 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3970 } // release lock
3971
3972 // Wake the looper because some connections have changed.
3973 mLooper->wake();
3974 return OK;
3975}
3976
Michael Wright3dd60e22019-03-27 22:06:44 +00003977status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003978 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003979 { // acquire lock
3980 std::scoped_lock _l(mLock);
3981
3982 if (displayId < 0) {
3983 ALOGW("Attempted to register input monitor without a specified display.");
3984 return BAD_VALUE;
3985 }
3986
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003987 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003988 ALOGW("Attempted to register input monitor without an identifying token.");
3989 return BAD_VALUE;
3990 }
3991
3992 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3993
3994 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003995 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003996 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00003997
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003998 auto& monitorsByDisplay =
3999 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004000 monitorsByDisplay[displayId].emplace_back(inputChannel);
4001
4002 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004003 }
4004 // Wake the looper because some connections have changed.
4005 mLooper->wake();
4006 return OK;
4007}
4008
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4010#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004011 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012#endif
4013
4014 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004015 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016
4017 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4018 if (status) {
4019 return status;
4020 }
4021 } // release lock
4022
4023 // Wake the poll loop because removing the connection may have changed the current
4024 // synchronization state.
4025 mLooper->wake();
4026 return OK;
4027}
4028
4029status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004030 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004031 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004032 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004034 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035 return BAD_VALUE;
4036 }
4037
John Recke0710582019-09-26 13:46:12 -07004038 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004039 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004040 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004041
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042 if (connection->monitor) {
4043 removeMonitorChannelLocked(inputChannel);
4044 }
4045
4046 mLooper->removeFd(inputChannel->getFd());
4047
4048 nsecs_t currentTime = now();
4049 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4050
4051 connection->status = Connection::STATUS_ZOMBIE;
4052 return OK;
4053}
4054
4055void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004056 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4057 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4058}
4059
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004060void InputDispatcher::removeMonitorChannelLocked(
4061 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004062 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004063 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004064 std::vector<Monitor>& monitors = it->second;
4065 const size_t numMonitors = monitors.size();
4066 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004067 if (monitors[i].inputChannel == inputChannel) {
4068 monitors.erase(monitors.begin() + i);
4069 break;
4070 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004071 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004072 if (monitors.empty()) {
4073 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004074 } else {
4075 ++it;
4076 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077 }
4078}
4079
Michael Wright3dd60e22019-03-27 22:06:44 +00004080status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4081 { // acquire lock
4082 std::scoped_lock _l(mLock);
4083 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4084
4085 if (!foundDisplayId) {
4086 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4087 return BAD_VALUE;
4088 }
4089 int32_t displayId = foundDisplayId.value();
4090
4091 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4092 if (stateIndex < 0) {
4093 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4094 return BAD_VALUE;
4095 }
4096
4097 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4098 std::optional<int32_t> foundDeviceId;
4099 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004100 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004101 foundDeviceId = state.deviceId;
4102 }
4103 }
4104 if (!foundDeviceId || !state.down) {
4105 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004106 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004107 return BAD_VALUE;
4108 }
4109 int32_t deviceId = foundDeviceId.value();
4110
4111 // Send cancel events to all the input channels we're stealing from.
4112 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004113 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004114 options.deviceId = deviceId;
4115 options.displayId = displayId;
4116 for (const TouchedWindow& window : state.windows) {
4117 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004118 if (channel != nullptr) {
4119 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4120 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004121 }
4122 // Then clear the current touch state so we stop dispatching to them as well.
4123 state.filterNonMonitors();
4124 }
4125 return OK;
4126}
4127
Michael Wright3dd60e22019-03-27 22:06:44 +00004128std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4129 const sp<IBinder>& token) {
4130 for (const auto& it : mGestureMonitorsByDisplay) {
4131 const std::vector<Monitor>& monitors = it.second;
4132 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004133 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004134 return it.first;
4135 }
4136 }
4137 }
4138 return std::nullopt;
4139}
4140
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004141sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4142 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004143 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004144 }
4145
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004146 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004147 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004148 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004149 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150 }
4151 }
Robert Carr4e670e52018-08-15 13:26:12 -07004152
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004153 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154}
4155
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004156void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4157 const sp<Connection>& connection, uint32_t seq,
4158 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004159 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4160 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 commandEntry->connection = connection;
4162 commandEntry->eventTime = currentTime;
4163 commandEntry->seq = seq;
4164 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004165 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166}
4167
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004168void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4169 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004171 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004173 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4174 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004176 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177}
4178
chaviw0c06c6e2019-01-09 13:27:07 -08004179void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004181 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4182 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004183 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4184 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004185 commandEntry->oldToken = oldToken;
4186 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004187 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004188}
4189
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004190void InputDispatcher::onANRLocked(nsecs_t currentTime,
4191 const sp<InputApplicationHandle>& applicationHandle,
4192 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4193 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4195 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4196 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4198 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4199 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200
4201 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004202 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 struct tm tm;
4204 localtime_r(&t, &tm);
4205 char timestr[64];
4206 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4207 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004208 mLastANRState += INDENT "ANR:\n";
4209 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004210 mLastANRState +=
4211 StringPrintf(INDENT2 "Window: %s\n",
4212 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004213 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4214 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4215 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216 dumpDispatchStateLocked(mLastANRState);
4217
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004218 std::unique_ptr<CommandEntry> commandEntry =
4219 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004221 commandEntry->inputChannel =
4222 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004224 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225}
4226
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004227void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 mLock.unlock();
4229
4230 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4231
4232 mLock.lock();
4233}
4234
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004235void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 sp<Connection> connection = commandEntry->connection;
4237
4238 if (connection->status != Connection::STATUS_ZOMBIE) {
4239 mLock.unlock();
4240
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004241 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242
4243 mLock.lock();
4244 }
4245}
4246
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004247void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004248 sp<IBinder> oldToken = commandEntry->oldToken;
4249 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004250 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004251 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004252 mLock.lock();
4253}
4254
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004255void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004256 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004257 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 mLock.unlock();
4259
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004260 nsecs_t newTimeout =
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004261 mPolicy->notifyANR(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262
4263 mLock.lock();
4264
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004265 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266}
4267
4268void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4269 CommandEntry* commandEntry) {
4270 KeyEntry* entry = commandEntry->keyEntry;
4271
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004272 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273
4274 mLock.unlock();
4275
Michael Wright2b3c3302018-03-02 17:19:13 +00004276 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004277 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004278 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004279 : nullptr;
4280 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004281 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4282 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004283 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285
4286 mLock.lock();
4287
4288 if (delay < 0) {
4289 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4290 } else if (!delay) {
4291 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4292 } else {
4293 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4294 entry->interceptKeyWakeupTime = now() + delay;
4295 }
4296 entry->release();
4297}
4298
chaviwfd6d3512019-03-25 13:23:49 -07004299void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4300 mLock.unlock();
4301 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4302 mLock.lock();
4303}
4304
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004305void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004307 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004309 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310
4311 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004312 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004313 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004314 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004316 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004317
4318 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4319 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4320 std::string msg =
4321 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4322 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4323 dispatchEntry->eventEntry->appendDescription(msg);
4324 ALOGI("%s", msg.c_str());
4325 }
4326
4327 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004328 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004329 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4330 restartEvent =
4331 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004332 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004333 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4334 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4335 handled);
4336 } else {
4337 restartEvent = false;
4338 }
4339
4340 // Dequeue the event and start the next cycle.
4341 // Note that because the lock might have been released, it is possible that the
4342 // contents of the wait queue to have been drained, so we need to double-check
4343 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004344 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4345 if (dispatchEntryIt != connection->waitQueue.end()) {
4346 dispatchEntry = *dispatchEntryIt;
4347 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004348 traceWaitQueueLength(connection);
4349 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004350 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004351 traceOutboundQueueLength(connection);
4352 } else {
4353 releaseDispatchEntry(dispatchEntry);
4354 }
4355 }
4356
4357 // Start the next dispatch cycle for this connection.
4358 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359}
4360
4361bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004362 DispatchEntry* dispatchEntry,
4363 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004364 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004365 if (!handled) {
4366 // Report the key as unhandled, since the fallback was not handled.
4367 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4368 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004369 return false;
4370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004372 // Get the fallback key state.
4373 // Clear it out after dispatching the UP.
4374 int32_t originalKeyCode = keyEntry->keyCode;
4375 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4376 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4377 connection->inputState.removeFallbackKey(originalKeyCode);
4378 }
4379
4380 if (handled || !dispatchEntry->hasForegroundTarget()) {
4381 // If the application handles the original key for which we previously
4382 // generated a fallback or if the window is not a foreground window,
4383 // then cancel the associated fallback key, if any.
4384 if (fallbackKeyCode != -1) {
4385 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004387 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004388 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4389 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4390 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004392 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004393 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394
4395 mLock.unlock();
4396
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004397 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004398 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399
4400 mLock.lock();
4401
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004402 // Cancel the fallback key.
4403 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004405 "application handled the original non-fallback key "
4406 "or is no longer a foreground target, "
4407 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 options.keyCode = fallbackKeyCode;
4409 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004411 connection->inputState.removeFallbackKey(originalKeyCode);
4412 }
4413 } else {
4414 // If the application did not handle a non-fallback key, first check
4415 // that we are in a good state to perform unhandled key event processing
4416 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004417 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004418 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004420 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004421 "since this is not an initial down. "
4422 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4423 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004425 return false;
4426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004428 // Dispatch the unhandled key to the policy.
4429#if DEBUG_OUTBOUND_EVENT_DETAILS
4430 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004431 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4432 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004433#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004434 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004435
4436 mLock.unlock();
4437
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004438 bool fallback =
4439 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4440 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004441
4442 mLock.lock();
4443
4444 if (connection->status != Connection::STATUS_NORMAL) {
4445 connection->inputState.removeFallbackKey(originalKeyCode);
4446 return false;
4447 }
4448
4449 // Latch the fallback keycode for this key on an initial down.
4450 // The fallback keycode cannot change at any other point in the lifecycle.
4451 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004453 fallbackKeyCode = event.getKeyCode();
4454 } else {
4455 fallbackKeyCode = AKEYCODE_UNKNOWN;
4456 }
4457 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4458 }
4459
4460 ALOG_ASSERT(fallbackKeyCode != -1);
4461
4462 // Cancel the fallback key if the policy decides not to send it anymore.
4463 // We will continue to dispatch the key to the policy but we will no
4464 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004465 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4466 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004467#if DEBUG_OUTBOUND_EVENT_DETAILS
4468 if (fallback) {
4469 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004470 "as a fallback for %d, but on the DOWN it had requested "
4471 "to send %d instead. Fallback canceled.",
4472 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004473 } else {
4474 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004475 "but on the DOWN it had requested to send %d. "
4476 "Fallback canceled.",
4477 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004478 }
4479#endif
4480
4481 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4482 "canceling fallback, policy no longer desires it");
4483 options.keyCode = fallbackKeyCode;
4484 synthesizeCancelationEventsForConnectionLocked(connection, options);
4485
4486 fallback = false;
4487 fallbackKeyCode = AKEYCODE_UNKNOWN;
4488 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004489 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004490 }
4491 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492
4493#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004494 {
4495 std::string msg;
4496 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4497 connection->inputState.getFallbackKeys();
4498 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004499 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004501 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004502 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004503 }
4504#endif
4505
4506 if (fallback) {
4507 // Restart the dispatch cycle using the fallback key.
4508 keyEntry->eventTime = event.getEventTime();
4509 keyEntry->deviceId = event.getDeviceId();
4510 keyEntry->source = event.getSource();
4511 keyEntry->displayId = event.getDisplayId();
4512 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4513 keyEntry->keyCode = fallbackKeyCode;
4514 keyEntry->scanCode = event.getScanCode();
4515 keyEntry->metaState = event.getMetaState();
4516 keyEntry->repeatCount = event.getRepeatCount();
4517 keyEntry->downTime = event.getDownTime();
4518 keyEntry->syntheticRepeat = false;
4519
4520#if DEBUG_OUTBOUND_EVENT_DETAILS
4521 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004522 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4523 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004524#endif
4525 return true; // restart the event
4526 } else {
4527#if DEBUG_OUTBOUND_EVENT_DETAILS
4528 ALOGD("Unhandled key event: No fallback key.");
4529#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004530
4531 // Report the key as unhandled, since there is no fallback key.
4532 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533 }
4534 }
4535 return false;
4536}
4537
4538bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004539 DispatchEntry* dispatchEntry,
4540 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541 return false;
4542}
4543
4544void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4545 mLock.unlock();
4546
4547 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4548
4549 mLock.lock();
4550}
4551
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004552KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4553 KeyEvent event;
4554 event.initialize(entry.deviceId, entry.source, entry.displayId, entry.action, entry.flags,
4555 entry.keyCode, entry.scanCode, entry.metaState, entry.repeatCount,
4556 entry.downTime, entry.eventTime);
4557 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558}
4559
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004560void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004561 int32_t injectionResult,
4562 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 // TODO Write some statistics about how long we spend waiting.
4564}
4565
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004566/**
4567 * Report the touch event latency to the statsd server.
4568 * Input events are reported for statistics if:
4569 * - This is a touchscreen event
4570 * - InputFilter is not enabled
4571 * - Event is not injected or synthesized
4572 *
4573 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4574 * from getting aggregated with the "old" data.
4575 */
4576void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4577 REQUIRES(mLock) {
4578 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4579 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4580 if (!reportForStatistics) {
4581 return;
4582 }
4583
4584 if (mTouchStatistics.shouldReport()) {
4585 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4586 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4587 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4588 mTouchStatistics.reset();
4589 }
4590 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4591 mTouchStatistics.addValue(latencyMicros);
4592}
4593
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594void InputDispatcher::traceInboundQueueLengthLocked() {
4595 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004596 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 }
4598}
4599
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004600void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601 if (ATRACE_ENABLED()) {
4602 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004603 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004604 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 }
4606}
4607
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004608void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609 if (ATRACE_ENABLED()) {
4610 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004611 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004612 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613 }
4614}
4615
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004616void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004617 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004619 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620 dumpDispatchStateLocked(dump);
4621
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004622 if (!mLastANRState.empty()) {
4623 dump += "\nInput Dispatcher State at time of last ANR:\n";
4624 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 }
4626}
4627
4628void InputDispatcher::monitor() {
4629 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004630 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004632 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633}
4634
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004635/**
4636 * Wake up the dispatcher and wait until it processes all events and commands.
4637 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4638 * this method can be safely called from any thread, as long as you've ensured that
4639 * the work you are interested in completing has already been queued.
4640 */
4641bool InputDispatcher::waitForIdle() {
4642 /**
4643 * Timeout should represent the longest possible time that a device might spend processing
4644 * events and commands.
4645 */
4646 constexpr std::chrono::duration TIMEOUT = 100ms;
4647 std::unique_lock lock(mLock);
4648 mLooper->wake();
4649 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4650 return result == std::cv_status::no_timeout;
4651}
4652
Garfield Tane84e6f92019-08-29 17:28:41 -07004653} // namespace android::inputdispatcher