blob: 116625c03e403df3b68254f0bffd7a47e04e4d87 [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
chaviwaf87b3e2019-10-01 16:59:28 -0700243static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
244 if (first == second) {
245 return true;
246 }
247
248 if (first == nullptr || second == nullptr) {
249 return false;
250 }
251
252 return first->getToken() == second->getToken();
253}
254
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700255// --- InputDispatcherThread ---
256
257class InputDispatcher::InputDispatcherThread : public Thread {
258public:
259 explicit InputDispatcherThread(InputDispatcher* dispatcher)
260 : Thread(/* canCallJava */ true), mDispatcher(dispatcher) {}
261
262 ~InputDispatcherThread() {}
263
264private:
265 InputDispatcher* mDispatcher;
266
267 virtual bool threadLoop() override {
268 mDispatcher->dispatchOnce();
269 return true;
270 }
271};
272
Michael Wrightd02c5b62014-02-10 15:10:22 -0800273// --- InputDispatcher ---
274
Garfield Tan00f511d2019-06-12 16:55:40 -0700275InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
276 : mPolicy(policy),
277 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700278 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tan00f511d2019-06-12 16:55:40 -0700279 mAppSwitchSawKeyDown(false),
280 mAppSwitchDueTime(LONG_LONG_MAX),
281 mNextUnblockedEvent(nullptr),
282 mDispatchEnabled(false),
283 mDispatchFrozen(false),
284 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800285 // mInTouchMode will be initialized by the WindowManager to the default device config.
286 // To avoid leaking stack in case that call never comes, and for tests,
287 // initialize it here anyways.
288 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700289 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
290 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800291 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800292 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800293
Yi Kong9b14ac62018-07-17 13:48:38 -0700294 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800295
296 policy->getDispatcherConfiguration(&mConfig);
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700297
298 mThread = new InputDispatcherThread(this);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800299}
300
301InputDispatcher::~InputDispatcher() {
302 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800303 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800304
305 resetKeyRepeatLocked();
306 releasePendingEventLocked();
307 drainInboundQueueLocked();
308 }
309
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700310 while (!mConnectionsByFd.empty()) {
311 sp<Connection> connection = mConnectionsByFd.begin()->second;
312 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800313 }
314}
315
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700316status_t InputDispatcher::start() {
317 if (mThread->isRunning()) {
318 return ALREADY_EXISTS;
319 }
320 return mThread->run("InputDispatcher", PRIORITY_URGENT_DISPLAY);
321}
322
323status_t InputDispatcher::stop() {
324 if (!mThread->isRunning()) {
325 return OK;
326 }
327 if (gettid() == mThread->getTid()) {
328 ALOGE("InputDispatcher can only be stopped from outside of the InputDispatcherThread!");
329 return INVALID_OPERATION;
330 }
331 // Directly calling requestExitAndWait() causes the thread to not exit
332 // if mLooper is waiting for a long timeout.
333 mThread->requestExit();
334 mLooper->wake();
335 return mThread->requestExitAndWait();
336}
337
Michael Wrightd02c5b62014-02-10 15:10:22 -0800338void InputDispatcher::dispatchOnce() {
339 nsecs_t nextWakeupTime = LONG_LONG_MAX;
340 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800341 std::scoped_lock _l(mLock);
342 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800343
344 // Run a dispatch loop if there are no pending commands.
345 // The dispatch loop might enqueue commands to run afterwards.
346 if (!haveCommandsLocked()) {
347 dispatchOnceInnerLocked(&nextWakeupTime);
348 }
349
350 // Run all pending commands if there are any.
351 // If any commands were run then force the next poll to wake up immediately.
352 if (runCommandsLockedInterruptible()) {
353 nextWakeupTime = LONG_LONG_MIN;
354 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800355
356 // We are about to enter an infinitely long sleep, because we have no commands or
357 // pending or queued events
358 if (nextWakeupTime == LONG_LONG_MAX) {
359 mDispatcherEnteredIdle.notify_all();
360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800361 } // release lock
362
363 // Wait for callback or timeout or wake. (make sure we round up, not down)
364 nsecs_t currentTime = now();
365 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
366 mLooper->pollOnce(timeoutMillis);
367}
368
369void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
370 nsecs_t currentTime = now();
371
Jeff Browndc5992e2014-04-11 01:27:26 -0700372 // Reset the key repeat timer whenever normal dispatch is suspended while the
373 // device is in a non-interactive state. This is to ensure that we abort a key
374 // repeat if the device is just coming out of sleep.
375 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800376 resetKeyRepeatLocked();
377 }
378
379 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
380 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100381 if (DEBUG_FOCUS) {
382 ALOGD("Dispatch frozen. Waiting some more.");
383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800384 return;
385 }
386
387 // Optimize latency of app switches.
388 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
389 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
390 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
391 if (mAppSwitchDueTime < *nextWakeupTime) {
392 *nextWakeupTime = mAppSwitchDueTime;
393 }
394
395 // Ready to start a new event.
396 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700397 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700398 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800399 if (isAppSwitchDue) {
400 // The inbound queue is empty so the app switch key we were waiting
401 // for will never arrive. Stop waiting for it.
402 resetPendingAppSwitchLocked(false);
403 isAppSwitchDue = false;
404 }
405
406 // Synthesize a key repeat if appropriate.
407 if (mKeyRepeatState.lastKeyEntry) {
408 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
409 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
410 } else {
411 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
412 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
413 }
414 }
415 }
416
417 // Nothing to do if there is no pending event.
418 if (!mPendingEvent) {
419 return;
420 }
421 } else {
422 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700423 mPendingEvent = mInboundQueue.front();
424 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800425 traceInboundQueueLengthLocked();
426 }
427
428 // Poke user activity for this event.
429 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700430 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 }
432
433 // Get ready to dispatch the event.
434 resetANRTimeoutsLocked();
435 }
436
437 // Now we have an event to dispatch.
438 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700439 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700441 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800442 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700443 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800444 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700445 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800446 }
447
448 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700449 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450 }
451
452 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700453 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700454 ConfigurationChangedEntry* typedEntry =
455 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
456 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700457 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700458 break;
459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800460
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700461 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700462 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
463 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700464 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700465 break;
466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800467
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700468 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700469 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
470 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700471 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700472 resetPendingAppSwitchLocked(true);
473 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700474 } else if (dropReason == DropReason::NOT_DROPPED) {
475 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700476 }
477 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700478 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700479 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700480 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700481 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
482 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700483 }
484 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
485 break;
486 }
487
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700488 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700489 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700490 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
491 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700493 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700494 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700495 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700496 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
497 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700498 }
499 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
500 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502 }
503
504 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700505 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700506 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800507 }
Michael Wright3a981722015-06-10 15:26:13 +0100508 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509
510 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700511 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800512 }
513}
514
515bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700516 bool needWake = mInboundQueue.empty();
517 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800518 traceInboundQueueLengthLocked();
519
520 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700521 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700522 // Optimize app switch latency.
523 // If the application takes too long to catch up then we drop all events preceding
524 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700525 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700526 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700527 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700528 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700529 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700530 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700532 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700534 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700535 mAppSwitchSawKeyDown = false;
536 needWake = true;
537 }
538 }
539 }
540 break;
541 }
542
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700543 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700544 // Optimize case where the current application is unresponsive and the user
545 // decides to touch a window in a different application.
546 // If the application takes too long to catch up then we drop all events preceding
547 // the touch into the other window.
548 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
549 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
550 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
551 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
552 mInputTargetWaitApplicationToken != nullptr) {
553 int32_t displayId = motionEntry->displayId;
554 int32_t x =
555 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
556 int32_t y =
557 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
558 sp<InputWindowHandle> touchedWindowHandle =
559 findTouchedWindowAtLocked(displayId, x, y);
560 if (touchedWindowHandle != nullptr &&
561 touchedWindowHandle->getApplicationToken() !=
562 mInputTargetWaitApplicationToken) {
563 // User touched a different application than the one we are waiting on.
564 // Flag the event, and start pruning the input queue.
565 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800566 needWake = true;
567 }
568 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700569 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700571 case EventEntry::Type::CONFIGURATION_CHANGED:
572 case EventEntry::Type::DEVICE_RESET: {
573 // nothing to do
574 break;
575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576 }
577
578 return needWake;
579}
580
581void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
582 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700583 mRecentQueue.push_back(entry);
584 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
585 mRecentQueue.front()->release();
586 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800587 }
588}
589
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700590sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
591 int32_t y, bool addOutsideTargets,
592 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800594 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
595 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596 const InputWindowInfo* windowInfo = windowHandle->getInfo();
597 if (windowInfo->displayId == displayId) {
598 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599
600 if (windowInfo->visible) {
601 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700602 bool isTouchModal = (flags &
603 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
604 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800606 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700607 if (portalToDisplayId != ADISPLAY_ID_NONE &&
608 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800609 if (addPortalWindows) {
610 // For the monitoring channels of the display.
611 mTempTouchState.addPortalWindow(windowHandle);
612 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700613 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
614 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800615 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 // Found window.
617 return windowHandle;
618 }
619 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800620
621 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700622 mTempTouchState.addOrUpdateWindow(windowHandle,
623 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
624 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 }
628 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700629 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630}
631
Garfield Tane84e6f92019-08-29 17:28:41 -0700632std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000633 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
634 std::vector<TouchedMonitor> touchedMonitors;
635
636 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
637 addGestureMonitors(monitors, touchedMonitors);
638 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
639 const InputWindowInfo* windowInfo = portalWindow->getInfo();
640 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700641 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
642 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000643 }
644 return touchedMonitors;
645}
646
647void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700648 std::vector<TouchedMonitor>& outTouchedMonitors,
649 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000650 if (monitors.empty()) {
651 return;
652 }
653 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
654 for (const Monitor& monitor : monitors) {
655 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
656 }
657}
658
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700659void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 const char* reason;
661 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700662 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700664 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700666 reason = "inbound event was dropped because the policy consumed it";
667 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700668 case DropReason::DISABLED:
669 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700670 ALOGI("Dropped event because input dispatch is disabled.");
671 }
672 reason = "inbound event was dropped because input dispatch is disabled";
673 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700674 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700675 ALOGI("Dropped event because of pending overdue app switch.");
676 reason = "inbound event was dropped because of pending overdue app switch";
677 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700678 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700679 ALOGI("Dropped event because the current application is not responding and the user "
680 "has started interacting with a different application.");
681 reason = "inbound event was dropped because the current application is not responding "
682 "and the user has started interacting with a different application";
683 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700684 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700685 ALOGI("Dropped event because it is stale.");
686 reason = "inbound event was dropped because it is stale";
687 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700688 case DropReason::NOT_DROPPED: {
689 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700690 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 }
693
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700694 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700695 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
697 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700698 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700700 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700701 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
702 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700703 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
704 synthesizeCancelationEventsForAllConnectionsLocked(options);
705 } else {
706 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
707 synthesizeCancelationEventsForAllConnectionsLocked(options);
708 }
709 break;
710 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700711 case EventEntry::Type::CONFIGURATION_CHANGED:
712 case EventEntry::Type::DEVICE_RESET: {
713 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
714 break;
715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 }
717}
718
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800719static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700720 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
721 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722}
723
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700724bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
725 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
726 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
727 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728}
729
730bool InputDispatcher::isAppSwitchPendingLocked() {
731 return mAppSwitchDueTime != LONG_LONG_MAX;
732}
733
734void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
735 mAppSwitchDueTime = LONG_LONG_MAX;
736
737#if DEBUG_APP_SWITCH
738 if (handled) {
739 ALOGD("App switch has arrived.");
740 } else {
741 ALOGD("App switch was abandoned.");
742 }
743#endif
744}
745
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700746bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
747 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748}
749
750bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700751 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752}
753
754bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700755 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 return false;
757 }
758
759 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700760 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700761 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700763 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764
765 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700766 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767 return true;
768}
769
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700770void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
771 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772}
773
774void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700775 while (!mInboundQueue.empty()) {
776 EventEntry* entry = mInboundQueue.front();
777 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 releaseInboundEventLocked(entry);
779 }
780 traceInboundQueueLengthLocked();
781}
782
783void InputDispatcher::releasePendingEventLocked() {
784 if (mPendingEvent) {
785 resetANRTimeoutsLocked();
786 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700787 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 }
789}
790
791void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
792 InjectionState* injectionState = entry->injectionState;
793 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
794#if DEBUG_DISPATCH_CYCLE
795 ALOGD("Injected inbound event was dropped.");
796#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800797 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 }
799 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700800 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
802 addRecentEventLocked(entry);
803 entry->release();
804}
805
806void InputDispatcher::resetKeyRepeatLocked() {
807 if (mKeyRepeatState.lastKeyEntry) {
808 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700809 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 }
811}
812
Garfield Tane84e6f92019-08-29 17:28:41 -0700813KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
815
816 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700817 uint32_t policyFlags = entry->policyFlags &
818 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 if (entry->refCount == 1) {
820 entry->recycle();
821 entry->eventTime = currentTime;
822 entry->policyFlags = policyFlags;
823 entry->repeatCount += 1;
824 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700825 KeyEntry* newEntry =
826 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId,
827 entry->source, entry->displayId, policyFlags, entry->action,
828 entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
829 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830
831 mKeyRepeatState.lastKeyEntry = newEntry;
832 entry->release();
833
834 entry = newEntry;
835 }
836 entry->syntheticRepeat = true;
837
838 // Increment reference count since we keep a reference to the event in
839 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
840 entry->refCount += 1;
841
842 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
843 return entry;
844}
845
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700846bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
847 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700849 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850#endif
851
852 // Reset key repeating in case a keyboard device was added or removed or something.
853 resetKeyRepeatLocked();
854
855 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700856 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
857 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700859 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 return true;
861}
862
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700865 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700866 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867#endif
868
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700869 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 options.deviceId = entry->deviceId;
871 synthesizeCancelationEventsForAllConnectionsLocked(options);
872 return true;
873}
874
875bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700876 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700878 if (!entry->dispatchInProgress) {
879 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
880 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
881 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
882 if (mKeyRepeatState.lastKeyEntry &&
883 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 // We have seen two identical key downs in a row which indicates that the device
885 // driver is automatically generating key repeats itself. We take note of the
886 // repeat here, but we disable our own next key repeat timer since it is clear that
887 // we will not need to synthesize key repeats ourselves.
888 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
889 resetKeyRepeatLocked();
890 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
891 } else {
892 // Not a repeat. Save key down state in case we do see a repeat later.
893 resetKeyRepeatLocked();
894 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
895 }
896 mKeyRepeatState.lastKeyEntry = entry;
897 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700898 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 resetKeyRepeatLocked();
900 }
901
902 if (entry->repeatCount == 1) {
903 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
904 } else {
905 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
906 }
907
908 entry->dispatchInProgress = true;
909
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700910 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 }
912
913 // Handle case where the policy asked us to try again later last time.
914 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
915 if (currentTime < entry->interceptKeyWakeupTime) {
916 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
917 *nextWakeupTime = entry->interceptKeyWakeupTime;
918 }
919 return false; // wait until next wakeup
920 }
921 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
922 entry->interceptKeyWakeupTime = 0;
923 }
924
925 // Give the policy a chance to intercept the key.
926 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
927 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700928 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -0700929 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800930 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700931 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +0800932 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700933 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934 }
935 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700936 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937 entry->refCount += 1;
938 return false; // wait for the command to run
939 } else {
940 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
941 }
942 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700943 if (*dropReason == DropReason::NOT_DROPPED) {
944 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 }
946 }
947
948 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700949 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700950 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700951 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952 : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800953 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 return true;
955 }
956
957 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800958 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700959 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700960 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
962 return false;
963 }
964
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800965 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
967 return true;
968 }
969
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800970 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700971 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972
973 // Dispatch the key.
974 dispatchEventLocked(currentTime, entry, inputTargets);
975 return true;
976}
977
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700978void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100980 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
982 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700983 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
984 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
985 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986#endif
987}
988
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
990 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000991 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 entry->dispatchInProgress = true;
995
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700996 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 }
998
999 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001000 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001001 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001002 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001003 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 return true;
1005 }
1006
1007 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1008
1009 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001010 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011
1012 bool conflictingPointerActions = false;
1013 int32_t injectionResult;
1014 if (isPointerEvent) {
1015 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001016 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001017 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001018 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 } else {
1020 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001021 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001022 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 }
1024 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1025 return false;
1026 }
1027
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001028 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001030 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 CancelationOptions::Mode mode(isPointerEvent
1032 ? CancelationOptions::CANCEL_POINTER_EVENTS
1033 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001034 CancelationOptions options(mode, "input event injection failed");
1035 synthesizeCancelationEventsForMonitorsLocked(options);
1036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 return true;
1038 }
1039
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001040 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001041 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001043 if (isPointerEvent) {
1044 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
1045 if (stateIndex >= 0) {
1046 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001047 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001048 // The event has gone through these portal windows, so we add monitoring targets of
1049 // the corresponding displays as well.
1050 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001051 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001052 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001053 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001054 }
1055 }
1056 }
1057 }
1058
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 // Dispatch the motion.
1060 if (conflictingPointerActions) {
1061 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001062 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 synthesizeCancelationEventsForAllConnectionsLocked(options);
1064 }
1065 dispatchEventLocked(currentTime, entry, inputTargets);
1066 return true;
1067}
1068
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001069void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001071 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 ", policyFlags=0x%x, "
1073 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1074 "metaState=0x%x, buttonState=0x%x,"
1075 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001076 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1077 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1078 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001080 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001082 "x=%f, y=%f, pressure=%f, size=%f, "
1083 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1084 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001085 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1086 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1087 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1088 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1089 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1090 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1091 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1092 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1093 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1094 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095 }
1096#endif
1097}
1098
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1100 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001101 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102#if DEBUG_DISPATCH_CYCLE
1103 ALOGD("dispatchEventToCurrentInputTargets");
1104#endif
1105
1106 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1107
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001108 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001110 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001111 sp<Connection> connection =
1112 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001113 if (connection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1115 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001116 if (DEBUG_FOCUS) {
1117 ALOGD("Dropping event delivery to target with channel '%s' because it "
1118 "is no longer registered with the input dispatcher.",
1119 inputTarget.inputChannel->getName().c_str());
1120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 }
1122 }
1123}
1124
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001125int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001126 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001129 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001131 if (DEBUG_FOCUS) {
1132 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1133 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001134 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1135 mInputTargetWaitStartTime = currentTime;
1136 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1137 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001138 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 }
1140 } else {
1141 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001142 if (DEBUG_FOCUS) {
1143 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
1144 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1145 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001147 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001149 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001150 timeout =
1151 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 } else {
1153 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1154 }
1155
1156 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1157 mInputTargetWaitStartTime = currentTime;
1158 mInputTargetWaitTimeoutTime = currentTime + timeout;
1159 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001160 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161
Yi Kong9b14ac62018-07-17 13:48:38 -07001162 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001163 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 }
Robert Carr740167f2018-10-11 19:03:41 -07001165 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1166 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 }
1168 }
1169 }
1170
1171 if (mInputTargetWaitTimeoutExpired) {
1172 return INPUT_EVENT_INJECTION_TIMED_OUT;
1173 }
1174
1175 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001176 onANRLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001177 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178
1179 // Force poll loop to wake up immediately on next iteration once we get the
1180 // ANR response back from the policy.
1181 *nextWakeupTime = LONG_LONG_MIN;
1182 return INPUT_EVENT_INJECTION_PENDING;
1183 } else {
1184 // Force poll loop to wake up when timeout is due.
1185 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1186 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1187 }
1188 return INPUT_EVENT_INJECTION_PENDING;
1189 }
1190}
1191
Robert Carr803535b2018-08-02 16:38:15 -07001192void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1193 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1194 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1195 state.removeWindowByToken(token);
1196 }
1197}
1198
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001199void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001200 nsecs_t newTimeout, const sp<IBinder>& inputConnectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 if (newTimeout > 0) {
1202 // Extend the timeout.
1203 mInputTargetWaitTimeoutTime = now() + newTimeout;
1204 } else {
1205 // Give up.
1206 mInputTargetWaitTimeoutExpired = true;
1207
1208 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001209 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001210 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001211 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001213 if (connection->status == Connection::STATUS_NORMAL) {
1214 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1215 "application not responding");
1216 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 }
1218 }
1219 }
1220}
1221
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001222nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1224 return currentTime - mInputTargetWaitStartTime;
1225 }
1226 return 0;
1227}
1228
1229void InputDispatcher::resetANRTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001230 if (DEBUG_FOCUS) {
1231 ALOGD("Resetting ANR timeouts.");
1232 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233
1234 // Reset input target wait timeout.
1235 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001236 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237}
1238
Tiger Huang721e26f2018-07-24 22:26:19 +08001239/**
1240 * Get the display id that the given event should go to. If this event specifies a valid display id,
1241 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1242 * Focused display is the display that the user most recently interacted with.
1243 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001244int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001245 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001246 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001247 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001248 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1249 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001250 break;
1251 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001252 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001253 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1254 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001255 break;
1256 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001257 case EventEntry::Type::CONFIGURATION_CHANGED:
1258 case EventEntry::Type::DEVICE_RESET: {
1259 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001260 return ADISPLAY_ID_NONE;
1261 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001262 }
1263 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1264}
1265
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001267 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001268 std::vector<InputTarget>& inputTargets,
1269 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001271 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272
Tiger Huang721e26f2018-07-24 22:26:19 +08001273 int32_t displayId = getTargetDisplayId(entry);
1274 sp<InputWindowHandle> focusedWindowHandle =
1275 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1276 sp<InputApplicationHandle> focusedApplicationHandle =
1277 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1278
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 // If there is no currently focused window and no focused application
1280 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001281 if (focusedWindowHandle == nullptr) {
1282 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001283 injectionResult =
1284 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1285 nullptr, nextWakeupTime,
1286 "Waiting because no window has focus but there is "
1287 "a focused application that may eventually add a "
1288 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289 goto Unresponsive;
1290 }
1291
Arthur Hung3b413f22018-10-26 18:05:34 +08001292 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001293 "%" PRId32 ".",
1294 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1296 goto Failed;
1297 }
1298
1299 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001300 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1302 goto Failed;
1303 }
1304
Jeff Brownffb49772014-10-10 19:01:34 -07001305 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001306 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001307 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001308 injectionResult =
1309 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1310 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311 goto Unresponsive;
1312 }
1313
1314 // Success! Output targets.
1315 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001316 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001317 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1318 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319
1320 // Done.
1321Failed:
1322Unresponsive:
1323 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001324 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001325 if (DEBUG_FOCUS) {
1326 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1327 "timeSpentWaitingForApplication=%0.1fms",
1328 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 return injectionResult;
1331}
1332
1333int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001334 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001335 std::vector<InputTarget>& inputTargets,
1336 nsecs_t* nextWakeupTime,
1337 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001338 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 enum InjectionPermission {
1340 INJECTION_PERMISSION_UNKNOWN,
1341 INJECTION_PERMISSION_GRANTED,
1342 INJECTION_PERMISSION_DENIED
1343 };
1344
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 // For security reasons, we defer updating the touch state until we are sure that
1346 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001347 int32_t displayId = entry.displayId;
1348 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1350
1351 // Update the touch state as needed based on the properties of the touch event.
1352 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1353 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1354 sp<InputWindowHandle> newHoverWindowHandle;
1355
Jeff Brownf086ddb2014-02-11 14:28:48 -08001356 // Copy current touch state into mTempTouchState.
1357 // This state is always reset at the end of this function, so if we don't find state
1358 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001359 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001360 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1361 if (oldStateIndex >= 0) {
1362 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1363 mTempTouchState.copyFrom(*oldState);
1364 }
1365
1366 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001367 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001368 (mTempTouchState.deviceId != entry.deviceId || mTempTouchState.source != entry.source ||
1369 mTempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001370 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1371 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1372 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1373 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1374 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001375 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 bool wrongDevice = false;
1377 if (newGesture) {
1378 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001379 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001380 if (DEBUG_FOCUS) {
1381 ALOGD("Dropping event because a pointer for a different device is already down "
1382 "in display %" PRId32,
1383 displayId);
1384 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001385 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1387 switchedDevice = false;
1388 wrongDevice = true;
1389 goto Failed;
1390 }
1391 mTempTouchState.reset();
1392 mTempTouchState.down = down;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001393 mTempTouchState.deviceId = entry.deviceId;
1394 mTempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 mTempTouchState.displayId = displayId;
1396 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001397 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001398 if (DEBUG_FOCUS) {
1399 ALOGI("Dropping move event because a pointer for a different device is already active "
1400 "in display %" PRId32,
1401 displayId);
1402 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001403 // TODO: test multiple simultaneous input streams.
1404 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1405 switchedDevice = false;
1406 wrongDevice = true;
1407 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 }
1409
1410 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1411 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1412
Garfield Tan00f511d2019-06-12 16:55:40 -07001413 int32_t x;
1414 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001416 // Always dispatch mouse events to cursor position.
1417 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001418 x = int32_t(entry.xCursorPosition);
1419 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001420 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001421 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1422 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001423 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001424 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001425 sp<InputWindowHandle> newTouchedWindowHandle =
1426 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1427 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001428
1429 std::vector<TouchedMonitor> newGestureMonitors = isDown
1430 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1431 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001434 if (newTouchedWindowHandle != nullptr &&
1435 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001436 // New window supports splitting, but we should never split mouse events.
1437 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 } else if (isSplit) {
1439 // New window does not support splitting but we have already split events.
1440 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001441 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 }
1443
1444 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001445 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 // Try to assign the pointer to the first foreground window we find, if there is one.
1447 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001448 }
1449
1450 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1451 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001452 "(%d, %d) in display %" PRId32 ".",
1453 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001454 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1455 goto Failed;
1456 }
1457
1458 if (newTouchedWindowHandle != nullptr) {
1459 // Set target flags.
1460 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1461 if (isSplit) {
1462 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001464 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1465 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1466 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1467 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1468 }
1469
1470 // Update hover state.
1471 if (isHoverAction) {
1472 newHoverWindowHandle = newTouchedWindowHandle;
1473 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1474 newHoverWindowHandle = mLastHoverWindowHandle;
1475 }
1476
1477 // Update the temporary touch state.
1478 BitSet32 pointerIds;
1479 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001480 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001481 pointerIds.markBit(pointerId);
1482 }
1483 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 }
1485
Michael Wright3dd60e22019-03-27 22:06:44 +00001486 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 } else {
1488 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1489
1490 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001491 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001492 if (DEBUG_FOCUS) {
1493 ALOGD("Dropping event because the pointer is not down or we previously "
1494 "dropped the pointer down event in display %" PRId32,
1495 displayId);
1496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1498 goto Failed;
1499 }
1500
1501 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001502 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001503 mTempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001504 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1505 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506
1507 sp<InputWindowHandle> oldTouchedWindowHandle =
1508 mTempTouchState.getFirstForegroundWindowHandle();
1509 sp<InputWindowHandle> newTouchedWindowHandle =
1510 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001511 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1512 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001513 if (DEBUG_FOCUS) {
1514 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1515 oldTouchedWindowHandle->getName().c_str(),
1516 newTouchedWindowHandle->getName().c_str(), displayId);
1517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 // Make a slippery exit from the old window.
1519 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001520 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1521 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522
1523 // Make a slippery entrance into the new window.
1524 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1525 isSplit = true;
1526 }
1527
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001528 int32_t targetFlags =
1529 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 if (isSplit) {
1531 targetFlags |= InputTarget::FLAG_SPLIT;
1532 }
1533 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1534 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1535 }
1536
1537 BitSet32 pointerIds;
1538 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001539 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 }
1541 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1542 }
1543 }
1544 }
1545
1546 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1547 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001548 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549#if DEBUG_HOVER
1550 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001551 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552#endif
1553 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001554 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1555 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556 }
1557
1558 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001559 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560#if DEBUG_HOVER
1561 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001562 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563#endif
1564 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001565 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1566 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 }
1568 }
1569
1570 // Check permission to inject into all touched foreground windows and ensure there
1571 // is at least one touched foreground window.
1572 {
1573 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001574 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1576 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001577 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1579 injectionPermission = INJECTION_PERMISSION_DENIED;
1580 goto Failed;
1581 }
1582 }
1583 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001584 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1585 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001586 if (DEBUG_FOCUS) {
1587 ALOGD("Dropping event because there is no touched foreground window in display "
1588 "%" PRId32 " or gesture monitor to receive it.",
1589 displayId);
1590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1592 goto Failed;
1593 }
1594
1595 // Permission granted to injection into all touched foreground windows.
1596 injectionPermission = INJECTION_PERMISSION_GRANTED;
1597 }
1598
1599 // Check whether windows listening for outside touches are owned by the same UID. If it is
1600 // set the policy flag that we will not reveal coordinate information to this window.
1601 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1602 sp<InputWindowHandle> foregroundWindowHandle =
1603 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001604 if (foregroundWindowHandle) {
1605 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1606 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1607 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1608 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1609 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1610 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001611 InputTarget::FLAG_ZERO_COORDS,
1612 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 }
1615 }
1616 }
1617 }
1618
1619 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001620 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001622 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001623 std::string reason =
1624 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1625 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001626 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001627 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1628 touchedWindow.windowHandle,
1629 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 goto Unresponsive;
1631 }
1632 }
1633 }
1634
1635 // If this is the first pointer going down and the touched window has a wallpaper
1636 // then also add the touched wallpaper windows so they are locked in for the duration
1637 // of the touch gesture.
1638 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1639 // engine only supports touch events. We would need to add a mechanism similar
1640 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1641 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1642 sp<InputWindowHandle> foregroundWindowHandle =
1643 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001644 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001645 const std::vector<sp<InputWindowHandle>> windowHandles =
1646 getWindowHandlesLocked(displayId);
1647 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001649 if (info->displayId == displayId &&
1650 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1651 mTempTouchState
1652 .addOrUpdateWindow(windowHandle,
1653 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1654 InputTarget::
1655 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1656 InputTarget::FLAG_DISPATCH_AS_IS,
1657 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 }
1659 }
1660 }
1661 }
1662
1663 // Success! Output targets.
1664 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1665
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001666 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001668 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 }
1670
Michael Wright3dd60e22019-03-27 22:06:44 +00001671 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1672 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001673 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001674 }
1675
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 // Drop the outside or hover touch windows since we will not care about them
1677 // in the next iteration.
1678 mTempTouchState.filterNonAsIsTouchWindows();
1679
1680Failed:
1681 // Check injection permission once and for all.
1682 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001683 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 injectionPermission = INJECTION_PERMISSION_GRANTED;
1685 } else {
1686 injectionPermission = INJECTION_PERMISSION_DENIED;
1687 }
1688 }
1689
1690 // Update final pieces of touch state if the injector had permission.
1691 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1692 if (!wrongDevice) {
1693 if (switchedDevice) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001694 if (DEBUG_FOCUS) {
1695 ALOGD("Conflicting pointer actions: Switched to a different device.");
1696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 *outConflictingPointerActions = true;
1698 }
1699
1700 if (isHoverAction) {
1701 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001702 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001703 if (DEBUG_FOCUS) {
1704 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1705 "down.");
1706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 *outConflictingPointerActions = true;
1708 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001709 mTempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001710 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1711 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001712 mTempTouchState.deviceId = entry.deviceId;
1713 mTempTouchState.source = entry.source;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001714 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001716 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1717 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001719 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1721 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001722 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001723 if (DEBUG_FOCUS) {
1724 ALOGD("Conflicting pointer actions: Down received while already down.");
1725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 *outConflictingPointerActions = true;
1727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1729 // One pointer went up.
1730 if (isSplit) {
1731 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001732 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001734 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001735 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1737 touchedWindow.pointerIds.clearBit(pointerId);
1738 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001739 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 continue;
1741 }
1742 }
1743 i += 1;
1744 }
1745 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001746 }
1747
1748 // Save changes unless the action was scroll in which case the temporary touch
1749 // state was only valid for this one action.
1750 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1751 if (mTempTouchState.displayId >= 0) {
1752 if (oldStateIndex >= 0) {
1753 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1754 } else {
1755 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1756 }
1757 } else if (oldStateIndex >= 0) {
1758 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1759 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760 }
1761
1762 // Update hover state.
1763 mLastHoverWindowHandle = newHoverWindowHandle;
1764 }
1765 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001766 if (DEBUG_FOCUS) {
1767 ALOGD("Not updating touch focus because injection was denied.");
1768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769 }
1770
1771Unresponsive:
1772 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1773 mTempTouchState.reset();
1774
1775 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001776 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001777 if (DEBUG_FOCUS) {
1778 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1779 "timeSpentWaitingForApplication=%0.1fms",
1780 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 return injectionResult;
1783}
1784
1785void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001786 int32_t targetFlags, BitSet32 pointerIds,
1787 std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001788 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1789 if (inputChannel == nullptr) {
1790 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1791 return;
1792 }
1793
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001795 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001796 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 target.flags = targetFlags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001798 target.xOffset = -windowInfo->frameLeft;
1799 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001800 target.globalScaleFactor = windowInfo->globalScaleFactor;
1801 target.windowXScale = windowInfo->windowXScale;
1802 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001804 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805}
1806
Michael Wright3dd60e22019-03-27 22:06:44 +00001807void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001808 int32_t displayId, float xOffset,
1809 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001810 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1811 mGlobalMonitorsByDisplay.find(displayId);
1812
1813 if (it != mGlobalMonitorsByDisplay.end()) {
1814 const std::vector<Monitor>& monitors = it->second;
1815 for (const Monitor& monitor : monitors) {
1816 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 }
1819}
1820
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001821void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1822 float yOffset,
1823 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001824 InputTarget target;
1825 target.inputChannel = monitor.inputChannel;
1826 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1827 target.xOffset = xOffset;
1828 target.yOffset = yOffset;
1829 target.pointerIds.clear();
1830 target.globalScaleFactor = 1.0f;
1831 inputTargets.push_back(target);
1832}
1833
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001835 const InjectionState* injectionState) {
1836 if (injectionState &&
1837 (windowHandle == nullptr ||
1838 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1839 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001840 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001842 "owned by uid %d",
1843 injectionState->injectorPid, injectionState->injectorUid,
1844 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 } else {
1846 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001847 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 }
1849 return false;
1850 }
1851 return true;
1852}
1853
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001854bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1855 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001857 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1858 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 if (otherHandle == windowHandle) {
1860 break;
1861 }
1862
1863 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001864 if (otherInfo->displayId == displayId && otherInfo->visible &&
1865 !otherInfo->isTrustedOverlay() && otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 return true;
1867 }
1868 }
1869 return false;
1870}
1871
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001872bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1873 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001874 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001875 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001876 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001877 if (otherHandle == windowHandle) {
1878 break;
1879 }
1880
1881 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001882 if (otherInfo->displayId == displayId && otherInfo->visible &&
1883 !otherInfo->isTrustedOverlay() && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001884 return true;
1885 }
1886 }
1887 return false;
1888}
1889
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001890std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
1891 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001892 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07001893 // If the window is paused then keep waiting.
1894 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001895 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001896 }
1897
1898 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001899 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001900 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001901 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001902 "registered with the input dispatcher. The window may be in the "
1903 "process of being removed.",
1904 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001905 }
1906
1907 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07001908 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001909 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001910 "The window may be in the process of being removed.",
1911 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07001912 }
1913
1914 // If the connection is backed up then keep waiting.
1915 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001916 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001917 "Outbound queue length: %zu. Wait queue length: %zu.",
1918 targetType, connection->outboundQueue.size(),
1919 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07001920 }
1921
1922 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001923 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07001924 // If the event is a key event, then we must wait for all previous events to
1925 // complete before delivering it because previous events may have the
1926 // side-effect of transferring focus to a different window and we want to
1927 // ensure that the following keys are sent to the new window.
1928 //
1929 // Suppose the user touches a button in a window then immediately presses "A".
1930 // If the button causes a pop-up window to appear then we want to ensure that
1931 // the "A" key is delivered to the new pop-up window. This is because users
1932 // often anticipate pending UI changes when typing on a keyboard.
1933 // To obtain this behavior, we must serialize key events with respect to all
1934 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001935 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001936 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001937 "finished processing all of the input events that were previously "
1938 "delivered to it. Outbound queue length: %zu. Wait queue length: "
1939 "%zu.",
1940 targetType, connection->outboundQueue.size(),
1941 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942 }
Jeff Brownffb49772014-10-10 19:01:34 -07001943 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 // Touch events can always be sent to a window immediately because the user intended
1945 // to touch whatever was visible at the time. Even if focus changes or a new
1946 // window appears moments later, the touch event was meant to be delivered to
1947 // whatever window happened to be on screen at the time.
1948 //
1949 // Generic motion events, such as trackball or joystick events are a little trickier.
1950 // Like key events, generic motion events are delivered to the focused window.
1951 // Unlike key events, generic motion events don't tend to transfer focus to other
1952 // windows and it is not important for them to be serialized. So we prefer to deliver
1953 // generic motion events as soon as possible to improve efficiency and reduce lag
1954 // through batching.
1955 //
1956 // The one case where we pause input event delivery is when the wait queue is piling
1957 // up with lots of events because the application is not responding.
1958 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001959 if (!connection->waitQueue.empty() &&
1960 currentTime >=
1961 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001962 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001963 "finished processing certain input events that were delivered to "
1964 "it over "
1965 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
1966 "%0.1fms.",
1967 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1968 connection->waitQueue.size(),
1969 (currentTime - connection->waitQueue.front()->deliveryTime) *
1970 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 }
1972 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001973 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974}
1975
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001976std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 const sp<InputApplicationHandle>& applicationHandle,
1978 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001979 if (applicationHandle != nullptr) {
1980 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001981 std::string label(applicationHandle->getName());
1982 label += " - ";
1983 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 return label;
1985 } else {
1986 return applicationHandle->getName();
1987 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001988 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 return windowHandle->getName();
1990 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001991 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 }
1993}
1994
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001995void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001996 int32_t displayId = getTargetDisplayId(eventEntry);
1997 sp<InputWindowHandle> focusedWindowHandle =
1998 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1999 if (focusedWindowHandle != nullptr) {
2000 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2002#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002003 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004#endif
2005 return;
2006 }
2007 }
2008
2009 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002010 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002011 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002012 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2013 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002014 return;
2015 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002017 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002018 eventType = USER_ACTIVITY_EVENT_TOUCH;
2019 }
2020 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002022 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002023 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2024 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002025 return;
2026 }
2027 eventType = USER_ACTIVITY_EVENT_BUTTON;
2028 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002030 case EventEntry::Type::CONFIGURATION_CHANGED:
2031 case EventEntry::Type::DEVICE_RESET: {
2032 LOG_ALWAYS_FATAL("%s events are not user activity",
2033 EventEntry::typeToString(eventEntry.type));
2034 break;
2035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036 }
2037
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002038 std::unique_ptr<CommandEntry> commandEntry =
2039 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002040 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002041 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002042 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043}
2044
2045void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002046 const sp<Connection>& connection,
2047 EventEntry* eventEntry,
2048 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002049 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002050 std::string message =
2051 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
2052 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002053 ATRACE_NAME(message.c_str());
2054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055#if DEBUG_DISPATCH_CYCLE
2056 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002057 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
2058 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
2059 connection->getInputChannelName().c_str(), inputTarget->flags, inputTarget->xOffset,
2060 inputTarget->yOffset, inputTarget->globalScaleFactor, inputTarget->windowXScale,
2061 inputTarget->windowYScale, inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062#endif
2063
2064 // Skip this event if the connection status is not normal.
2065 // We don't want to enqueue additional outbound events if the connection is broken.
2066 if (connection->status != Connection::STATUS_NORMAL) {
2067#if DEBUG_DISPATCH_CYCLE
2068 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002069 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070#endif
2071 return;
2072 }
2073
2074 // Split a motion event if needed.
2075 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002076 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002078 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
2079 if (inputTarget->pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002080 MotionEntry* splitMotionEntry =
2081 splitMotionEvent(originalMotionEntry, inputTarget->pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 if (!splitMotionEntry) {
2083 return; // split event was dropped
2084 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002085 if (DEBUG_FOCUS) {
2086 ALOGD("channel '%s' ~ Split motion event.",
2087 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002088 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002089 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002090 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 splitMotionEntry->release();
2092 return;
2093 }
2094 }
2095
2096 // Not splitting. Enqueue dispatch entries for the event as is.
2097 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2098}
2099
2100void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002101 const sp<Connection>& connection,
2102 EventEntry* eventEntry,
2103 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002104 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002105 std::string message =
2106 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32
2107 ")",
2108 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002109 ATRACE_NAME(message.c_str());
2110 }
2111
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002112 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113
2114 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002115 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002116 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002117 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002118 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002119 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002120 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002121 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002122 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002123 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002124 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002125 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002126 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127
2128 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002129 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 startDispatchCycleLocked(currentTime, connection);
2131 }
2132}
2133
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002134void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2135 EventEntry* eventEntry,
2136 const InputTarget* inputTarget,
2137 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002138 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002139 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2140 connection->getInputChannelName().c_str(),
2141 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002142 ATRACE_NAME(message.c_str());
2143 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 int32_t inputTargetFlags = inputTarget->flags;
2145 if (!(inputTargetFlags & dispatchMode)) {
2146 return;
2147 }
2148 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2149
2150 // This is a new event.
2151 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002152 DispatchEntry* dispatchEntry =
2153 new DispatchEntry(eventEntry, // increments ref
2154 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
2155 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2156 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157
2158 // Apply target flags and update the connection's input state.
2159 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002160 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002161 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
2162 dispatchEntry->resolvedAction = keyEntry.action;
2163 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002165 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2166 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002168 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2169 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002171 delete dispatchEntry;
2172 return; // skip the inconsistent event
2173 }
2174 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002177 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002178 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002179 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2180 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2181 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2182 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2183 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2184 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2185 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2186 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2187 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2188 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2189 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002190 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002191 }
2192 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002193 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2194 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002196 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2197 "event",
2198 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002200 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002203 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002204 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2205 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2206 }
2207 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2208 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2209 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002211 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2212 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002214 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2215 "event",
2216 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002218 delete dispatchEntry;
2219 return; // skip the inconsistent event
2220 }
2221
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002222 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002223 inputTarget->inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002224
2225 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002227 case EventEntry::Type::CONFIGURATION_CHANGED:
2228 case EventEntry::Type::DEVICE_RESET: {
2229 LOG_ALWAYS_FATAL("%s events should not go to apps",
2230 EventEntry::typeToString(eventEntry->type));
2231 break;
2232 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 }
2234
2235 // Remember that we are waiting for this dispatch to complete.
2236 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002237 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 }
2239
2240 // Enqueue the dispatch entry.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002241 connection->outboundQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002242 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002243}
2244
chaviwfd6d3512019-03-25 13:23:49 -07002245void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002246 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002247 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002248 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2249 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002250 return;
2251 }
2252
2253 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2254 if (inputWindowHandle == nullptr) {
2255 return;
2256 }
2257
chaviw8c9cf542019-03-25 13:02:48 -07002258 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002259 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002260
2261 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2262
2263 if (!hasFocusChanged) {
2264 return;
2265 }
2266
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002267 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2268 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002269 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002270 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271}
2272
2273void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002274 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002275 if (ATRACE_ENABLED()) {
2276 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002277 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002278 ATRACE_NAME(message.c_str());
2279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002281 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282#endif
2283
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002284 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2285 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 dispatchEntry->deliveryTime = currentTime;
2287
2288 // Publish the event.
2289 status_t status;
2290 EventEntry* eventEntry = dispatchEntry->eventEntry;
2291 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002292 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002293 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 // Publish the key event.
2296 status = connection->inputPublisher
2297 .publishKeyEvent(dispatchEntry->seq, keyEntry->deviceId,
2298 keyEntry->source, keyEntry->displayId,
2299 dispatchEntry->resolvedAction,
2300 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2301 keyEntry->scanCode, keyEntry->metaState,
2302 keyEntry->repeatCount, keyEntry->downTime,
2303 keyEntry->eventTime);
2304 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 }
2306
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002307 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002308 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002310 PointerCoords scaledCoords[MAX_POINTERS];
2311 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2312
2313 // Set the X and Y offset depending on the input source.
2314 float xOffset, yOffset;
2315 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2316 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2317 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2318 float wxs = dispatchEntry->windowXScale;
2319 float wys = dispatchEntry->windowYScale;
2320 xOffset = dispatchEntry->xOffset * wxs;
2321 yOffset = dispatchEntry->yOffset * wys;
2322 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
2323 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2324 scaledCoords[i] = motionEntry->pointerCoords[i];
2325 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
2326 }
2327 usingCoords = scaledCoords;
2328 }
2329 } else {
2330 xOffset = 0.0f;
2331 yOffset = 0.0f;
2332
2333 // We don't want the dispatch target to know.
2334 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2335 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2336 scaledCoords[i].clear();
2337 }
2338 usingCoords = scaledCoords;
2339 }
2340 }
2341
2342 // Publish the motion event.
2343 status = connection->inputPublisher
2344 .publishMotionEvent(dispatchEntry->seq, motionEntry->deviceId,
2345 motionEntry->source, motionEntry->displayId,
2346 dispatchEntry->resolvedAction,
2347 motionEntry->actionButton,
2348 dispatchEntry->resolvedFlags,
2349 motionEntry->edgeFlags, motionEntry->metaState,
2350 motionEntry->buttonState,
2351 motionEntry->classification, xOffset, yOffset,
2352 motionEntry->xPrecision,
2353 motionEntry->yPrecision,
2354 motionEntry->xCursorPosition,
2355 motionEntry->yCursorPosition,
2356 motionEntry->downTime, motionEntry->eventTime,
2357 motionEntry->pointerCount,
2358 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002359 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002360 break;
2361 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002362 case EventEntry::Type::CONFIGURATION_CHANGED:
2363 case EventEntry::Type::DEVICE_RESET: {
2364 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2365 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002366 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368 }
2369
2370 // Check the result.
2371 if (status) {
2372 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002373 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002375 "This is unexpected because the wait queue is empty, so the pipe "
2376 "should be empty and we shouldn't have any problems writing an "
2377 "event to it, status=%d",
2378 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2380 } else {
2381 // Pipe is full and we are waiting for the app to finish process some events
2382 // before sending more events to it.
2383#if DEBUG_DISPATCH_CYCLE
2384 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002385 "waiting for the application to catch up",
2386 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387#endif
2388 connection->inputPublisherBlocked = true;
2389 }
2390 } else {
2391 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002392 "status=%d",
2393 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2395 }
2396 return;
2397 }
2398
2399 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002400 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2401 connection->outboundQueue.end(),
2402 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002403 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002404 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002405 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 }
2407}
2408
2409void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002410 const sp<Connection>& connection, uint32_t seq,
2411 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412#if DEBUG_DISPATCH_CYCLE
2413 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002414 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415#endif
2416
2417 connection->inputPublisherBlocked = false;
2418
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002419 if (connection->status == Connection::STATUS_BROKEN ||
2420 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 return;
2422 }
2423
2424 // Notify other system components and prepare to start the next dispatch cycle.
2425 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2426}
2427
2428void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002429 const sp<Connection>& connection,
2430 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431#if DEBUG_DISPATCH_CYCLE
2432 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002433 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434#endif
2435
2436 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002437 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002438 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002439 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002440 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441
2442 // The connection appears to be unrecoverably broken.
2443 // Ignore already broken or zombie connections.
2444 if (connection->status == Connection::STATUS_NORMAL) {
2445 connection->status = Connection::STATUS_BROKEN;
2446
2447 if (notify) {
2448 // Notify other system components.
2449 onDispatchCycleBrokenLocked(currentTime, connection);
2450 }
2451 }
2452}
2453
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002454void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2455 while (!queue.empty()) {
2456 DispatchEntry* dispatchEntry = queue.front();
2457 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002458 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459 }
2460}
2461
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002462void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002464 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 }
2466 delete dispatchEntry;
2467}
2468
2469int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2470 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2471
2472 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002473 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002475 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002477 "fd=%d, events=0x%x",
2478 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 return 0; // remove the callback
2480 }
2481
2482 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002483 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2485 if (!(events & ALOOPER_EVENT_INPUT)) {
2486 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002487 "events=0x%x",
2488 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 return 1;
2490 }
2491
2492 nsecs_t currentTime = now();
2493 bool gotOne = false;
2494 status_t status;
2495 for (;;) {
2496 uint32_t seq;
2497 bool handled;
2498 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2499 if (status) {
2500 break;
2501 }
2502 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2503 gotOne = true;
2504 }
2505 if (gotOne) {
2506 d->runCommandsLockedInterruptible();
2507 if (status == WOULD_BLOCK) {
2508 return 1;
2509 }
2510 }
2511
2512 notify = status != DEAD_OBJECT || !connection->monitor;
2513 if (notify) {
2514 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002515 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 }
2517 } else {
2518 // Monitor channels are never explicitly unregistered.
2519 // We do it automatically when the remote endpoint is closed so don't warn
2520 // about them.
2521 notify = !connection->monitor;
2522 if (notify) {
2523 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002524 "events=0x%x",
2525 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 }
2527 }
2528
2529 // Unregister the channel.
2530 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2531 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002532 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533}
2534
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002535void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002537 for (const auto& pair : mConnectionsByFd) {
2538 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539 }
2540}
2541
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002542void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002543 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002544 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2545 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2546}
2547
2548void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2549 const CancelationOptions& options,
2550 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2551 for (const auto& it : monitorsByDisplay) {
2552 const std::vector<Monitor>& monitors = it.second;
2553 for (const Monitor& monitor : monitors) {
2554 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002555 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002556 }
2557}
2558
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2560 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002561 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002562 if (connection == nullptr) {
2563 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002565
2566 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567}
2568
2569void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2570 const sp<Connection>& connection, const CancelationOptions& options) {
2571 if (connection->status == Connection::STATUS_BROKEN) {
2572 return;
2573 }
2574
2575 nsecs_t currentTime = now();
2576
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002577 std::vector<EventEntry*> cancelationEvents =
2578 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002580 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002582 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002583 "with reality: %s, mode=%d.",
2584 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2585 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586#endif
2587 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002588 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 switch (cancelationEventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002590 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002591 logOutboundKeyDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002592 static_cast<const KeyEntry&>(*cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002593 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002594 }
2595 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002596 logOutboundMotionDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002597 static_cast<const MotionEntry&>(
2598 *cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002599 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002600 }
2601 case EventEntry::Type::CONFIGURATION_CHANGED:
2602 case EventEntry::Type::DEVICE_RESET: {
2603 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2604 EventEntry::typeToString(cancelationEventEntry->type));
2605 break;
2606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 }
2608
2609 InputTarget target;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002610 sp<InputWindowHandle> windowHandle =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002611 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002612 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2614 target.xOffset = -windowInfo->frameLeft;
2615 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002616 target.globalScaleFactor = windowInfo->globalScaleFactor;
2617 target.windowXScale = windowInfo->windowXScale;
2618 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 } else {
2620 target.xOffset = 0;
2621 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002622 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 }
2624 target.inputChannel = connection->inputChannel;
2625 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2626
chaviw8c9cf542019-03-25 13:02:48 -07002627 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002628 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629
2630 cancelationEventEntry->release();
2631 }
2632
2633 startDispatchCycleLocked(currentTime, connection);
2634 }
2635}
2636
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002637MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002638 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639 ALOG_ASSERT(pointerIds.value != 0);
2640
2641 uint32_t splitPointerIndexMap[MAX_POINTERS];
2642 PointerProperties splitPointerProperties[MAX_POINTERS];
2643 PointerCoords splitPointerCoords[MAX_POINTERS];
2644
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002645 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 uint32_t splitPointerCount = 0;
2647
2648 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002649 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002651 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652 uint32_t pointerId = uint32_t(pointerProperties.id);
2653 if (pointerIds.hasBit(pointerId)) {
2654 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2655 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2656 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002657 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658 splitPointerCount += 1;
2659 }
2660 }
2661
2662 if (splitPointerCount != pointerIds.count()) {
2663 // This is bad. We are missing some of the pointers that we expected to deliver.
2664 // Most likely this indicates that we received an ACTION_MOVE events that has
2665 // different pointer ids than we expected based on the previous ACTION_DOWN
2666 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2667 // in this way.
2668 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002669 "we expected there to be %d pointers. This probably means we received "
2670 "a broken sequence of pointer ids from the input device.",
2671 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002672 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673 }
2674
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002675 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002677 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2678 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2680 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002681 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 uint32_t pointerId = uint32_t(pointerProperties.id);
2683 if (pointerIds.hasBit(pointerId)) {
2684 if (pointerIds.count() == 1) {
2685 // The first/last pointer went down/up.
2686 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002687 ? AMOTION_EVENT_ACTION_DOWN
2688 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 } else {
2690 // A secondary pointer went down/up.
2691 uint32_t splitPointerIndex = 0;
2692 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2693 splitPointerIndex += 1;
2694 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002695 action = maskedAction |
2696 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 }
2698 } else {
2699 // An unrelated pointer changed.
2700 action = AMOTION_EVENT_ACTION_MOVE;
2701 }
2702 }
2703
Garfield Tan00f511d2019-06-12 16:55:40 -07002704 MotionEntry* splitMotionEntry =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002705 new MotionEntry(originalMotionEntry.sequenceNum, originalMotionEntry.eventTime,
2706 originalMotionEntry.deviceId, originalMotionEntry.source,
2707 originalMotionEntry.displayId, originalMotionEntry.policyFlags, action,
2708 originalMotionEntry.actionButton, originalMotionEntry.flags,
2709 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2710 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2711 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2712 originalMotionEntry.xCursorPosition,
2713 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002714 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002716 if (originalMotionEntry.injectionState) {
2717 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718 splitMotionEntry->injectionState->refCount += 1;
2719 }
2720
2721 return splitMotionEntry;
2722}
2723
2724void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2725#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002726 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727#endif
2728
2729 bool needWake;
2730 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002731 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732
Prabir Pradhan42611e02018-11-27 14:04:02 -08002733 ConfigurationChangedEntry* newEntry =
2734 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735 needWake = enqueueInboundEventLocked(newEntry);
2736 } // release lock
2737
2738 if (needWake) {
2739 mLooper->wake();
2740 }
2741}
2742
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002743/**
2744 * If one of the meta shortcuts is detected, process them here:
2745 * Meta + Backspace -> generate BACK
2746 * Meta + Enter -> generate HOME
2747 * This will potentially overwrite keyCode and metaState.
2748 */
2749void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002750 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002751 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2752 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2753 if (keyCode == AKEYCODE_DEL) {
2754 newKeyCode = AKEYCODE_BACK;
2755 } else if (keyCode == AKEYCODE_ENTER) {
2756 newKeyCode = AKEYCODE_HOME;
2757 }
2758 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002759 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002760 struct KeyReplacement replacement = {keyCode, deviceId};
2761 mReplacedKeys.add(replacement, newKeyCode);
2762 keyCode = newKeyCode;
2763 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2764 }
2765 } else if (action == AKEY_EVENT_ACTION_UP) {
2766 // In order to maintain a consistent stream of up and down events, check to see if the key
2767 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2768 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002769 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002770 struct KeyReplacement replacement = {keyCode, deviceId};
2771 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2772 if (index >= 0) {
2773 keyCode = mReplacedKeys.valueAt(index);
2774 mReplacedKeys.removeItemsAt(index);
2775 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2776 }
2777 }
2778}
2779
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2781#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002782 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2783 "policyFlags=0x%x, action=0x%x, "
2784 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2785 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2786 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2787 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788#endif
2789 if (!validateKeyEvent(args->action)) {
2790 return;
2791 }
2792
2793 uint32_t policyFlags = args->policyFlags;
2794 int32_t flags = args->flags;
2795 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002796 // InputDispatcher tracks and generates key repeats on behalf of
2797 // whatever notifies it, so repeatCount should always be set to 0
2798 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002799 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2800 policyFlags |= POLICY_FLAG_VIRTUAL;
2801 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803 if (policyFlags & POLICY_FLAG_FUNCTION) {
2804 metaState |= AMETA_FUNCTION_ON;
2805 }
2806
2807 policyFlags |= POLICY_FLAG_TRUSTED;
2808
Michael Wright78f24442014-08-06 15:55:28 -07002809 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002810 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002811
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 KeyEvent event;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002813 event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2814 args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815
Michael Wright2b3c3302018-03-02 17:19:13 +00002816 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002818 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2819 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002820 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 bool needWake;
2824 { // acquire lock
2825 mLock.lock();
2826
2827 if (shouldSendKeyToInputFilterLocked(args)) {
2828 mLock.unlock();
2829
2830 policyFlags |= POLICY_FLAG_FILTERED;
2831 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2832 return; // event was consumed by the filter
2833 }
2834
2835 mLock.lock();
2836 }
2837
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002838 KeyEntry* newEntry =
2839 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2840 args->displayId, policyFlags, args->action, flags, keyCode,
2841 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842
2843 needWake = enqueueInboundEventLocked(newEntry);
2844 mLock.unlock();
2845 } // release lock
2846
2847 if (needWake) {
2848 mLooper->wake();
2849 }
2850}
2851
2852bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2853 return mInputFilterEnabled;
2854}
2855
2856void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2857#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002858 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan00f511d2019-06-12 16:55:40 -07002859 ", policyFlags=0x%x, "
2860 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
2861 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07002862 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan00f511d2019-06-12 16:55:40 -07002863 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2864 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Jaewan Kim372fbe42019-10-02 10:58:46 +09002865 args->edgeFlags, args->xPrecision, args->yPrecision, args->xCursorPosition,
Garfield Tan00f511d2019-06-12 16:55:40 -07002866 args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 for (uint32_t i = 0; i < args->pointerCount; i++) {
2868 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002869 "x=%f, y=%f, pressure=%f, size=%f, "
2870 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2871 "orientation=%f",
2872 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2873 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2874 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2875 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2876 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2877 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2878 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2879 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2880 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2881 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882 }
2883#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002884 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2885 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886 return;
2887 }
2888
2889 uint32_t policyFlags = args->policyFlags;
2890 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002891
2892 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002893 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002894 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2895 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002896 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898
2899 bool needWake;
2900 { // acquire lock
2901 mLock.lock();
2902
2903 if (shouldSendMotionToInputFilterLocked(args)) {
2904 mLock.unlock();
2905
2906 MotionEvent event;
Garfield Tan00f511d2019-06-12 16:55:40 -07002907 event.initialize(args->deviceId, args->source, args->displayId, args->action,
2908 args->actionButton, args->flags, args->edgeFlags, args->metaState,
2909 args->buttonState, args->classification, 0, 0, args->xPrecision,
2910 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2911 args->downTime, args->eventTime, args->pointerCount,
2912 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913
2914 policyFlags |= POLICY_FLAG_FILTERED;
2915 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2916 return; // event was consumed by the filter
2917 }
2918
2919 mLock.lock();
2920 }
2921
2922 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07002923 MotionEntry* newEntry =
2924 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2925 args->displayId, policyFlags, args->action, args->actionButton,
2926 args->flags, args->metaState, args->buttonState,
2927 args->classification, args->edgeFlags, args->xPrecision,
2928 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2929 args->downTime, args->pointerCount, args->pointerProperties,
2930 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931
2932 needWake = enqueueInboundEventLocked(newEntry);
2933 mLock.unlock();
2934 } // release lock
2935
2936 if (needWake) {
2937 mLooper->wake();
2938 }
2939}
2940
2941bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002942 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943}
2944
2945void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2946#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002947 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 "switchMask=0x%08x",
2949 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950#endif
2951
2952 uint32_t policyFlags = args->policyFlags;
2953 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002954 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955}
2956
2957void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2958#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
2960 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961#endif
2962
2963 bool needWake;
2964 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002965 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002966
Prabir Pradhan42611e02018-11-27 14:04:02 -08002967 DeviceResetEntry* newEntry =
2968 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969 needWake = enqueueInboundEventLocked(newEntry);
2970 } // release lock
2971
2972 if (needWake) {
2973 mLooper->wake();
2974 }
2975}
2976
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002977int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
2978 int32_t injectorUid, int32_t syncMode,
2979 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980#if DEBUG_INBOUND_EVENT_DETAILS
2981 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002982 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2983 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002984#endif
2985
2986 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2987
2988 policyFlags |= POLICY_FLAG_INJECTED;
2989 if (hasInjectionPermission(injectorPid, injectorUid)) {
2990 policyFlags |= POLICY_FLAG_TRUSTED;
2991 }
2992
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07002993 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002995 case AINPUT_EVENT_TYPE_KEY: {
2996 KeyEvent keyEvent;
2997 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2998 int32_t action = keyEvent.getAction();
2999 if (!validateKeyEvent(action)) {
3000 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003003 int32_t flags = keyEvent.getFlags();
3004 int32_t keyCode = keyEvent.getKeyCode();
3005 int32_t metaState = keyEvent.getMetaState();
3006 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
3007 /*byref*/ keyCode, /*byref*/ metaState);
3008 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
3009 keyEvent.getDisplayId(), action, flags, keyCode,
3010 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
3011 keyEvent.getDownTime(), keyEvent.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003013 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3014 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003015 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003016
3017 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3018 android::base::Timer t;
3019 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3020 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3021 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3022 std::to_string(t.duration().count()).c_str());
3023 }
3024 }
3025
3026 mLock.lock();
3027 KeyEntry* injectedEntry =
3028 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
3029 keyEvent.getDeviceId(), keyEvent.getSource(),
3030 keyEvent.getDisplayId(), policyFlags, action, flags,
3031 keyEvent.getKeyCode(), keyEvent.getScanCode(),
3032 keyEvent.getMetaState(), keyEvent.getRepeatCount(),
3033 keyEvent.getDownTime());
3034 injectedEntries.push(injectedEntry);
3035 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036 }
3037
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003038 case AINPUT_EVENT_TYPE_MOTION: {
3039 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3040 int32_t action = motionEvent->getAction();
3041 size_t pointerCount = motionEvent->getPointerCount();
3042 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3043 int32_t actionButton = motionEvent->getActionButton();
3044 int32_t displayId = motionEvent->getDisplayId();
3045 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3046 return INPUT_EVENT_INJECTION_FAILED;
3047 }
3048
3049 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3050 nsecs_t eventTime = motionEvent->getEventTime();
3051 android::base::Timer t;
3052 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3053 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3054 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3055 std::to_string(t.duration().count()).c_str());
3056 }
3057 }
3058
3059 mLock.lock();
3060 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3061 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3062 MotionEntry* injectedEntry =
Garfield Tan00f511d2019-06-12 16:55:40 -07003063 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3064 motionEvent->getDeviceId(), motionEvent->getSource(),
3065 motionEvent->getDisplayId(), policyFlags, action, actionButton,
3066 motionEvent->getFlags(), motionEvent->getMetaState(),
3067 motionEvent->getButtonState(), motionEvent->getClassification(),
3068 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3069 motionEvent->getYPrecision(),
3070 motionEvent->getRawXCursorPosition(),
3071 motionEvent->getRawYCursorPosition(),
3072 motionEvent->getDownTime(), uint32_t(pointerCount),
3073 pointerProperties, samplePointerCoords,
3074 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003075 injectedEntries.push(injectedEntry);
3076 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3077 sampleEventTimes += 1;
3078 samplePointerCoords += pointerCount;
3079 MotionEntry* nextInjectedEntry =
3080 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3081 motionEvent->getDeviceId(), motionEvent->getSource(),
3082 motionEvent->getDisplayId(), policyFlags, action,
3083 actionButton, motionEvent->getFlags(),
3084 motionEvent->getMetaState(), motionEvent->getButtonState(),
3085 motionEvent->getClassification(),
3086 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3087 motionEvent->getYPrecision(),
3088 motionEvent->getRawXCursorPosition(),
3089 motionEvent->getRawYCursorPosition(),
3090 motionEvent->getDownTime(), uint32_t(pointerCount),
3091 pointerProperties, samplePointerCoords,
3092 motionEvent->getXOffset(), motionEvent->getYOffset());
3093 injectedEntries.push(nextInjectedEntry);
3094 }
3095 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003098 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003099 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 }
3102
3103 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3104 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3105 injectionState->injectionIsAsync = true;
3106 }
3107
3108 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003109 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110
3111 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003112 while (!injectedEntries.empty()) {
3113 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3114 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 }
3116
3117 mLock.unlock();
3118
3119 if (needWake) {
3120 mLooper->wake();
3121 }
3122
3123 int32_t injectionResult;
3124 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003125 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126
3127 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3128 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3129 } else {
3130 for (;;) {
3131 injectionResult = injectionState->injectionResult;
3132 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3133 break;
3134 }
3135
3136 nsecs_t remainingTimeout = endTime - now();
3137 if (remainingTimeout <= 0) {
3138#if DEBUG_INJECTION
3139 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003140 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141#endif
3142 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3143 break;
3144 }
3145
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003146 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 }
3148
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3150 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 while (injectionState->pendingForegroundDispatches != 0) {
3152#if DEBUG_INJECTION
3153 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003154 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155#endif
3156 nsecs_t remainingTimeout = endTime - now();
3157 if (remainingTimeout <= 0) {
3158#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003159 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3160 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161#endif
3162 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3163 break;
3164 }
3165
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003166 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167 }
3168 }
3169 }
3170
3171 injectionState->release();
3172 } // release lock
3173
3174#if DEBUG_INJECTION
3175 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003176 "injectorPid=%d, injectorUid=%d",
3177 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178#endif
3179
3180 return injectionResult;
3181}
3182
3183bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 return injectorUid == 0 ||
3185 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186}
3187
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003188void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189 InjectionState* injectionState = entry->injectionState;
3190 if (injectionState) {
3191#if DEBUG_INJECTION
3192 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 "injectorPid=%d, injectorUid=%d",
3194 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195#endif
3196
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003197 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 // Log the outcome since the injector did not wait for the injection result.
3199 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003200 case INPUT_EVENT_INJECTION_SUCCEEDED:
3201 ALOGV("Asynchronous input event injection succeeded.");
3202 break;
3203 case INPUT_EVENT_INJECTION_FAILED:
3204 ALOGW("Asynchronous input event injection failed.");
3205 break;
3206 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3207 ALOGW("Asynchronous input event injection permission denied.");
3208 break;
3209 case INPUT_EVENT_INJECTION_TIMED_OUT:
3210 ALOGW("Asynchronous input event injection timed out.");
3211 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 }
3213 }
3214
3215 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003216 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 }
3218}
3219
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003220void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 InjectionState* injectionState = entry->injectionState;
3222 if (injectionState) {
3223 injectionState->pendingForegroundDispatches += 1;
3224 }
3225}
3226
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003227void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 InjectionState* injectionState = entry->injectionState;
3229 if (injectionState) {
3230 injectionState->pendingForegroundDispatches -= 1;
3231
3232 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003233 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234 }
3235 }
3236}
3237
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003238std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3239 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003240 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003241}
3242
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003244 const sp<IBinder>& windowHandleToken) 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>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003248 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003249 return windowHandle;
3250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251 }
3252 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003253 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254}
3255
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003256bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003257 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003258 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3259 for (const sp<InputWindowHandle>& handle : windowHandles) {
3260 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003261 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003262 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003263 ", but it should belong to display %" PRId32,
3264 windowHandle->getName().c_str(), it.first,
3265 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003266 }
3267 return true;
3268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269 }
3270 }
3271 return false;
3272}
3273
Robert Carr5c8a0262018-10-03 16:30:44 -07003274sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3275 size_t count = mInputChannelsByToken.count(token);
3276 if (count == 0) {
3277 return nullptr;
3278 }
3279 return mInputChannelsByToken.at(token);
3280}
3281
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003282void InputDispatcher::updateWindowHandlesForDisplayLocked(
3283 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3284 if (inputWindowHandles.empty()) {
3285 // Remove all handles on a display if there are no windows left.
3286 mWindowHandlesByDisplay.erase(displayId);
3287 return;
3288 }
3289
3290 // Since we compare the pointer of input window handles across window updates, we need
3291 // to make sure the handle object for the same window stays unchanged across updates.
3292 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003293 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003294 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003295 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003296 }
3297
3298 std::vector<sp<InputWindowHandle>> newHandles;
3299 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3300 if (!handle->updateInfo()) {
3301 // handle no longer valid
3302 continue;
3303 }
3304
3305 const InputWindowInfo* info = handle->getInfo();
3306 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3307 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3308 const bool noInputChannel =
3309 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3310 const bool canReceiveInput =
3311 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3312 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3313 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003314 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003315 handle->getName().c_str());
3316 }
3317 continue;
3318 }
3319
3320 if (info->displayId != displayId) {
3321 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3322 handle->getName().c_str(), displayId, info->displayId);
3323 continue;
3324 }
3325
chaviwaf87b3e2019-10-01 16:59:28 -07003326 if (oldHandlesById.find(handle->getId()) != oldHandlesById.end()) {
3327 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003328 oldHandle->updateFrom(handle);
3329 newHandles.push_back(oldHandle);
3330 } else {
3331 newHandles.push_back(handle);
3332 }
3333 }
3334
3335 // Insert or replace
3336 mWindowHandlesByDisplay[displayId] = newHandles;
3337}
3338
Arthur Hungb92218b2018-08-14 12:00:21 +08003339/**
3340 * Called from InputManagerService, update window handle list by displayId that can receive input.
3341 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3342 * If set an empty list, remove all handles from the specific display.
3343 * For focused handle, check if need to change and send a cancel event to previous one.
3344 * For removed handle, check if need to send a cancel event if already in touch.
3345 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003346void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 int32_t displayId,
3348 const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003349 if (DEBUG_FOCUS) {
3350 std::string windowList;
3351 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3352 windowList += iwh->getName() + " ";
3353 }
3354 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003357 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358
Arthur Hungb92218b2018-08-14 12:00:21 +08003359 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003360 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3361 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003363 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
3364
Tiger Huang721e26f2018-07-24 22:26:19 +08003365 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 bool foundHoveredWindow = false;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003367 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3368 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3369 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3370 windowHandle->getInfo()->visible) {
3371 newFocusedWindowHandle = windowHandle;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003372 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003373 if (windowHandle == mLastHoverWindowHandle) {
3374 foundHoveredWindow = true;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 }
3377
3378 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003379 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380 }
3381
Tiger Huang721e26f2018-07-24 22:26:19 +08003382 sp<InputWindowHandle> oldFocusedWindowHandle =
3383 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3384
chaviwaf87b3e2019-10-01 16:59:28 -07003385 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003386 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003387 if (DEBUG_FOCUS) {
3388 ALOGD("Focus left window: %s in display %" PRId32,
3389 oldFocusedWindowHandle->getName().c_str(), displayId);
3390 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003391 sp<InputChannel> focusedInputChannel =
3392 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003393 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003395 "focus left window");
3396 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003398 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003400 if (newFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003401 if (DEBUG_FOCUS) {
3402 ALOGD("Focus entered window: %s in display %" PRId32,
3403 newFocusedWindowHandle->getName().c_str(), displayId);
3404 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003405 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 }
Robert Carrf759f162018-11-13 12:57:11 -08003407
3408 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003409 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 }
3412
Arthur Hungb92218b2018-08-14 12:00:21 +08003413 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3414 if (stateIndex >= 0) {
3415 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003416 for (size_t i = 0; i < state.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003417 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003418 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003419 if (DEBUG_FOCUS) {
3420 ALOGD("Touched window was removed: %s in display %" PRId32,
3421 touchedWindow.windowHandle->getName().c_str(), displayId);
3422 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003423 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003424 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003425 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003426 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003427 "touched window was removed");
3428 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3429 options);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003430 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003431 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003432 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003433 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 }
3436 }
3437
3438 // Release information for windows that are no longer present.
3439 // This ensures that unused input channels are released promptly.
3440 // Otherwise, they might stick around until the window handle is destroyed
3441 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003442 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003443 if (!hasWindowHandleLocked(oldWindowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003444 if (DEBUG_FOCUS) {
3445 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
3446 }
Arthur Hung3b413f22018-10-26 18:05:34 +08003447 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 }
3449 }
3450 } // release lock
3451
3452 // Wake up poll loop since it may need to make new input dispatching choices.
3453 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003454
3455 if (setInputWindowsListener) {
3456 setInputWindowsListener->onSetInputWindowsFinished();
3457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458}
3459
3460void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003461 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003462 if (DEBUG_FOCUS) {
3463 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3464 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003467 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468
Tiger Huang721e26f2018-07-24 22:26:19 +08003469 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3470 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003471 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003472 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3473 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003476 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003478 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003480 oldFocusedApplicationHandle.clear();
3481 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 } // release lock
3484
3485 // Wake up poll loop since it may need to make new input dispatching choices.
3486 mLooper->wake();
3487}
3488
Tiger Huang721e26f2018-07-24 22:26:19 +08003489/**
3490 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3491 * the display not specified.
3492 *
3493 * We track any unreleased events for each window. If a window loses the ability to receive the
3494 * released event, we will send a cancel event to it. So when the focused display is changed, we
3495 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3496 * display. The display-specified events won't be affected.
3497 */
3498void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003499 if (DEBUG_FOCUS) {
3500 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3501 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003502 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003503 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003504
3505 if (mFocusedDisplayId != displayId) {
3506 sp<InputWindowHandle> oldFocusedWindowHandle =
3507 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3508 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003509 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003510 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003511 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003512 CancelationOptions
3513 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3514 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003515 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003516 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3517 }
3518 }
3519 mFocusedDisplayId = displayId;
3520
3521 // Sanity check
3522 sp<InputWindowHandle> newFocusedWindowHandle =
3523 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003524 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003525
Tiger Huang721e26f2018-07-24 22:26:19 +08003526 if (newFocusedWindowHandle == nullptr) {
3527 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3528 if (!mFocusedWindowHandlesByDisplay.empty()) {
3529 ALOGE("But another display has a focused window:");
3530 for (auto& it : mFocusedWindowHandlesByDisplay) {
3531 const int32_t displayId = it.first;
3532 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003533 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3534 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003535 }
3536 }
3537 }
3538 }
3539
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003540 if (DEBUG_FOCUS) {
3541 logDispatchStateLocked();
3542 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003543 } // release lock
3544
3545 // Wake up poll loop since it may need to make new input dispatching choices.
3546 mLooper->wake();
3547}
3548
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003550 if (DEBUG_FOCUS) {
3551 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553
3554 bool changed;
3555 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003556 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557
3558 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3559 if (mDispatchFrozen && !frozen) {
3560 resetANRTimeoutsLocked();
3561 }
3562
3563 if (mDispatchEnabled && !enabled) {
3564 resetAndDropEverythingLocked("dispatcher is being disabled");
3565 }
3566
3567 mDispatchEnabled = enabled;
3568 mDispatchFrozen = frozen;
3569 changed = true;
3570 } else {
3571 changed = false;
3572 }
3573
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003574 if (DEBUG_FOCUS) {
3575 logDispatchStateLocked();
3576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577 } // release lock
3578
3579 if (changed) {
3580 // Wake up poll loop since it may need to make new input dispatching choices.
3581 mLooper->wake();
3582 }
3583}
3584
3585void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003586 if (DEBUG_FOCUS) {
3587 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589
3590 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003591 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592
3593 if (mInputFilterEnabled == enabled) {
3594 return;
3595 }
3596
3597 mInputFilterEnabled = enabled;
3598 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3599 } // release lock
3600
3601 // Wake up poll loop since there might be work to do to drop everything.
3602 mLooper->wake();
3603}
3604
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003605void InputDispatcher::setInTouchMode(bool inTouchMode) {
3606 std::scoped_lock lock(mLock);
3607 mInTouchMode = inTouchMode;
3608}
3609
chaviwfbe5d9c2018-12-26 12:23:37 -08003610bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3611 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003612 if (DEBUG_FOCUS) {
3613 ALOGD("Trivial transfer to same window.");
3614 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003615 return true;
3616 }
3617
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003619 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620
chaviwfbe5d9c2018-12-26 12:23:37 -08003621 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3622 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003623 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003624 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625 return false;
3626 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003627 if (DEBUG_FOCUS) {
3628 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3629 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3630 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003632 if (DEBUG_FOCUS) {
3633 ALOGD("Cannot transfer focus because windows are on different displays.");
3634 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 return false;
3636 }
3637
3638 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003639 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3640 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3641 for (size_t i = 0; i < state.windows.size(); i++) {
3642 const TouchedWindow& touchedWindow = state.windows[i];
3643 if (touchedWindow.windowHandle == fromWindowHandle) {
3644 int32_t oldTargetFlags = touchedWindow.targetFlags;
3645 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003647 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003649 int32_t newTargetFlags = oldTargetFlags &
3650 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3651 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003652 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653
Jeff Brownf086ddb2014-02-11 14:28:48 -08003654 found = true;
3655 goto Found;
3656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 }
3658 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003659 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003661 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003662 if (DEBUG_FOCUS) {
3663 ALOGD("Focus transfer failed because from window did not have focus.");
3664 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003665 return false;
3666 }
3667
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003668 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3669 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003670 if (fromConnection != nullptr && toConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003671 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003672 CancelationOptions
3673 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3674 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3676 }
3677
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003678 if (DEBUG_FOCUS) {
3679 logDispatchStateLocked();
3680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 } // release lock
3682
3683 // Wake up poll loop since it may need to make new input dispatching choices.
3684 mLooper->wake();
3685 return true;
3686}
3687
3688void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003689 if (DEBUG_FOCUS) {
3690 ALOGD("Resetting and dropping all events (%s).", reason);
3691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692
3693 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3694 synthesizeCancelationEventsForAllConnectionsLocked(options);
3695
3696 resetKeyRepeatLocked();
3697 releasePendingEventLocked();
3698 drainInboundQueueLocked();
3699 resetANRTimeoutsLocked();
3700
Jeff Brownf086ddb2014-02-11 14:28:48 -08003701 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003703 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704}
3705
3706void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003707 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 dumpDispatchStateLocked(dump);
3709
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003710 std::istringstream stream(dump);
3711 std::string line;
3712
3713 while (std::getline(stream, line, '\n')) {
3714 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 }
3716}
3717
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003718void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003719 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3720 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3721 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003722 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723
Tiger Huang721e26f2018-07-24 22:26:19 +08003724 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3725 dump += StringPrintf(INDENT "FocusedApplications:\n");
3726 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3727 const int32_t displayId = it.first;
3728 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003729 dump += StringPrintf(INDENT2 "displayId=%" PRId32
3730 ", name='%s', dispatchingTimeout=%0.3fms\n",
3731 displayId, applicationHandle->getName().c_str(),
3732 applicationHandle->getDispatchingTimeout(
3733 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3734 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08003735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003737 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003739
3740 if (!mFocusedWindowHandlesByDisplay.empty()) {
3741 dump += StringPrintf(INDENT "FocusedWindows:\n");
3742 for (auto& it : mFocusedWindowHandlesByDisplay) {
3743 const int32_t displayId = it.first;
3744 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003745 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3746 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003747 }
3748 } else {
3749 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751
Jeff Brownf086ddb2014-02-11 14:28:48 -08003752 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003753 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003754 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3755 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003756 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003757 state.displayId, toString(state.down), toString(state.split),
3758 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003759 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003760 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003761 for (size_t i = 0; i < state.windows.size(); i++) {
3762 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003763 dump += StringPrintf(INDENT4
3764 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3765 i, touchedWindow.windowHandle->getName().c_str(),
3766 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003767 }
3768 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003769 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003770 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003771 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003772 dump += INDENT3 "Portal windows:\n";
3773 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003774 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003775 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3776 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003777 }
3778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779 }
3780 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003781 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 }
3783
Arthur Hungb92218b2018-08-14 12:00:21 +08003784 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003785 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003786 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003787 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003788 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003789 dump += INDENT2 "Windows:\n";
3790 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003791 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003792 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793
Arthur Hungb92218b2018-08-14 12:00:21 +08003794 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003795 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
3796 "hasWallpaper=%s, "
3797 "visible=%s, canReceiveKeys=%s, flags=0x%08x, "
3798 "type=0x%08x, layer=%d, "
3799 "frame=[%d,%d][%d,%d], globalScale=%f, "
3800 "windowScale=(%f,%f), "
3801 "touchableRegion=",
3802 i, windowInfo->name.c_str(), windowInfo->displayId,
3803 windowInfo->portalToDisplayId,
3804 toString(windowInfo->paused),
3805 toString(windowInfo->hasFocus),
3806 toString(windowInfo->hasWallpaper),
3807 toString(windowInfo->visible),
3808 toString(windowInfo->canReceiveKeys),
3809 windowInfo->layoutParamsFlags,
3810 windowInfo->layoutParamsType, windowInfo->layer,
3811 windowInfo->frameLeft, windowInfo->frameTop,
3812 windowInfo->frameRight, windowInfo->frameBottom,
3813 windowInfo->globalScaleFactor, windowInfo->windowXScale,
3814 windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003815 dumpRegion(dump, windowInfo->touchableRegion);
3816 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3817 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003818 windowInfo->ownerPid, windowInfo->ownerUid,
3819 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08003820 }
3821 } else {
3822 dump += INDENT2 "Windows: <none>\n";
3823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 }
3825 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003826 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 }
3828
Michael Wright3dd60e22019-03-27 22:06:44 +00003829 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003830 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003831 const std::vector<Monitor>& monitors = it.second;
3832 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3833 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003834 }
3835 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003836 const std::vector<Monitor>& monitors = it.second;
3837 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3838 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003841 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 }
3843
3844 nsecs_t currentTime = now();
3845
3846 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003847 if (!mRecentQueue.empty()) {
3848 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
3849 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003850 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003852 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853 }
3854 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003855 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 }
3857
3858 // Dump event currently being dispatched.
3859 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003860 dump += INDENT "PendingEvent:\n";
3861 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003863 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003864 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003866 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 }
3868
3869 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003870 if (!mInboundQueue.empty()) {
3871 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
3872 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003873 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003875 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 }
3877 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003878 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 }
3880
Michael Wright78f24442014-08-06 15:55:28 -07003881 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003882 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003883 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3884 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3885 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003886 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3887 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07003888 }
3889 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003890 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003891 }
3892
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003893 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003894 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003895 for (const auto& pair : mConnectionsByFd) {
3896 const sp<Connection>& connection = pair.second;
3897 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
3898 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3899 pair.first, connection->getInputChannelName().c_str(),
3900 connection->getWindowName().c_str(), connection->getStatusLabel(),
3901 toString(connection->monitor),
3902 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003904 if (!connection->outboundQueue.empty()) {
3905 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
3906 connection->outboundQueue.size());
3907 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 dump.append(INDENT4);
3909 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003910 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003911 entry->targetFlags, entry->resolvedAction,
3912 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913 }
3914 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003915 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916 }
3917
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003918 if (!connection->waitQueue.empty()) {
3919 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
3920 connection->waitQueue.size());
3921 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003922 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003924 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003925 "age=%0.1fms, wait=%0.1fms\n",
3926 entry->targetFlags, entry->resolvedAction,
3927 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3928 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 }
3930 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003931 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932 }
3933 }
3934 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003935 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 }
3937
3938 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003939 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003940 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003942 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 }
3944
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003945 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003946 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003947 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003948 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949}
3950
Michael Wright3dd60e22019-03-27 22:06:44 +00003951void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3952 const size_t numMonitors = monitors.size();
3953 for (size_t i = 0; i < numMonitors; i++) {
3954 const Monitor& monitor = monitors[i];
3955 const sp<InputChannel>& channel = monitor.inputChannel;
3956 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3957 dump += "\n";
3958 }
3959}
3960
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003961status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07003963 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964#endif
3965
3966 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003967 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003968 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003969 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003971 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 return BAD_VALUE;
3973 }
3974
Michael Wright3dd60e22019-03-27 22:06:44 +00003975 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976
3977 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003978 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003979 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3982 } // release lock
3983
3984 // Wake the looper because some connections have changed.
3985 mLooper->wake();
3986 return OK;
3987}
3988
Michael Wright3dd60e22019-03-27 22:06:44 +00003989status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003990 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003991 { // acquire lock
3992 std::scoped_lock _l(mLock);
3993
3994 if (displayId < 0) {
3995 ALOGW("Attempted to register input monitor without a specified display.");
3996 return BAD_VALUE;
3997 }
3998
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003999 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004000 ALOGW("Attempted to register input monitor without an identifying token.");
4001 return BAD_VALUE;
4002 }
4003
4004 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
4005
4006 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004007 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004008 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004009
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004010 auto& monitorsByDisplay =
4011 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004012 monitorsByDisplay[displayId].emplace_back(inputChannel);
4013
4014 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004015 }
4016 // Wake the looper because some connections have changed.
4017 mLooper->wake();
4018 return OK;
4019}
4020
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4022#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004023 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024#endif
4025
4026 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004027 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028
4029 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4030 if (status) {
4031 return status;
4032 }
4033 } // release lock
4034
4035 // Wake the poll loop because removing the connection may have changed the current
4036 // synchronization state.
4037 mLooper->wake();
4038 return OK;
4039}
4040
4041status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004042 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004043 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004044 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004046 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047 return BAD_VALUE;
4048 }
4049
John Recke0710582019-09-26 13:46:12 -07004050 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004051 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004052 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004053
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054 if (connection->monitor) {
4055 removeMonitorChannelLocked(inputChannel);
4056 }
4057
4058 mLooper->removeFd(inputChannel->getFd());
4059
4060 nsecs_t currentTime = now();
4061 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4062
4063 connection->status = Connection::STATUS_ZOMBIE;
4064 return OK;
4065}
4066
4067void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004068 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4069 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4070}
4071
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004072void InputDispatcher::removeMonitorChannelLocked(
4073 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004074 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004075 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004076 std::vector<Monitor>& monitors = it->second;
4077 const size_t numMonitors = monitors.size();
4078 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004079 if (monitors[i].inputChannel == inputChannel) {
4080 monitors.erase(monitors.begin() + i);
4081 break;
4082 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004083 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004084 if (monitors.empty()) {
4085 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004086 } else {
4087 ++it;
4088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 }
4090}
4091
Michael Wright3dd60e22019-03-27 22:06:44 +00004092status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4093 { // acquire lock
4094 std::scoped_lock _l(mLock);
4095 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4096
4097 if (!foundDisplayId) {
4098 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4099 return BAD_VALUE;
4100 }
4101 int32_t displayId = foundDisplayId.value();
4102
4103 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4104 if (stateIndex < 0) {
4105 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4106 return BAD_VALUE;
4107 }
4108
4109 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4110 std::optional<int32_t> foundDeviceId;
4111 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004112 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004113 foundDeviceId = state.deviceId;
4114 }
4115 }
4116 if (!foundDeviceId || !state.down) {
4117 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004118 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004119 return BAD_VALUE;
4120 }
4121 int32_t deviceId = foundDeviceId.value();
4122
4123 // Send cancel events to all the input channels we're stealing from.
4124 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004125 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004126 options.deviceId = deviceId;
4127 options.displayId = displayId;
4128 for (const TouchedWindow& window : state.windows) {
4129 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004130 if (channel != nullptr) {
4131 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4132 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004133 }
4134 // Then clear the current touch state so we stop dispatching to them as well.
4135 state.filterNonMonitors();
4136 }
4137 return OK;
4138}
4139
Michael Wright3dd60e22019-03-27 22:06:44 +00004140std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4141 const sp<IBinder>& token) {
4142 for (const auto& it : mGestureMonitorsByDisplay) {
4143 const std::vector<Monitor>& monitors = it.second;
4144 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004145 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004146 return it.first;
4147 }
4148 }
4149 }
4150 return std::nullopt;
4151}
4152
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004153sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4154 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004155 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004156 }
4157
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004158 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004159 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004160 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004161 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 }
4163 }
Robert Carr4e670e52018-08-15 13:26:12 -07004164
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004165 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166}
4167
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004168void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4169 const sp<Connection>& connection, uint32_t seq,
4170 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004171 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4172 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 commandEntry->connection = connection;
4174 commandEntry->eventTime = currentTime;
4175 commandEntry->seq = seq;
4176 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004177 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178}
4179
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4181 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004183 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004185 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4186 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004188 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189}
4190
chaviw0c06c6e2019-01-09 13:27:07 -08004191void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004192 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004193 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4194 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004195 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4196 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004197 commandEntry->oldToken = oldToken;
4198 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004199 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004200}
4201
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202void InputDispatcher::onANRLocked(nsecs_t currentTime,
4203 const sp<InputApplicationHandle>& applicationHandle,
4204 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4205 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4207 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4208 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004209 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4210 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4211 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212
4213 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004214 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215 struct tm tm;
4216 localtime_r(&t, &tm);
4217 char timestr[64];
4218 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4219 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004220 mLastANRState += INDENT "ANR:\n";
4221 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004222 mLastANRState +=
4223 StringPrintf(INDENT2 "Window: %s\n",
4224 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004225 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4226 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4227 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 dumpDispatchStateLocked(mLastANRState);
4229
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004230 std::unique_ptr<CommandEntry> commandEntry =
4231 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 commandEntry->inputChannel =
4234 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004236 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237}
4238
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004239void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 mLock.unlock();
4241
4242 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4243
4244 mLock.lock();
4245}
4246
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004247void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 sp<Connection> connection = commandEntry->connection;
4249
4250 if (connection->status != Connection::STATUS_ZOMBIE) {
4251 mLock.unlock();
4252
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004253 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254
4255 mLock.lock();
4256 }
4257}
4258
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004259void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004260 sp<IBinder> oldToken = commandEntry->oldToken;
4261 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004262 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004263 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004264 mLock.lock();
4265}
4266
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004267void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004268 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004269 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 mLock.unlock();
4271
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004272 nsecs_t newTimeout =
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004273 mPolicy->notifyANR(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274
4275 mLock.lock();
4276
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004277 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278}
4279
4280void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4281 CommandEntry* commandEntry) {
4282 KeyEntry* entry = commandEntry->keyEntry;
4283
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004284 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285
4286 mLock.unlock();
4287
Michael Wright2b3c3302018-03-02 17:19:13 +00004288 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004289 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004290 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004291 : nullptr;
4292 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004293 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4294 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004295 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297
4298 mLock.lock();
4299
4300 if (delay < 0) {
4301 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4302 } else if (!delay) {
4303 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4304 } else {
4305 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4306 entry->interceptKeyWakeupTime = now() + delay;
4307 }
4308 entry->release();
4309}
4310
chaviwfd6d3512019-03-25 13:23:49 -07004311void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4312 mLock.unlock();
4313 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4314 mLock.lock();
4315}
4316
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004317void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004319 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004321 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322
4323 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004324 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004325 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004326 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004328 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004329
4330 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4331 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4332 std::string msg =
4333 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4334 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4335 dispatchEntry->eventEntry->appendDescription(msg);
4336 ALOGI("%s", msg.c_str());
4337 }
4338
4339 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004340 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004341 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4342 restartEvent =
4343 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004344 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004345 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4346 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4347 handled);
4348 } else {
4349 restartEvent = false;
4350 }
4351
4352 // Dequeue the event and start the next cycle.
4353 // Note that because the lock might have been released, it is possible that the
4354 // contents of the wait queue to have been drained, so we need to double-check
4355 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004356 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4357 if (dispatchEntryIt != connection->waitQueue.end()) {
4358 dispatchEntry = *dispatchEntryIt;
4359 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004360 traceWaitQueueLength(connection);
4361 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004362 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004363 traceOutboundQueueLength(connection);
4364 } else {
4365 releaseDispatchEntry(dispatchEntry);
4366 }
4367 }
4368
4369 // Start the next dispatch cycle for this connection.
4370 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371}
4372
4373bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004374 DispatchEntry* dispatchEntry,
4375 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004376 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004377 if (!handled) {
4378 // Report the key as unhandled, since the fallback was not handled.
4379 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4380 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004381 return false;
4382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004384 // Get the fallback key state.
4385 // Clear it out after dispatching the UP.
4386 int32_t originalKeyCode = keyEntry->keyCode;
4387 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4388 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4389 connection->inputState.removeFallbackKey(originalKeyCode);
4390 }
4391
4392 if (handled || !dispatchEntry->hasForegroundTarget()) {
4393 // If the application handles the original key for which we previously
4394 // generated a fallback or if the window is not a foreground window,
4395 // then cancel the associated fallback key, if any.
4396 if (fallbackKeyCode != -1) {
4397 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004399 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004400 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4401 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4402 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004404 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004405 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406
4407 mLock.unlock();
4408
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004409 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004410 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004411
4412 mLock.lock();
4413
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004414 // Cancel the fallback key.
4415 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004417 "application handled the original non-fallback key "
4418 "or is no longer a foreground target, "
4419 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 options.keyCode = fallbackKeyCode;
4421 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004423 connection->inputState.removeFallbackKey(originalKeyCode);
4424 }
4425 } else {
4426 // If the application did not handle a non-fallback key, first check
4427 // that we are in a good state to perform unhandled key event processing
4428 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004429 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004430 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004432 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004433 "since this is not an initial down. "
4434 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4435 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004437 return false;
4438 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004440 // Dispatch the unhandled key to the policy.
4441#if DEBUG_OUTBOUND_EVENT_DETAILS
4442 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004443 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4444 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004445#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004446 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004447
4448 mLock.unlock();
4449
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004450 bool fallback =
4451 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4452 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004453
4454 mLock.lock();
4455
4456 if (connection->status != Connection::STATUS_NORMAL) {
4457 connection->inputState.removeFallbackKey(originalKeyCode);
4458 return false;
4459 }
4460
4461 // Latch the fallback keycode for this key on an initial down.
4462 // The fallback keycode cannot change at any other point in the lifecycle.
4463 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004465 fallbackKeyCode = event.getKeyCode();
4466 } else {
4467 fallbackKeyCode = AKEYCODE_UNKNOWN;
4468 }
4469 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4470 }
4471
4472 ALOG_ASSERT(fallbackKeyCode != -1);
4473
4474 // Cancel the fallback key if the policy decides not to send it anymore.
4475 // We will continue to dispatch the key to the policy but we will no
4476 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004477 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4478 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004479#if DEBUG_OUTBOUND_EVENT_DETAILS
4480 if (fallback) {
4481 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004482 "as a fallback for %d, but on the DOWN it had requested "
4483 "to send %d instead. Fallback canceled.",
4484 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004485 } else {
4486 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004487 "but on the DOWN it had requested to send %d. "
4488 "Fallback canceled.",
4489 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004490 }
4491#endif
4492
4493 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4494 "canceling fallback, policy no longer desires it");
4495 options.keyCode = fallbackKeyCode;
4496 synthesizeCancelationEventsForConnectionLocked(connection, options);
4497
4498 fallback = false;
4499 fallbackKeyCode = AKEYCODE_UNKNOWN;
4500 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004501 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004502 }
4503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504
4505#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004506 {
4507 std::string msg;
4508 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4509 connection->inputState.getFallbackKeys();
4510 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004511 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004513 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004514 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004515 }
4516#endif
4517
4518 if (fallback) {
4519 // Restart the dispatch cycle using the fallback key.
4520 keyEntry->eventTime = event.getEventTime();
4521 keyEntry->deviceId = event.getDeviceId();
4522 keyEntry->source = event.getSource();
4523 keyEntry->displayId = event.getDisplayId();
4524 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4525 keyEntry->keyCode = fallbackKeyCode;
4526 keyEntry->scanCode = event.getScanCode();
4527 keyEntry->metaState = event.getMetaState();
4528 keyEntry->repeatCount = event.getRepeatCount();
4529 keyEntry->downTime = event.getDownTime();
4530 keyEntry->syntheticRepeat = false;
4531
4532#if DEBUG_OUTBOUND_EVENT_DETAILS
4533 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004534 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4535 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004536#endif
4537 return true; // restart the event
4538 } else {
4539#if DEBUG_OUTBOUND_EVENT_DETAILS
4540 ALOGD("Unhandled key event: No fallback key.");
4541#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004542
4543 // Report the key as unhandled, since there is no fallback key.
4544 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 }
4546 }
4547 return false;
4548}
4549
4550bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004551 DispatchEntry* dispatchEntry,
4552 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 return false;
4554}
4555
4556void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4557 mLock.unlock();
4558
4559 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4560
4561 mLock.lock();
4562}
4563
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004564KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4565 KeyEvent event;
4566 event.initialize(entry.deviceId, entry.source, entry.displayId, entry.action, entry.flags,
4567 entry.keyCode, entry.scanCode, entry.metaState, entry.repeatCount,
4568 entry.downTime, entry.eventTime);
4569 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570}
4571
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004572void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004573 int32_t injectionResult,
4574 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575 // TODO Write some statistics about how long we spend waiting.
4576}
4577
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004578/**
4579 * Report the touch event latency to the statsd server.
4580 * Input events are reported for statistics if:
4581 * - This is a touchscreen event
4582 * - InputFilter is not enabled
4583 * - Event is not injected or synthesized
4584 *
4585 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4586 * from getting aggregated with the "old" data.
4587 */
4588void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4589 REQUIRES(mLock) {
4590 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4591 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4592 if (!reportForStatistics) {
4593 return;
4594 }
4595
4596 if (mTouchStatistics.shouldReport()) {
4597 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4598 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4599 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4600 mTouchStatistics.reset();
4601 }
4602 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4603 mTouchStatistics.addValue(latencyMicros);
4604}
4605
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606void InputDispatcher::traceInboundQueueLengthLocked() {
4607 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004608 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609 }
4610}
4611
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004612void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613 if (ATRACE_ENABLED()) {
4614 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004615 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004616 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617 }
4618}
4619
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004620void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621 if (ATRACE_ENABLED()) {
4622 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004623 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004624 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 }
4626}
4627
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004628void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004629 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004631 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 dumpDispatchStateLocked(dump);
4633
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004634 if (!mLastANRState.empty()) {
4635 dump += "\nInput Dispatcher State at time of last ANR:\n";
4636 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637 }
4638}
4639
4640void InputDispatcher::monitor() {
4641 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004642 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004644 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645}
4646
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004647/**
4648 * Wake up the dispatcher and wait until it processes all events and commands.
4649 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4650 * this method can be safely called from any thread, as long as you've ensured that
4651 * the work you are interested in completing has already been queued.
4652 */
4653bool InputDispatcher::waitForIdle() {
4654 /**
4655 * Timeout should represent the longest possible time that a device might spend processing
4656 * events and commands.
4657 */
4658 constexpr std::chrono::duration TIMEOUT = 100ms;
4659 std::unique_lock lock(mLock);
4660 mLooper->wake();
4661 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4662 return result == std::cv_status::no_timeout;
4663}
4664
Garfield Tane84e6f92019-08-29 17:28:41 -07004665} // namespace android::inputdispatcher