blob: ce7399ef6e62a3e853953ebc8d625b11e370f630 [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
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800255static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
256 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
257}
258
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700259// --- InputDispatcherThread ---
260
261class InputDispatcher::InputDispatcherThread : public Thread {
262public:
263 explicit InputDispatcherThread(InputDispatcher* dispatcher)
264 : Thread(/* canCallJava */ true), mDispatcher(dispatcher) {}
265
266 ~InputDispatcherThread() {}
267
268private:
269 InputDispatcher* mDispatcher;
270
271 virtual bool threadLoop() override {
272 mDispatcher->dispatchOnce();
273 return true;
274 }
275};
276
Michael Wrightd02c5b62014-02-10 15:10:22 -0800277// --- InputDispatcher ---
278
Garfield Tan00f511d2019-06-12 16:55:40 -0700279InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
280 : mPolicy(policy),
281 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700282 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tan00f511d2019-06-12 16:55:40 -0700283 mAppSwitchSawKeyDown(false),
284 mAppSwitchDueTime(LONG_LONG_MAX),
285 mNextUnblockedEvent(nullptr),
286 mDispatchEnabled(false),
287 mDispatchFrozen(false),
288 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800289 // mInTouchMode will be initialized by the WindowManager to the default device config.
290 // To avoid leaking stack in case that call never comes, and for tests,
291 // initialize it here anyways.
292 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700293 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
294 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800295 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800296 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800297
Yi Kong9b14ac62018-07-17 13:48:38 -0700298 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800299
300 policy->getDispatcherConfiguration(&mConfig);
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700301
302 mThread = new InputDispatcherThread(this);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800303}
304
305InputDispatcher::~InputDispatcher() {
306 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800307 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800308
309 resetKeyRepeatLocked();
310 releasePendingEventLocked();
311 drainInboundQueueLocked();
312 }
313
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700314 while (!mConnectionsByFd.empty()) {
315 sp<Connection> connection = mConnectionsByFd.begin()->second;
316 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800317 }
318}
319
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700320status_t InputDispatcher::start() {
321 if (mThread->isRunning()) {
322 return ALREADY_EXISTS;
323 }
324 return mThread->run("InputDispatcher", PRIORITY_URGENT_DISPLAY);
325}
326
327status_t InputDispatcher::stop() {
328 if (!mThread->isRunning()) {
329 return OK;
330 }
331 if (gettid() == mThread->getTid()) {
332 ALOGE("InputDispatcher can only be stopped from outside of the InputDispatcherThread!");
333 return INVALID_OPERATION;
334 }
335 // Directly calling requestExitAndWait() causes the thread to not exit
336 // if mLooper is waiting for a long timeout.
337 mThread->requestExit();
338 mLooper->wake();
339 return mThread->requestExitAndWait();
340}
341
Michael Wrightd02c5b62014-02-10 15:10:22 -0800342void InputDispatcher::dispatchOnce() {
343 nsecs_t nextWakeupTime = LONG_LONG_MAX;
344 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800345 std::scoped_lock _l(mLock);
346 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800347
348 // Run a dispatch loop if there are no pending commands.
349 // The dispatch loop might enqueue commands to run afterwards.
350 if (!haveCommandsLocked()) {
351 dispatchOnceInnerLocked(&nextWakeupTime);
352 }
353
354 // Run all pending commands if there are any.
355 // If any commands were run then force the next poll to wake up immediately.
356 if (runCommandsLockedInterruptible()) {
357 nextWakeupTime = LONG_LONG_MIN;
358 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800359
360 // We are about to enter an infinitely long sleep, because we have no commands or
361 // pending or queued events
362 if (nextWakeupTime == LONG_LONG_MAX) {
363 mDispatcherEnteredIdle.notify_all();
364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800365 } // release lock
366
367 // Wait for callback or timeout or wake. (make sure we round up, not down)
368 nsecs_t currentTime = now();
369 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
370 mLooper->pollOnce(timeoutMillis);
371}
372
373void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
374 nsecs_t currentTime = now();
375
Jeff Browndc5992e2014-04-11 01:27:26 -0700376 // Reset the key repeat timer whenever normal dispatch is suspended while the
377 // device is in a non-interactive state. This is to ensure that we abort a key
378 // repeat if the device is just coming out of sleep.
379 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800380 resetKeyRepeatLocked();
381 }
382
383 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
384 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100385 if (DEBUG_FOCUS) {
386 ALOGD("Dispatch frozen. Waiting some more.");
387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800388 return;
389 }
390
391 // Optimize latency of app switches.
392 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
393 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
394 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
395 if (mAppSwitchDueTime < *nextWakeupTime) {
396 *nextWakeupTime = mAppSwitchDueTime;
397 }
398
399 // Ready to start a new event.
400 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700401 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700402 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403 if (isAppSwitchDue) {
404 // The inbound queue is empty so the app switch key we were waiting
405 // for will never arrive. Stop waiting for it.
406 resetPendingAppSwitchLocked(false);
407 isAppSwitchDue = false;
408 }
409
410 // Synthesize a key repeat if appropriate.
411 if (mKeyRepeatState.lastKeyEntry) {
412 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
413 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
414 } else {
415 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
416 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
417 }
418 }
419 }
420
421 // Nothing to do if there is no pending event.
422 if (!mPendingEvent) {
423 return;
424 }
425 } else {
426 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700427 mPendingEvent = mInboundQueue.front();
428 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800429 traceInboundQueueLengthLocked();
430 }
431
432 // Poke user activity for this event.
433 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700434 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800435 }
436
437 // Get ready to dispatch the event.
438 resetANRTimeoutsLocked();
439 }
440
441 // Now we have an event to dispatch.
442 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700443 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800444 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700445 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800446 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700447 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700449 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450 }
451
452 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700453 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800454 }
455
456 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700457 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700458 ConfigurationChangedEntry* typedEntry =
459 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
460 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700461 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700462 break;
463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700465 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700466 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
467 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700468 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700469 break;
470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800471
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100472 case EventEntry::Type::FOCUS: {
473 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
474 dispatchFocusLocked(currentTime, typedEntry);
475 done = true;
476 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
477 break;
478 }
479
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700480 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700481 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
482 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700483 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700484 resetPendingAppSwitchLocked(true);
485 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700486 } else if (dropReason == DropReason::NOT_DROPPED) {
487 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700488 }
489 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700490 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700491 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700492 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700493 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
494 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700495 }
496 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
497 break;
498 }
499
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700500 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700501 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700502 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
503 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800504 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700505 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700506 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700507 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700508 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
509 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700510 }
511 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
512 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514 }
515
516 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700517 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700518 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519 }
Michael Wright3a981722015-06-10 15:26:13 +0100520 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521
522 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700523 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800524 }
525}
526
527bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700528 bool needWake = mInboundQueue.empty();
529 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 traceInboundQueueLengthLocked();
531
532 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700533 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700534 // Optimize app switch latency.
535 // If the application takes too long to catch up then we drop all events preceding
536 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700537 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700538 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700539 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700540 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700541 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700542 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700544 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700546 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700547 mAppSwitchSawKeyDown = false;
548 needWake = true;
549 }
550 }
551 }
552 break;
553 }
554
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700555 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700556 // Optimize case where the current application is unresponsive and the user
557 // decides to touch a window in a different application.
558 // If the application takes too long to catch up then we drop all events preceding
559 // the touch into the other window.
560 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
561 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
562 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
563 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
564 mInputTargetWaitApplicationToken != nullptr) {
565 int32_t displayId = motionEntry->displayId;
566 int32_t x =
567 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
568 int32_t y =
569 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
570 sp<InputWindowHandle> touchedWindowHandle =
571 findTouchedWindowAtLocked(displayId, x, y);
572 if (touchedWindowHandle != nullptr &&
573 touchedWindowHandle->getApplicationToken() !=
574 mInputTargetWaitApplicationToken) {
575 // User touched a different application than the one we are waiting on.
576 // Flag the event, and start pruning the input queue.
577 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800578 needWake = true;
579 }
580 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700581 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800582 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700583 case EventEntry::Type::CONFIGURATION_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100584 case EventEntry::Type::DEVICE_RESET:
585 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700586 // nothing to do
587 break;
588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 }
590
591 return needWake;
592}
593
594void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
595 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700596 mRecentQueue.push_back(entry);
597 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
598 mRecentQueue.front()->release();
599 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600 }
601}
602
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700603sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
604 int32_t y, bool addOutsideTargets,
605 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800607 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
608 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609 const InputWindowInfo* windowInfo = windowHandle->getInfo();
610 if (windowInfo->displayId == displayId) {
611 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612
613 if (windowInfo->visible) {
614 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700615 bool isTouchModal = (flags &
616 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
617 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800619 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700620 if (portalToDisplayId != ADISPLAY_ID_NONE &&
621 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800622 if (addPortalWindows) {
623 // For the monitoring channels of the display.
624 mTempTouchState.addPortalWindow(windowHandle);
625 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700626 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
627 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 // Found window.
630 return windowHandle;
631 }
632 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800633
634 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700635 mTempTouchState.addOrUpdateWindow(windowHandle,
636 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
637 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640 }
641 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700642 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800643}
644
Garfield Tane84e6f92019-08-29 17:28:41 -0700645std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000646 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
647 std::vector<TouchedMonitor> touchedMonitors;
648
649 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
650 addGestureMonitors(monitors, touchedMonitors);
651 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
652 const InputWindowInfo* windowInfo = portalWindow->getInfo();
653 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700654 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
655 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000656 }
657 return touchedMonitors;
658}
659
660void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700661 std::vector<TouchedMonitor>& outTouchedMonitors,
662 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000663 if (monitors.empty()) {
664 return;
665 }
666 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
667 for (const Monitor& monitor : monitors) {
668 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
669 }
670}
671
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700672void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673 const char* reason;
674 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700675 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700677 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700679 reason = "inbound event was dropped because the policy consumed it";
680 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700681 case DropReason::DISABLED:
682 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700683 ALOGI("Dropped event because input dispatch is disabled.");
684 }
685 reason = "inbound event was dropped because input dispatch is disabled";
686 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700687 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700688 ALOGI("Dropped event because of pending overdue app switch.");
689 reason = "inbound event was dropped because of pending overdue app switch";
690 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700691 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700692 ALOGI("Dropped event because the current application is not responding and the user "
693 "has started interacting with a different application.");
694 reason = "inbound event was dropped because the current application is not responding "
695 "and the user has started interacting with a different application";
696 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700697 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700698 ALOGI("Dropped event because it is stale.");
699 reason = "inbound event was dropped because it is stale";
700 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700701 case DropReason::NOT_DROPPED: {
702 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700703 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 }
706
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700707 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700708 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800709 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
710 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700711 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700713 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700714 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
715 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700716 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
717 synthesizeCancelationEventsForAllConnectionsLocked(options);
718 } else {
719 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
720 synthesizeCancelationEventsForAllConnectionsLocked(options);
721 }
722 break;
723 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100724 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700725 case EventEntry::Type::CONFIGURATION_CHANGED:
726 case EventEntry::Type::DEVICE_RESET: {
727 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
728 break;
729 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 }
731}
732
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800733static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700734 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
735 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736}
737
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700738bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
739 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
740 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
741 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742}
743
744bool InputDispatcher::isAppSwitchPendingLocked() {
745 return mAppSwitchDueTime != LONG_LONG_MAX;
746}
747
748void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
749 mAppSwitchDueTime = LONG_LONG_MAX;
750
751#if DEBUG_APP_SWITCH
752 if (handled) {
753 ALOGD("App switch has arrived.");
754 } else {
755 ALOGD("App switch was abandoned.");
756 }
757#endif
758}
759
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700761 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762}
763
764bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700765 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 return false;
767 }
768
769 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700770 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700771 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700773 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774
775 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700776 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 return true;
778}
779
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700780void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
781 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782}
783
784void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700785 while (!mInboundQueue.empty()) {
786 EventEntry* entry = mInboundQueue.front();
787 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 releaseInboundEventLocked(entry);
789 }
790 traceInboundQueueLengthLocked();
791}
792
793void InputDispatcher::releasePendingEventLocked() {
794 if (mPendingEvent) {
795 resetANRTimeoutsLocked();
796 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700797 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 }
799}
800
801void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
802 InjectionState* injectionState = entry->injectionState;
803 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
804#if DEBUG_DISPATCH_CYCLE
805 ALOGD("Injected inbound event was dropped.");
806#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800807 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808 }
809 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700810 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811 }
812 addRecentEventLocked(entry);
813 entry->release();
814}
815
816void InputDispatcher::resetKeyRepeatLocked() {
817 if (mKeyRepeatState.lastKeyEntry) {
818 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700819 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820 }
821}
822
Garfield Tane84e6f92019-08-29 17:28:41 -0700823KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
825
826 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700827 uint32_t policyFlags = entry->policyFlags &
828 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829 if (entry->refCount == 1) {
830 entry->recycle();
831 entry->eventTime = currentTime;
832 entry->policyFlags = policyFlags;
833 entry->repeatCount += 1;
834 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 KeyEntry* newEntry =
836 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId,
837 entry->source, entry->displayId, policyFlags, entry->action,
838 entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
839 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840
841 mKeyRepeatState.lastKeyEntry = newEntry;
842 entry->release();
843
844 entry = newEntry;
845 }
846 entry->syntheticRepeat = true;
847
848 // Increment reference count since we keep a reference to the event in
849 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
850 entry->refCount += 1;
851
852 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
853 return entry;
854}
855
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700856bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
857 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700859 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860#endif
861
862 // Reset key repeating in case a keyboard device was added or removed or something.
863 resetKeyRepeatLocked();
864
865 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700866 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
867 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700869 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 return true;
871}
872
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700873bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700875 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700876 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877#endif
878
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 options.deviceId = entry->deviceId;
881 synthesizeCancelationEventsForAllConnectionsLocked(options);
882 return true;
883}
884
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100885void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
886 FocusEntry* focusEntry =
887 new FocusEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, now(), window.getToken(), hasFocus);
888 enqueueInboundEventLocked(focusEntry);
889}
890
891void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
892 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
893 if (channel == nullptr) {
894 return; // Window has gone away
895 }
896 InputTarget target;
897 target.inputChannel = channel;
898 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
899 entry->dispatchInProgress = true;
900
901 dispatchEventLocked(currentTime, entry, {target});
902}
903
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700907 if (!entry->dispatchInProgress) {
908 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
909 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
910 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
911 if (mKeyRepeatState.lastKeyEntry &&
912 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913 // We have seen two identical key downs in a row which indicates that the device
914 // driver is automatically generating key repeats itself. We take note of the
915 // repeat here, but we disable our own next key repeat timer since it is clear that
916 // we will not need to synthesize key repeats ourselves.
917 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
918 resetKeyRepeatLocked();
919 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
920 } else {
921 // Not a repeat. Save key down state in case we do see a repeat later.
922 resetKeyRepeatLocked();
923 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
924 }
925 mKeyRepeatState.lastKeyEntry = entry;
926 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700927 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 resetKeyRepeatLocked();
929 }
930
931 if (entry->repeatCount == 1) {
932 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
933 } else {
934 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
935 }
936
937 entry->dispatchInProgress = true;
938
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700939 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 }
941
942 // Handle case where the policy asked us to try again later last time.
943 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
944 if (currentTime < entry->interceptKeyWakeupTime) {
945 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
946 *nextWakeupTime = entry->interceptKeyWakeupTime;
947 }
948 return false; // wait until next wakeup
949 }
950 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
951 entry->interceptKeyWakeupTime = 0;
952 }
953
954 // Give the policy a chance to intercept the key.
955 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
956 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700957 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -0700958 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800959 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700960 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +0800961 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700962 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963 }
964 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700965 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 entry->refCount += 1;
967 return false; // wait for the command to run
968 } else {
969 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
970 }
971 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700972 if (*dropReason == DropReason::NOT_DROPPED) {
973 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974 }
975 }
976
977 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700978 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700979 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700980 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800982 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 return true;
984 }
985
986 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800987 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700988 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700989 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
991 return false;
992 }
993
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800994 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
996 return true;
997 }
998
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800999 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001000 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001
1002 // Dispatch the key.
1003 dispatchEventLocked(currentTime, entry, inputTargets);
1004 return true;
1005}
1006
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001007void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001009 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001010 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1011 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001012 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1013 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1014 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015#endif
1016}
1017
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001018bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1019 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001020 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 entry->dispatchInProgress = true;
1024
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001025 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 }
1027
1028 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001029 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001031 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001032 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 return true;
1034 }
1035
1036 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1037
1038 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001039 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040
1041 bool conflictingPointerActions = false;
1042 int32_t injectionResult;
1043 if (isPointerEvent) {
1044 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001045 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001046 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001047 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 } else {
1049 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001050 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001051 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 }
1053 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1054 return false;
1055 }
1056
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001057 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001059 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001060 CancelationOptions::Mode mode(isPointerEvent
1061 ? CancelationOptions::CANCEL_POINTER_EVENTS
1062 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001063 CancelationOptions options(mode, "input event injection failed");
1064 synthesizeCancelationEventsForMonitorsLocked(options);
1065 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 return true;
1067 }
1068
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001069 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001070 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001072 if (isPointerEvent) {
1073 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
1074 if (stateIndex >= 0) {
1075 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001076 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001077 // The event has gone through these portal windows, so we add monitoring targets of
1078 // the corresponding displays as well.
1079 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001080 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001081 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001082 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001083 }
1084 }
1085 }
1086 }
1087
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 // Dispatch the motion.
1089 if (conflictingPointerActions) {
1090 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001091 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 synthesizeCancelationEventsForAllConnectionsLocked(options);
1093 }
1094 dispatchEventLocked(currentTime, entry, inputTargets);
1095 return true;
1096}
1097
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001098void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001100 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 ", policyFlags=0x%x, "
1102 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1103 "metaState=0x%x, buttonState=0x%x,"
1104 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001105 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1106 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1107 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001109 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001111 "x=%f, y=%f, pressure=%f, size=%f, "
1112 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1113 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001114 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1115 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1116 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1117 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1118 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1119 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1120 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1121 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1122 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1123 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 }
1125#endif
1126}
1127
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1129 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001130 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131#if DEBUG_DISPATCH_CYCLE
1132 ALOGD("dispatchEventToCurrentInputTargets");
1133#endif
1134
1135 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1136
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001137 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001138
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001139 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001140 sp<Connection> connection =
1141 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001142 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001143 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001145 if (DEBUG_FOCUS) {
1146 ALOGD("Dropping event delivery to target with channel '%s' because it "
1147 "is no longer registered with the input dispatcher.",
1148 inputTarget.inputChannel->getName().c_str());
1149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150 }
1151 }
1152}
1153
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001154int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001155 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001157 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001158 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001160 if (DEBUG_FOCUS) {
1161 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1162 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1164 mInputTargetWaitStartTime = currentTime;
1165 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1166 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001167 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 }
1169 } else {
1170 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001171 if (DEBUG_FOCUS) {
1172 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
1173 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001176 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001178 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001179 timeout =
1180 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 } else {
1182 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1183 }
1184
1185 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1186 mInputTargetWaitStartTime = currentTime;
1187 mInputTargetWaitTimeoutTime = currentTime + timeout;
1188 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001189 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190
Yi Kong9b14ac62018-07-17 13:48:38 -07001191 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001192 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 }
Robert Carr740167f2018-10-11 19:03:41 -07001194 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1195 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 }
1197 }
1198 }
1199
1200 if (mInputTargetWaitTimeoutExpired) {
1201 return INPUT_EVENT_INJECTION_TIMED_OUT;
1202 }
1203
1204 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001205 onANRLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001206 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207
1208 // Force poll loop to wake up immediately on next iteration once we get the
1209 // ANR response back from the policy.
1210 *nextWakeupTime = LONG_LONG_MIN;
1211 return INPUT_EVENT_INJECTION_PENDING;
1212 } else {
1213 // Force poll loop to wake up when timeout is due.
1214 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1215 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1216 }
1217 return INPUT_EVENT_INJECTION_PENDING;
1218 }
1219}
1220
Robert Carr803535b2018-08-02 16:38:15 -07001221void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1222 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1223 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1224 state.removeWindowByToken(token);
1225 }
1226}
1227
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001228void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001229 nsecs_t newTimeout, const sp<IBinder>& inputConnectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 if (newTimeout > 0) {
1231 // Extend the timeout.
1232 mInputTargetWaitTimeoutTime = now() + newTimeout;
1233 } else {
1234 // Give up.
1235 mInputTargetWaitTimeoutExpired = true;
1236
1237 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001238 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001239 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001240 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001242 if (connection->status == Connection::STATUS_NORMAL) {
1243 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1244 "application not responding");
1245 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 }
1247 }
1248 }
1249}
1250
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001251nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1253 return currentTime - mInputTargetWaitStartTime;
1254 }
1255 return 0;
1256}
1257
1258void InputDispatcher::resetANRTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001259 if (DEBUG_FOCUS) {
1260 ALOGD("Resetting ANR timeouts.");
1261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262
1263 // Reset input target wait timeout.
1264 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001265 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266}
1267
Tiger Huang721e26f2018-07-24 22:26:19 +08001268/**
1269 * Get the display id that the given event should go to. If this event specifies a valid display id,
1270 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1271 * Focused display is the display that the user most recently interacted with.
1272 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001273int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001274 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001275 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001276 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001277 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1278 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001279 break;
1280 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001281 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001282 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1283 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001284 break;
1285 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001286 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001287 case EventEntry::Type::CONFIGURATION_CHANGED:
1288 case EventEntry::Type::DEVICE_RESET: {
1289 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001290 return ADISPLAY_ID_NONE;
1291 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001292 }
1293 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1294}
1295
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001297 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001298 std::vector<InputTarget>& inputTargets,
1299 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001301 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302
Tiger Huang721e26f2018-07-24 22:26:19 +08001303 int32_t displayId = getTargetDisplayId(entry);
1304 sp<InputWindowHandle> focusedWindowHandle =
1305 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1306 sp<InputApplicationHandle> focusedApplicationHandle =
1307 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1308
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 // If there is no currently focused window and no focused application
1310 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001311 if (focusedWindowHandle == nullptr) {
1312 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001313 injectionResult =
1314 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1315 nullptr, nextWakeupTime,
1316 "Waiting because no window has focus but there is "
1317 "a focused application that may eventually add a "
1318 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319 goto Unresponsive;
1320 }
1321
Arthur Hung3b413f22018-10-26 18:05:34 +08001322 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001323 "%" PRId32 ".",
1324 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1326 goto Failed;
1327 }
1328
1329 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001330 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1332 goto Failed;
1333 }
1334
Jeff Brownffb49772014-10-10 19:01:34 -07001335 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001336 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001337 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001338 injectionResult =
1339 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1340 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 goto Unresponsive;
1342 }
1343
1344 // Success! Output targets.
1345 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001346 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001347 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1348 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349
1350 // Done.
1351Failed:
1352Unresponsive:
1353 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001354 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001355 if (DEBUG_FOCUS) {
1356 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1357 "timeSpentWaitingForApplication=%0.1fms",
1358 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 return injectionResult;
1361}
1362
1363int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001364 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001365 std::vector<InputTarget>& inputTargets,
1366 nsecs_t* nextWakeupTime,
1367 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001368 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 enum InjectionPermission {
1370 INJECTION_PERMISSION_UNKNOWN,
1371 INJECTION_PERMISSION_GRANTED,
1372 INJECTION_PERMISSION_DENIED
1373 };
1374
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 // For security reasons, we defer updating the touch state until we are sure that
1376 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001377 int32_t displayId = entry.displayId;
1378 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1380
1381 // Update the touch state as needed based on the properties of the touch event.
1382 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1383 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1384 sp<InputWindowHandle> newHoverWindowHandle;
1385
Jeff Brownf086ddb2014-02-11 14:28:48 -08001386 // Copy current touch state into mTempTouchState.
1387 // This state is always reset at the end of this function, so if we don't find state
1388 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001389 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001390 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1391 if (oldStateIndex >= 0) {
1392 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1393 mTempTouchState.copyFrom(*oldState);
1394 }
1395
1396 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001397 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398 (mTempTouchState.deviceId != entry.deviceId || mTempTouchState.source != entry.source ||
1399 mTempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001400 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1401 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1402 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1403 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1404 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001405 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406 bool wrongDevice = false;
1407 if (newGesture) {
1408 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001409 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001410 if (DEBUG_FOCUS) {
1411 ALOGD("Dropping event because a pointer for a different device is already down "
1412 "in display %" PRId32,
1413 displayId);
1414 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001415 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1417 switchedDevice = false;
1418 wrongDevice = true;
1419 goto Failed;
1420 }
1421 mTempTouchState.reset();
1422 mTempTouchState.down = down;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001423 mTempTouchState.deviceId = entry.deviceId;
1424 mTempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 mTempTouchState.displayId = displayId;
1426 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001427 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001428 if (DEBUG_FOCUS) {
1429 ALOGI("Dropping move event because a pointer for a different device is already active "
1430 "in display %" PRId32,
1431 displayId);
1432 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001433 // TODO: test multiple simultaneous input streams.
1434 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1435 switchedDevice = false;
1436 wrongDevice = true;
1437 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 }
1439
1440 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1441 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1442
Garfield Tan00f511d2019-06-12 16:55:40 -07001443 int32_t x;
1444 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001446 // Always dispatch mouse events to cursor position.
1447 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001448 x = int32_t(entry.xCursorPosition);
1449 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001450 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001451 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1452 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001453 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001454 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001455 sp<InputWindowHandle> newTouchedWindowHandle =
1456 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1457 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001458
1459 std::vector<TouchedMonitor> newGestureMonitors = isDown
1460 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1461 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001464 if (newTouchedWindowHandle != nullptr &&
1465 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001466 // New window supports splitting, but we should never split mouse events.
1467 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 } else if (isSplit) {
1469 // New window does not support splitting but we have already split events.
1470 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001471 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 }
1473
1474 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001475 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 // Try to assign the pointer to the first foreground window we find, if there is one.
1477 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001478 }
1479
1480 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1481 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001482 "(%d, %d) in display %" PRId32 ".",
1483 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001484 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1485 goto Failed;
1486 }
1487
1488 if (newTouchedWindowHandle != nullptr) {
1489 // Set target flags.
1490 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1491 if (isSplit) {
1492 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001494 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1495 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1496 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1497 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1498 }
1499
1500 // Update hover state.
1501 if (isHoverAction) {
1502 newHoverWindowHandle = newTouchedWindowHandle;
1503 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1504 newHoverWindowHandle = mLastHoverWindowHandle;
1505 }
1506
1507 // Update the temporary touch state.
1508 BitSet32 pointerIds;
1509 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001510 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001511 pointerIds.markBit(pointerId);
1512 }
1513 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 }
1515
Michael Wright3dd60e22019-03-27 22:06:44 +00001516 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 } else {
1518 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1519
1520 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001521 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001522 if (DEBUG_FOCUS) {
1523 ALOGD("Dropping event because the pointer is not down or we previously "
1524 "dropped the pointer down event in display %" PRId32,
1525 displayId);
1526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1528 goto Failed;
1529 }
1530
1531 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001532 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001533 mTempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001534 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1535 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536
1537 sp<InputWindowHandle> oldTouchedWindowHandle =
1538 mTempTouchState.getFirstForegroundWindowHandle();
1539 sp<InputWindowHandle> newTouchedWindowHandle =
1540 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001541 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1542 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001543 if (DEBUG_FOCUS) {
1544 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1545 oldTouchedWindowHandle->getName().c_str(),
1546 newTouchedWindowHandle->getName().c_str(), displayId);
1547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 // Make a slippery exit from the old window.
1549 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001550 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1551 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552
1553 // Make a slippery entrance into the new window.
1554 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1555 isSplit = true;
1556 }
1557
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001558 int32_t targetFlags =
1559 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 if (isSplit) {
1561 targetFlags |= InputTarget::FLAG_SPLIT;
1562 }
1563 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1564 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1565 }
1566
1567 BitSet32 pointerIds;
1568 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001569 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 }
1571 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1572 }
1573 }
1574 }
1575
1576 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1577 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001578 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579#if DEBUG_HOVER
1580 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001581 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582#endif
1583 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001584 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1585 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 }
1587
1588 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001589 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590#if DEBUG_HOVER
1591 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001592 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593#endif
1594 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001595 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1596 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 }
1598 }
1599
1600 // Check permission to inject into all touched foreground windows and ensure there
1601 // is at least one touched foreground window.
1602 {
1603 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001604 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1606 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001607 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1609 injectionPermission = INJECTION_PERMISSION_DENIED;
1610 goto Failed;
1611 }
1612 }
1613 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001614 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1615 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001616 if (DEBUG_FOCUS) {
1617 ALOGD("Dropping event because there is no touched foreground window in display "
1618 "%" PRId32 " or gesture monitor to receive it.",
1619 displayId);
1620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1622 goto Failed;
1623 }
1624
1625 // Permission granted to injection into all touched foreground windows.
1626 injectionPermission = INJECTION_PERMISSION_GRANTED;
1627 }
1628
1629 // Check whether windows listening for outside touches are owned by the same UID. If it is
1630 // set the policy flag that we will not reveal coordinate information to this window.
1631 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1632 sp<InputWindowHandle> foregroundWindowHandle =
1633 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001634 if (foregroundWindowHandle) {
1635 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1636 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1637 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1638 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1639 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1640 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001641 InputTarget::FLAG_ZERO_COORDS,
1642 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 }
1645 }
1646 }
1647 }
1648
1649 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001650 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001652 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001653 std::string reason =
1654 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1655 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001656 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001657 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1658 touchedWindow.windowHandle,
1659 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 goto Unresponsive;
1661 }
1662 }
1663 }
1664
1665 // If this is the first pointer going down and the touched window has a wallpaper
1666 // then also add the touched wallpaper windows so they are locked in for the duration
1667 // of the touch gesture.
1668 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1669 // engine only supports touch events. We would need to add a mechanism similar
1670 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1671 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1672 sp<InputWindowHandle> foregroundWindowHandle =
1673 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001674 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001675 const std::vector<sp<InputWindowHandle>> windowHandles =
1676 getWindowHandlesLocked(displayId);
1677 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001679 if (info->displayId == displayId &&
1680 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1681 mTempTouchState
1682 .addOrUpdateWindow(windowHandle,
1683 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1684 InputTarget::
1685 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1686 InputTarget::FLAG_DISPATCH_AS_IS,
1687 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 }
1689 }
1690 }
1691 }
1692
1693 // Success! Output targets.
1694 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1695
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001696 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001698 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001699 }
1700
Michael Wright3dd60e22019-03-27 22:06:44 +00001701 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1702 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001703 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001704 }
1705
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706 // Drop the outside or hover touch windows since we will not care about them
1707 // in the next iteration.
1708 mTempTouchState.filterNonAsIsTouchWindows();
1709
1710Failed:
1711 // Check injection permission once and for all.
1712 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001713 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 injectionPermission = INJECTION_PERMISSION_GRANTED;
1715 } else {
1716 injectionPermission = INJECTION_PERMISSION_DENIED;
1717 }
1718 }
1719
1720 // Update final pieces of touch state if the injector had permission.
1721 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1722 if (!wrongDevice) {
1723 if (switchedDevice) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001724 if (DEBUG_FOCUS) {
1725 ALOGD("Conflicting pointer actions: Switched to a different device.");
1726 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 *outConflictingPointerActions = true;
1728 }
1729
1730 if (isHoverAction) {
1731 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001732 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001733 if (DEBUG_FOCUS) {
1734 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1735 "down.");
1736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 *outConflictingPointerActions = true;
1738 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001739 mTempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001740 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1741 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001742 mTempTouchState.deviceId = entry.deviceId;
1743 mTempTouchState.source = entry.source;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001744 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001746 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1747 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001749 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1751 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001752 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001753 if (DEBUG_FOCUS) {
1754 ALOGD("Conflicting pointer actions: Down received while already down.");
1755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 *outConflictingPointerActions = true;
1757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1759 // One pointer went up.
1760 if (isSplit) {
1761 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001762 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001764 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001765 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1767 touchedWindow.pointerIds.clearBit(pointerId);
1768 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001769 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 continue;
1771 }
1772 }
1773 i += 1;
1774 }
1775 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001776 }
1777
1778 // Save changes unless the action was scroll in which case the temporary touch
1779 // state was only valid for this one action.
1780 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1781 if (mTempTouchState.displayId >= 0) {
1782 if (oldStateIndex >= 0) {
1783 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1784 } else {
1785 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1786 }
1787 } else if (oldStateIndex >= 0) {
1788 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790 }
1791
1792 // Update hover state.
1793 mLastHoverWindowHandle = newHoverWindowHandle;
1794 }
1795 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001796 if (DEBUG_FOCUS) {
1797 ALOGD("Not updating touch focus because injection was denied.");
1798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 }
1800
1801Unresponsive:
1802 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1803 mTempTouchState.reset();
1804
1805 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001806 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001807 if (DEBUG_FOCUS) {
1808 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1809 "timeSpentWaitingForApplication=%0.1fms",
1810 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 return injectionResult;
1813}
1814
1815void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001816 int32_t targetFlags, BitSet32 pointerIds,
1817 std::vector<InputTarget>& inputTargets) {
Chavi Weingartenb38d8c62020-01-08 21:20:39 +00001818 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1819 if (inputChannel == nullptr) {
1820 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1821 return;
chaviw5d22a232019-12-11 16:47:32 -08001822 }
1823
Chavi Weingartenb38d8c62020-01-08 21:20:39 +00001824 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1825 InputTarget target;
1826 target.inputChannel = inputChannel;
1827 target.flags = targetFlags;
1828 target.xOffset = -windowInfo->frameLeft;
1829 target.yOffset = -windowInfo->frameTop;
1830 target.globalScaleFactor = windowInfo->globalScaleFactor;
1831 target.windowXScale = windowInfo->windowXScale;
1832 target.windowYScale = windowInfo->windowYScale;
1833 target.pointerIds = pointerIds;
1834 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835}
1836
Michael Wright3dd60e22019-03-27 22:06:44 +00001837void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001838 int32_t displayId, float xOffset,
1839 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001840 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1841 mGlobalMonitorsByDisplay.find(displayId);
1842
1843 if (it != mGlobalMonitorsByDisplay.end()) {
1844 const std::vector<Monitor>& monitors = it->second;
1845 for (const Monitor& monitor : monitors) {
1846 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 }
1849}
1850
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001851void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1852 float yOffset,
1853 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001854 InputTarget target;
1855 target.inputChannel = monitor.inputChannel;
1856 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingartenb38d8c62020-01-08 21:20:39 +00001857 target.xOffset = xOffset;
1858 target.yOffset = yOffset;
1859 target.pointerIds.clear();
1860 target.globalScaleFactor = 1.0f;
Michael Wright3dd60e22019-03-27 22:06:44 +00001861 inputTargets.push_back(target);
1862}
1863
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001865 const InjectionState* injectionState) {
1866 if (injectionState &&
1867 (windowHandle == nullptr ||
1868 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1869 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001870 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001872 "owned by uid %d",
1873 injectionState->injectorPid, injectionState->injectorUid,
1874 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 } else {
1876 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001877 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878 }
1879 return false;
1880 }
1881 return true;
1882}
1883
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001884bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1885 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001887 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1888 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 if (otherHandle == windowHandle) {
1890 break;
1891 }
1892
1893 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001894 if (otherInfo->displayId == displayId && otherInfo->visible &&
1895 !otherInfo->isTrustedOverlay() && otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896 return true;
1897 }
1898 }
1899 return false;
1900}
1901
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001902bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1903 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001904 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001905 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001906 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001907 if (otherHandle == windowHandle) {
1908 break;
1909 }
1910
1911 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001912 if (otherInfo->displayId == displayId && otherInfo->visible &&
1913 !otherInfo->isTrustedOverlay() && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001914 return true;
1915 }
1916 }
1917 return false;
1918}
1919
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001920std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
1921 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001922 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07001923 // If the window is paused then keep waiting.
1924 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001925 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001926 }
1927
1928 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001929 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001930 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001931 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001932 "registered with the input dispatcher. The window may be in the "
1933 "process of being removed.",
1934 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001935 }
1936
1937 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07001938 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001939 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001940 "The window may be in the process of being removed.",
1941 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07001942 }
1943
1944 // If the connection is backed up then keep waiting.
1945 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001946 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001947 "Outbound queue length: %zu. Wait queue length: %zu.",
1948 targetType, connection->outboundQueue.size(),
1949 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07001950 }
1951
1952 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001953 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07001954 // If the event is a key event, then we must wait for all previous events to
1955 // complete before delivering it because previous events may have the
1956 // side-effect of transferring focus to a different window and we want to
1957 // ensure that the following keys are sent to the new window.
1958 //
1959 // Suppose the user touches a button in a window then immediately presses "A".
1960 // If the button causes a pop-up window to appear then we want to ensure that
1961 // the "A" key is delivered to the new pop-up window. This is because users
1962 // often anticipate pending UI changes when typing on a keyboard.
1963 // To obtain this behavior, we must serialize key events with respect to all
1964 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001965 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001966 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001967 "finished processing all of the input events that were previously "
1968 "delivered to it. Outbound queue length: %zu. Wait queue length: "
1969 "%zu.",
1970 targetType, connection->outboundQueue.size(),
1971 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 }
Jeff Brownffb49772014-10-10 19:01:34 -07001973 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 // Touch events can always be sent to a window immediately because the user intended
1975 // to touch whatever was visible at the time. Even if focus changes or a new
1976 // window appears moments later, the touch event was meant to be delivered to
1977 // whatever window happened to be on screen at the time.
1978 //
1979 // Generic motion events, such as trackball or joystick events are a little trickier.
1980 // Like key events, generic motion events are delivered to the focused window.
1981 // Unlike key events, generic motion events don't tend to transfer focus to other
1982 // windows and it is not important for them to be serialized. So we prefer to deliver
1983 // generic motion events as soon as possible to improve efficiency and reduce lag
1984 // through batching.
1985 //
1986 // The one case where we pause input event delivery is when the wait queue is piling
1987 // up with lots of events because the application is not responding.
1988 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001989 if (!connection->waitQueue.empty() &&
1990 currentTime >=
1991 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001992 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001993 "finished processing certain input events that were delivered to "
1994 "it over "
1995 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
1996 "%0.1fms.",
1997 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1998 connection->waitQueue.size(),
1999 (currentTime - connection->waitQueue.front()->deliveryTime) *
2000 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 }
2002 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002003 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004}
2005
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002006std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 const sp<InputApplicationHandle>& applicationHandle,
2008 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002009 if (applicationHandle != nullptr) {
2010 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002011 std::string label(applicationHandle->getName());
2012 label += " - ";
2013 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 return label;
2015 } else {
2016 return applicationHandle->getName();
2017 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002018 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 return windowHandle->getName();
2020 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002021 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022 }
2023}
2024
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002025void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002026 if (eventEntry.type == EventEntry::Type::FOCUS) {
2027 // Focus events are passed to apps, but do not represent user activity.
2028 return;
2029 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002030 int32_t displayId = getTargetDisplayId(eventEntry);
2031 sp<InputWindowHandle> focusedWindowHandle =
2032 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2033 if (focusedWindowHandle != nullptr) {
2034 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2036#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002037 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038#endif
2039 return;
2040 }
2041 }
2042
2043 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002044 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002045 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002046 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2047 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002048 return;
2049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002051 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002052 eventType = USER_ACTIVITY_EVENT_TOUCH;
2053 }
2054 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002056 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002057 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2058 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002059 return;
2060 }
2061 eventType = USER_ACTIVITY_EVENT_BUTTON;
2062 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002064 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002065 case EventEntry::Type::CONFIGURATION_CHANGED:
2066 case EventEntry::Type::DEVICE_RESET: {
2067 LOG_ALWAYS_FATAL("%s events are not user activity",
2068 EventEntry::typeToString(eventEntry.type));
2069 break;
2070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 }
2072
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002073 std::unique_ptr<CommandEntry> commandEntry =
2074 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002075 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002077 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078}
2079
2080void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002081 const sp<Connection>& connection,
2082 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002083 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002084 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002085 std::string message =
2086 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
2087 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002088 ATRACE_NAME(message.c_str());
2089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090#if DEBUG_DISPATCH_CYCLE
2091 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002092 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
2093 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002094 connection->getInputChannelName().c_str(), inputTarget.flags, inputTarget.xOffset,
2095 inputTarget.yOffset, inputTarget.globalScaleFactor, inputTarget.windowXScale,
2096 inputTarget.windowYScale, inputTarget.pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097#endif
2098
2099 // Skip this event if the connection status is not normal.
2100 // We don't want to enqueue additional outbound events if the connection is broken.
2101 if (connection->status != Connection::STATUS_NORMAL) {
2102#if DEBUG_DISPATCH_CYCLE
2103 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002104 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105#endif
2106 return;
2107 }
2108
2109 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002110 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2111 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2112 "Entry type %s should not have FLAG_SPLIT",
2113 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002115 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002116 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002117 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002118 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119 if (!splitMotionEntry) {
2120 return; // split event was dropped
2121 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002122 if (DEBUG_FOCUS) {
2123 ALOGD("channel '%s' ~ Split motion event.",
2124 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002125 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002126 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002127 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128 splitMotionEntry->release();
2129 return;
2130 }
2131 }
2132
2133 // Not splitting. Enqueue dispatch entries for the event as is.
2134 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2135}
2136
2137void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002138 const sp<Connection>& connection,
2139 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002140 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002141 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002142 std::string message =
2143 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32
2144 ")",
2145 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002146 ATRACE_NAME(message.c_str());
2147 }
2148
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002149 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150
2151 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002152 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002153 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002154 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002155 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002156 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002157 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002158 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002159 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002160 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002161 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002162 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002163 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164
2165 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002166 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 startDispatchCycleLocked(currentTime, connection);
2168 }
2169}
2170
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002171void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2172 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002173 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002174 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002175 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002176 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2177 connection->getInputChannelName().c_str(),
2178 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002179 ATRACE_NAME(message.c_str());
2180 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002181 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182 if (!(inputTargetFlags & dispatchMode)) {
2183 return;
2184 }
2185 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2186
2187 // This is a new event.
2188 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002189 std::unique_ptr<DispatchEntry> dispatchEntry =
2190 std::make_unique<DispatchEntry>(eventEntry, // increments ref
2191 inputTargetFlags, inputTarget.xOffset,
2192 inputTarget.yOffset, inputTarget.globalScaleFactor,
2193 inputTarget.windowXScale, inputTarget.windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194
2195 // Apply target flags and update the connection's input state.
2196 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002197 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002198 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
2199 dispatchEntry->resolvedAction = keyEntry.action;
2200 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002202 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2203 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002205 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2206 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002208 return; // skip the inconsistent event
2209 }
2210 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002213 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002214 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002215 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2216 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2217 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2218 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2219 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2220 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2221 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2222 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2223 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2224 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2225 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002226 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002227 }
2228 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002229 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2230 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002232 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2233 "event",
2234 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002236 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002239 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002240 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2241 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2242 }
2243 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2244 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2245 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002247 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2248 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002250 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2251 "event",
2252 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 return; // skip the inconsistent event
2255 }
2256
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002257 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002258 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002259
2260 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002262 case EventEntry::Type::FOCUS: {
2263 break;
2264 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002265 case EventEntry::Type::CONFIGURATION_CHANGED:
2266 case EventEntry::Type::DEVICE_RESET: {
2267 LOG_ALWAYS_FATAL("%s events should not go to apps",
2268 EventEntry::typeToString(eventEntry->type));
2269 break;
2270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 }
2272
2273 // Remember that we are waiting for this dispatch to complete.
2274 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002275 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 }
2277
2278 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002279 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002280 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002281}
2282
chaviwfd6d3512019-03-25 13:23:49 -07002283void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002284 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002285 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002286 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2287 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002288 return;
2289 }
2290
2291 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2292 if (inputWindowHandle == nullptr) {
2293 return;
2294 }
2295
chaviw8c9cf542019-03-25 13:02:48 -07002296 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002297 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002298
2299 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2300
2301 if (!hasFocusChanged) {
2302 return;
2303 }
2304
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002305 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2306 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002307 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002308 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309}
2310
2311void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002312 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002313 if (ATRACE_ENABLED()) {
2314 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002315 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002316 ATRACE_NAME(message.c_str());
2317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002319 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320#endif
2321
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002322 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2323 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 dispatchEntry->deliveryTime = currentTime;
2325
2326 // Publish the event.
2327 status_t status;
2328 EventEntry* eventEntry = dispatchEntry->eventEntry;
2329 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002330 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002331 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002333 // Publish the key event.
2334 status = connection->inputPublisher
2335 .publishKeyEvent(dispatchEntry->seq, keyEntry->deviceId,
2336 keyEntry->source, keyEntry->displayId,
2337 dispatchEntry->resolvedAction,
2338 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2339 keyEntry->scanCode, keyEntry->metaState,
2340 keyEntry->repeatCount, keyEntry->downTime,
2341 keyEntry->eventTime);
2342 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 }
2344
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002345 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002346 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002348 PointerCoords scaledCoords[MAX_POINTERS];
2349 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2350
2351 // Set the X and Y offset depending on the input source.
2352 float xOffset, yOffset;
2353 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2354 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2355 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2356 float wxs = dispatchEntry->windowXScale;
2357 float wys = dispatchEntry->windowYScale;
2358 xOffset = dispatchEntry->xOffset * wxs;
2359 yOffset = dispatchEntry->yOffset * wys;
2360 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
2361 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2362 scaledCoords[i] = motionEntry->pointerCoords[i];
2363 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
2364 }
2365 usingCoords = scaledCoords;
2366 }
2367 } else {
2368 xOffset = 0.0f;
2369 yOffset = 0.0f;
2370
2371 // We don't want the dispatch target to know.
2372 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2373 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2374 scaledCoords[i].clear();
2375 }
2376 usingCoords = scaledCoords;
2377 }
2378 }
2379
2380 // Publish the motion event.
2381 status = connection->inputPublisher
2382 .publishMotionEvent(dispatchEntry->seq, motionEntry->deviceId,
2383 motionEntry->source, motionEntry->displayId,
2384 dispatchEntry->resolvedAction,
2385 motionEntry->actionButton,
2386 dispatchEntry->resolvedFlags,
2387 motionEntry->edgeFlags, motionEntry->metaState,
2388 motionEntry->buttonState,
2389 motionEntry->classification, xOffset, yOffset,
2390 motionEntry->xPrecision,
2391 motionEntry->yPrecision,
2392 motionEntry->xCursorPosition,
2393 motionEntry->yCursorPosition,
2394 motionEntry->downTime, motionEntry->eventTime,
2395 motionEntry->pointerCount,
2396 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002397 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002398 break;
2399 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002400 case EventEntry::Type::FOCUS: {
2401 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2402 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
2403 focusEntry->hasFocus,
2404 mInTouchMode);
2405 break;
2406 }
2407
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002408 case EventEntry::Type::CONFIGURATION_CHANGED:
2409 case EventEntry::Type::DEVICE_RESET: {
2410 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2411 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002412 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414 }
2415
2416 // Check the result.
2417 if (status) {
2418 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002419 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002421 "This is unexpected because the wait queue is empty, so the pipe "
2422 "should be empty and we shouldn't have any problems writing an "
2423 "event to it, status=%d",
2424 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2426 } else {
2427 // Pipe is full and we are waiting for the app to finish process some events
2428 // before sending more events to it.
2429#if DEBUG_DISPATCH_CYCLE
2430 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002431 "waiting for the application to catch up",
2432 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433#endif
2434 connection->inputPublisherBlocked = true;
2435 }
2436 } else {
2437 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002438 "status=%d",
2439 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2441 }
2442 return;
2443 }
2444
2445 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002446 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2447 connection->outboundQueue.end(),
2448 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002449 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002450 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002451 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 }
2453}
2454
2455void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002456 const sp<Connection>& connection, uint32_t seq,
2457 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458#if DEBUG_DISPATCH_CYCLE
2459 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002460 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002461#endif
2462
2463 connection->inputPublisherBlocked = false;
2464
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002465 if (connection->status == Connection::STATUS_BROKEN ||
2466 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 return;
2468 }
2469
2470 // Notify other system components and prepare to start the next dispatch cycle.
2471 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2472}
2473
2474void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002475 const sp<Connection>& connection,
2476 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477#if DEBUG_DISPATCH_CYCLE
2478 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002479 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480#endif
2481
2482 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002483 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002484 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002485 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002486 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487
2488 // The connection appears to be unrecoverably broken.
2489 // Ignore already broken or zombie connections.
2490 if (connection->status == Connection::STATUS_NORMAL) {
2491 connection->status = Connection::STATUS_BROKEN;
2492
2493 if (notify) {
2494 // Notify other system components.
2495 onDispatchCycleBrokenLocked(currentTime, connection);
2496 }
2497 }
2498}
2499
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002500void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2501 while (!queue.empty()) {
2502 DispatchEntry* dispatchEntry = queue.front();
2503 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002504 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 }
2506}
2507
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002508void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002510 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 }
2512 delete dispatchEntry;
2513}
2514
2515int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2516 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2517
2518 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002519 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002521 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002523 "fd=%d, events=0x%x",
2524 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 return 0; // remove the callback
2526 }
2527
2528 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002529 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2531 if (!(events & ALOOPER_EVENT_INPUT)) {
2532 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533 "events=0x%x",
2534 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 return 1;
2536 }
2537
2538 nsecs_t currentTime = now();
2539 bool gotOne = false;
2540 status_t status;
2541 for (;;) {
2542 uint32_t seq;
2543 bool handled;
2544 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2545 if (status) {
2546 break;
2547 }
2548 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2549 gotOne = true;
2550 }
2551 if (gotOne) {
2552 d->runCommandsLockedInterruptible();
2553 if (status == WOULD_BLOCK) {
2554 return 1;
2555 }
2556 }
2557
2558 notify = status != DEAD_OBJECT || !connection->monitor;
2559 if (notify) {
2560 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 }
2563 } else {
2564 // Monitor channels are never explicitly unregistered.
2565 // We do it automatically when the remote endpoint is closed so don't warn
2566 // about them.
2567 notify = !connection->monitor;
2568 if (notify) {
2569 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002570 "events=0x%x",
2571 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 }
2573 }
2574
2575 // Unregister the channel.
2576 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2577 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002578 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579}
2580
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002581void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002583 for (const auto& pair : mConnectionsByFd) {
2584 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 }
2586}
2587
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002588void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002589 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002590 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2591 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2592}
2593
2594void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2595 const CancelationOptions& options,
2596 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2597 for (const auto& it : monitorsByDisplay) {
2598 const std::vector<Monitor>& monitors = it.second;
2599 for (const Monitor& monitor : monitors) {
2600 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002601 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002602 }
2603}
2604
Michael Wrightd02c5b62014-02-10 15:10:22 -08002605void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2606 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002607 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002608 if (connection == nullptr) {
2609 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002611
2612 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613}
2614
2615void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2616 const sp<Connection>& connection, const CancelationOptions& options) {
2617 if (connection->status == Connection::STATUS_BROKEN) {
2618 return;
2619 }
2620
2621 nsecs_t currentTime = now();
2622
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002623 std::vector<EventEntry*> cancelationEvents =
2624 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002626 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002628 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002629 "with reality: %s, mode=%d.",
2630 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2631 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632#endif
2633 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002634 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002635 switch (cancelationEventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002636 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002637 logOutboundKeyDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002638 static_cast<const KeyEntry&>(*cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002639 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002640 }
2641 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002642 logOutboundMotionDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002643 static_cast<const MotionEntry&>(
2644 *cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002645 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002646 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002647 case EventEntry::Type::FOCUS: {
2648 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2649 break;
2650 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002651 case EventEntry::Type::CONFIGURATION_CHANGED:
2652 case EventEntry::Type::DEVICE_RESET: {
2653 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2654 EventEntry::typeToString(cancelationEventEntry->type));
2655 break;
2656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 }
2658
2659 InputTarget target;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002660 sp<InputWindowHandle> windowHandle =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002661 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002662 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingartenb38d8c62020-01-08 21:20:39 +00002664 target.xOffset = -windowInfo->frameLeft;
2665 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002666 target.globalScaleFactor = windowInfo->globalScaleFactor;
Chavi Weingartenb38d8c62020-01-08 21:20:39 +00002667 target.windowXScale = windowInfo->windowXScale;
2668 target.windowYScale = windowInfo->windowYScale;
2669 } else {
2670 target.xOffset = 0;
2671 target.yOffset = 0;
2672 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673 }
2674 target.inputChannel = connection->inputChannel;
2675 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2676
chaviw8c9cf542019-03-25 13:02:48 -07002677 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002678 target, InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679
2680 cancelationEventEntry->release();
2681 }
2682
2683 startDispatchCycleLocked(currentTime, connection);
2684 }
2685}
2686
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002687MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002688 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 ALOG_ASSERT(pointerIds.value != 0);
2690
2691 uint32_t splitPointerIndexMap[MAX_POINTERS];
2692 PointerProperties splitPointerProperties[MAX_POINTERS];
2693 PointerCoords splitPointerCoords[MAX_POINTERS];
2694
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002695 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696 uint32_t splitPointerCount = 0;
2697
2698 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002699 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002701 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702 uint32_t pointerId = uint32_t(pointerProperties.id);
2703 if (pointerIds.hasBit(pointerId)) {
2704 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2705 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2706 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002707 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 splitPointerCount += 1;
2709 }
2710 }
2711
2712 if (splitPointerCount != pointerIds.count()) {
2713 // This is bad. We are missing some of the pointers that we expected to deliver.
2714 // Most likely this indicates that we received an ACTION_MOVE events that has
2715 // different pointer ids than we expected based on the previous ACTION_DOWN
2716 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2717 // in this way.
2718 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002719 "we expected there to be %d pointers. This probably means we received "
2720 "a broken sequence of pointer ids from the input device.",
2721 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002722 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723 }
2724
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002725 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002727 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2728 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2730 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002731 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732 uint32_t pointerId = uint32_t(pointerProperties.id);
2733 if (pointerIds.hasBit(pointerId)) {
2734 if (pointerIds.count() == 1) {
2735 // The first/last pointer went down/up.
2736 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002737 ? AMOTION_EVENT_ACTION_DOWN
2738 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 } else {
2740 // A secondary pointer went down/up.
2741 uint32_t splitPointerIndex = 0;
2742 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2743 splitPointerIndex += 1;
2744 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002745 action = maskedAction |
2746 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747 }
2748 } else {
2749 // An unrelated pointer changed.
2750 action = AMOTION_EVENT_ACTION_MOVE;
2751 }
2752 }
2753
Garfield Tan00f511d2019-06-12 16:55:40 -07002754 MotionEntry* splitMotionEntry =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002755 new MotionEntry(originalMotionEntry.sequenceNum, originalMotionEntry.eventTime,
2756 originalMotionEntry.deviceId, originalMotionEntry.source,
2757 originalMotionEntry.displayId, originalMotionEntry.policyFlags, action,
2758 originalMotionEntry.actionButton, originalMotionEntry.flags,
2759 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2760 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2761 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2762 originalMotionEntry.xCursorPosition,
2763 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002764 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002766 if (originalMotionEntry.injectionState) {
2767 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768 splitMotionEntry->injectionState->refCount += 1;
2769 }
2770
2771 return splitMotionEntry;
2772}
2773
2774void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2775#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002776 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777#endif
2778
2779 bool needWake;
2780 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002781 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782
Prabir Pradhan42611e02018-11-27 14:04:02 -08002783 ConfigurationChangedEntry* newEntry =
2784 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 needWake = enqueueInboundEventLocked(newEntry);
2786 } // release lock
2787
2788 if (needWake) {
2789 mLooper->wake();
2790 }
2791}
2792
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002793/**
2794 * If one of the meta shortcuts is detected, process them here:
2795 * Meta + Backspace -> generate BACK
2796 * Meta + Enter -> generate HOME
2797 * This will potentially overwrite keyCode and metaState.
2798 */
2799void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002800 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002801 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2802 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2803 if (keyCode == AKEYCODE_DEL) {
2804 newKeyCode = AKEYCODE_BACK;
2805 } else if (keyCode == AKEYCODE_ENTER) {
2806 newKeyCode = AKEYCODE_HOME;
2807 }
2808 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002809 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002810 struct KeyReplacement replacement = {keyCode, deviceId};
2811 mReplacedKeys.add(replacement, newKeyCode);
2812 keyCode = newKeyCode;
2813 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2814 }
2815 } else if (action == AKEY_EVENT_ACTION_UP) {
2816 // In order to maintain a consistent stream of up and down events, check to see if the key
2817 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2818 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002819 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002820 struct KeyReplacement replacement = {keyCode, deviceId};
2821 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2822 if (index >= 0) {
2823 keyCode = mReplacedKeys.valueAt(index);
2824 mReplacedKeys.removeItemsAt(index);
2825 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2826 }
2827 }
2828}
2829
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2831#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002832 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2833 "policyFlags=0x%x, action=0x%x, "
2834 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2835 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2836 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2837 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838#endif
2839 if (!validateKeyEvent(args->action)) {
2840 return;
2841 }
2842
2843 uint32_t policyFlags = args->policyFlags;
2844 int32_t flags = args->flags;
2845 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002846 // InputDispatcher tracks and generates key repeats on behalf of
2847 // whatever notifies it, so repeatCount should always be set to 0
2848 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2850 policyFlags |= POLICY_FLAG_VIRTUAL;
2851 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 if (policyFlags & POLICY_FLAG_FUNCTION) {
2854 metaState |= AMETA_FUNCTION_ON;
2855 }
2856
2857 policyFlags |= POLICY_FLAG_TRUSTED;
2858
Michael Wright78f24442014-08-06 15:55:28 -07002859 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002860 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002861
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862 KeyEvent event;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002863 event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2864 args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865
Michael Wright2b3c3302018-03-02 17:19:13 +00002866 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002868 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2869 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002870 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002871 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 bool needWake;
2874 { // acquire lock
2875 mLock.lock();
2876
2877 if (shouldSendKeyToInputFilterLocked(args)) {
2878 mLock.unlock();
2879
2880 policyFlags |= POLICY_FLAG_FILTERED;
2881 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2882 return; // event was consumed by the filter
2883 }
2884
2885 mLock.lock();
2886 }
2887
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002888 KeyEntry* newEntry =
2889 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2890 args->displayId, policyFlags, args->action, flags, keyCode,
2891 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892
2893 needWake = enqueueInboundEventLocked(newEntry);
2894 mLock.unlock();
2895 } // release lock
2896
2897 if (needWake) {
2898 mLooper->wake();
2899 }
2900}
2901
2902bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2903 return mInputFilterEnabled;
2904}
2905
2906void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2907#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002908 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan00f511d2019-06-12 16:55:40 -07002909 ", policyFlags=0x%x, "
2910 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
2911 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07002912 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan00f511d2019-06-12 16:55:40 -07002913 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2914 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Jaewan Kim372fbe42019-10-02 10:58:46 +09002915 args->edgeFlags, args->xPrecision, args->yPrecision, args->xCursorPosition,
Garfield Tan00f511d2019-06-12 16:55:40 -07002916 args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917 for (uint32_t i = 0; i < args->pointerCount; i++) {
2918 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 "x=%f, y=%f, pressure=%f, size=%f, "
2920 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2921 "orientation=%f",
2922 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2923 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2924 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2925 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2926 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2927 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2928 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2929 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2930 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2931 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932 }
2933#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002934 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2935 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936 return;
2937 }
2938
2939 uint32_t policyFlags = args->policyFlags;
2940 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002941
2942 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002943 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002944 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2945 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002946 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948
2949 bool needWake;
2950 { // acquire lock
2951 mLock.lock();
2952
2953 if (shouldSendMotionToInputFilterLocked(args)) {
2954 mLock.unlock();
2955
2956 MotionEvent event;
Garfield Tan00f511d2019-06-12 16:55:40 -07002957 event.initialize(args->deviceId, args->source, args->displayId, args->action,
2958 args->actionButton, args->flags, args->edgeFlags, args->metaState,
2959 args->buttonState, args->classification, 0, 0, args->xPrecision,
2960 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2961 args->downTime, args->eventTime, args->pointerCount,
2962 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002963
2964 policyFlags |= POLICY_FLAG_FILTERED;
2965 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2966 return; // event was consumed by the filter
2967 }
2968
2969 mLock.lock();
2970 }
2971
2972 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07002973 MotionEntry* newEntry =
2974 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2975 args->displayId, policyFlags, args->action, args->actionButton,
2976 args->flags, args->metaState, args->buttonState,
2977 args->classification, args->edgeFlags, args->xPrecision,
2978 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2979 args->downTime, args->pointerCount, args->pointerProperties,
2980 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002981
2982 needWake = enqueueInboundEventLocked(newEntry);
2983 mLock.unlock();
2984 } // release lock
2985
2986 if (needWake) {
2987 mLooper->wake();
2988 }
2989}
2990
2991bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002992 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993}
2994
2995void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2996#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002997 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002998 "switchMask=0x%08x",
2999 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000#endif
3001
3002 uint32_t policyFlags = args->policyFlags;
3003 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003004 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005}
3006
3007void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3008#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003009 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3010 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011#endif
3012
3013 bool needWake;
3014 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003015 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016
Prabir Pradhan42611e02018-11-27 14:04:02 -08003017 DeviceResetEntry* newEntry =
3018 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019 needWake = enqueueInboundEventLocked(newEntry);
3020 } // release lock
3021
3022 if (needWake) {
3023 mLooper->wake();
3024 }
3025}
3026
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003027int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3028 int32_t injectorUid, int32_t syncMode,
3029 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030#if DEBUG_INBOUND_EVENT_DETAILS
3031 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003032 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
3033 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034#endif
3035
3036 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
3037
3038 policyFlags |= POLICY_FLAG_INJECTED;
3039 if (hasInjectionPermission(injectorPid, injectorUid)) {
3040 policyFlags |= POLICY_FLAG_TRUSTED;
3041 }
3042
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003043 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003045 case AINPUT_EVENT_TYPE_KEY: {
3046 KeyEvent keyEvent;
3047 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
3048 int32_t action = keyEvent.getAction();
3049 if (!validateKeyEvent(action)) {
3050 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003053 int32_t flags = keyEvent.getFlags();
3054 int32_t keyCode = keyEvent.getKeyCode();
3055 int32_t metaState = keyEvent.getMetaState();
3056 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
3057 /*byref*/ keyCode, /*byref*/ metaState);
3058 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
3059 keyEvent.getDisplayId(), action, flags, keyCode,
3060 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
3061 keyEvent.getDownTime(), keyEvent.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003063 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3064 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003065 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003066
3067 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3068 android::base::Timer t;
3069 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3070 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3071 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3072 std::to_string(t.duration().count()).c_str());
3073 }
3074 }
3075
3076 mLock.lock();
3077 KeyEntry* injectedEntry =
3078 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
3079 keyEvent.getDeviceId(), keyEvent.getSource(),
3080 keyEvent.getDisplayId(), policyFlags, action, flags,
3081 keyEvent.getKeyCode(), keyEvent.getScanCode(),
3082 keyEvent.getMetaState(), keyEvent.getRepeatCount(),
3083 keyEvent.getDownTime());
3084 injectedEntries.push(injectedEntry);
3085 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 }
3087
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 case AINPUT_EVENT_TYPE_MOTION: {
3089 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3090 int32_t action = motionEvent->getAction();
3091 size_t pointerCount = motionEvent->getPointerCount();
3092 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3093 int32_t actionButton = motionEvent->getActionButton();
3094 int32_t displayId = motionEvent->getDisplayId();
3095 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3096 return INPUT_EVENT_INJECTION_FAILED;
3097 }
3098
3099 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3100 nsecs_t eventTime = motionEvent->getEventTime();
3101 android::base::Timer t;
3102 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3103 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3104 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3105 std::to_string(t.duration().count()).c_str());
3106 }
3107 }
3108
3109 mLock.lock();
3110 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3111 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3112 MotionEntry* injectedEntry =
Garfield Tan00f511d2019-06-12 16:55:40 -07003113 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3114 motionEvent->getDeviceId(), motionEvent->getSource(),
3115 motionEvent->getDisplayId(), policyFlags, action, actionButton,
3116 motionEvent->getFlags(), motionEvent->getMetaState(),
3117 motionEvent->getButtonState(), motionEvent->getClassification(),
3118 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3119 motionEvent->getYPrecision(),
3120 motionEvent->getRawXCursorPosition(),
3121 motionEvent->getRawYCursorPosition(),
3122 motionEvent->getDownTime(), uint32_t(pointerCount),
3123 pointerProperties, samplePointerCoords,
3124 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003125 injectedEntries.push(injectedEntry);
3126 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3127 sampleEventTimes += 1;
3128 samplePointerCoords += pointerCount;
3129 MotionEntry* nextInjectedEntry =
3130 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3131 motionEvent->getDeviceId(), motionEvent->getSource(),
3132 motionEvent->getDisplayId(), policyFlags, action,
3133 actionButton, motionEvent->getFlags(),
3134 motionEvent->getMetaState(), motionEvent->getButtonState(),
3135 motionEvent->getClassification(),
3136 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3137 motionEvent->getYPrecision(),
3138 motionEvent->getRawXCursorPosition(),
3139 motionEvent->getRawYCursorPosition(),
3140 motionEvent->getDownTime(), uint32_t(pointerCount),
3141 pointerProperties, samplePointerCoords,
3142 motionEvent->getXOffset(), motionEvent->getYOffset());
3143 injectedEntries.push(nextInjectedEntry);
3144 }
3145 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003148 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003149 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003150 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 }
3152
3153 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3154 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3155 injectionState->injectionIsAsync = true;
3156 }
3157
3158 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003159 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160
3161 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003162 while (!injectedEntries.empty()) {
3163 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3164 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 }
3166
3167 mLock.unlock();
3168
3169 if (needWake) {
3170 mLooper->wake();
3171 }
3172
3173 int32_t injectionResult;
3174 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003175 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176
3177 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3178 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3179 } else {
3180 for (;;) {
3181 injectionResult = injectionState->injectionResult;
3182 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3183 break;
3184 }
3185
3186 nsecs_t remainingTimeout = endTime - now();
3187 if (remainingTimeout <= 0) {
3188#if DEBUG_INJECTION
3189 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003190 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191#endif
3192 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3193 break;
3194 }
3195
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003196 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 }
3198
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003199 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3200 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 while (injectionState->pendingForegroundDispatches != 0) {
3202#if DEBUG_INJECTION
3203 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003204 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205#endif
3206 nsecs_t remainingTimeout = endTime - now();
3207 if (remainingTimeout <= 0) {
3208#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3210 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211#endif
3212 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3213 break;
3214 }
3215
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003216 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 }
3218 }
3219 }
3220
3221 injectionState->release();
3222 } // release lock
3223
3224#if DEBUG_INJECTION
3225 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 "injectorPid=%d, injectorUid=%d",
3227 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228#endif
3229
3230 return injectionResult;
3231}
3232
3233bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003234 return injectorUid == 0 ||
3235 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236}
3237
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003238void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 InjectionState* injectionState = entry->injectionState;
3240 if (injectionState) {
3241#if DEBUG_INJECTION
3242 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 "injectorPid=%d, injectorUid=%d",
3244 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245#endif
3246
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003247 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 // Log the outcome since the injector did not wait for the injection result.
3249 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003250 case INPUT_EVENT_INJECTION_SUCCEEDED:
3251 ALOGV("Asynchronous input event injection succeeded.");
3252 break;
3253 case INPUT_EVENT_INJECTION_FAILED:
3254 ALOGW("Asynchronous input event injection failed.");
3255 break;
3256 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3257 ALOGW("Asynchronous input event injection permission denied.");
3258 break;
3259 case INPUT_EVENT_INJECTION_TIMED_OUT:
3260 ALOGW("Asynchronous input event injection timed out.");
3261 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262 }
3263 }
3264
3265 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003266 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267 }
3268}
3269
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003270void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271 InjectionState* injectionState = entry->injectionState;
3272 if (injectionState) {
3273 injectionState->pendingForegroundDispatches += 1;
3274 }
3275}
3276
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003277void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278 InjectionState* injectionState = entry->injectionState;
3279 if (injectionState) {
3280 injectionState->pendingForegroundDispatches -= 1;
3281
3282 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003283 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284 }
3285 }
3286}
3287
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003288std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3289 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003290 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003291}
3292
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003294 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003295 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003296 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3297 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003298 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003299 return windowHandle;
3300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301 }
3302 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003303 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304}
3305
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003306bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003307 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003308 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3309 for (const sp<InputWindowHandle>& handle : windowHandles) {
3310 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003311 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003312 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003313 ", but it should belong to display %" PRId32,
3314 windowHandle->getName().c_str(), it.first,
3315 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003316 }
3317 return true;
3318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319 }
3320 }
3321 return false;
3322}
3323
Robert Carr5c8a0262018-10-03 16:30:44 -07003324sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3325 size_t count = mInputChannelsByToken.count(token);
3326 if (count == 0) {
3327 return nullptr;
3328 }
3329 return mInputChannelsByToken.at(token);
3330}
3331
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003332void InputDispatcher::updateWindowHandlesForDisplayLocked(
3333 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3334 if (inputWindowHandles.empty()) {
3335 // Remove all handles on a display if there are no windows left.
3336 mWindowHandlesByDisplay.erase(displayId);
3337 return;
3338 }
3339
3340 // Since we compare the pointer of input window handles across window updates, we need
3341 // to make sure the handle object for the same window stays unchanged across updates.
3342 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003343 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003344 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003345 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003346 }
3347
3348 std::vector<sp<InputWindowHandle>> newHandles;
3349 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3350 if (!handle->updateInfo()) {
3351 // handle no longer valid
3352 continue;
3353 }
3354
3355 const InputWindowInfo* info = handle->getInfo();
3356 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3357 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3358 const bool noInputChannel =
3359 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3360 const bool canReceiveInput =
3361 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3362 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3363 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003364 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003365 handle->getName().c_str());
3366 }
3367 continue;
3368 }
3369
3370 if (info->displayId != displayId) {
3371 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3372 handle->getName().c_str(), displayId, info->displayId);
3373 continue;
3374 }
3375
chaviwaf87b3e2019-10-01 16:59:28 -07003376 if (oldHandlesById.find(handle->getId()) != oldHandlesById.end()) {
3377 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003378 oldHandle->updateFrom(handle);
3379 newHandles.push_back(oldHandle);
3380 } else {
3381 newHandles.push_back(handle);
3382 }
3383 }
3384
3385 // Insert or replace
3386 mWindowHandlesByDisplay[displayId] = newHandles;
3387}
3388
Arthur Hungb92218b2018-08-14 12:00:21 +08003389/**
3390 * Called from InputManagerService, update window handle list by displayId that can receive input.
3391 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3392 * If set an empty list, remove all handles from the specific display.
3393 * For focused handle, check if need to change and send a cancel event to previous one.
3394 * For removed handle, check if need to send a cancel event if already in touch.
3395 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003396void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003397 int32_t displayId,
3398 const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003399 if (DEBUG_FOCUS) {
3400 std::string windowList;
3401 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3402 windowList += iwh->getName() + " ";
3403 }
3404 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003407 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408
Arthur Hungb92218b2018-08-14 12:00:21 +08003409 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003410 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3411 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003413 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
3414
Tiger Huang721e26f2018-07-24 22:26:19 +08003415 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 bool foundHoveredWindow = false;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003417 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3418 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3419 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3420 windowHandle->getInfo()->visible) {
3421 newFocusedWindowHandle = windowHandle;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003422 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003423 if (windowHandle == mLastHoverWindowHandle) {
3424 foundHoveredWindow = true;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 }
3427
3428 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003429 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 }
3431
Tiger Huang721e26f2018-07-24 22:26:19 +08003432 sp<InputWindowHandle> oldFocusedWindowHandle =
3433 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3434
chaviwaf87b3e2019-10-01 16:59:28 -07003435 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003436 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003437 if (DEBUG_FOCUS) {
3438 ALOGD("Focus left window: %s in display %" PRId32,
3439 oldFocusedWindowHandle->getName().c_str(), displayId);
3440 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003441 sp<InputChannel> focusedInputChannel =
3442 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003443 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003445 "focus left window");
3446 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003447 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003449 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003451 if (newFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003452 if (DEBUG_FOCUS) {
3453 ALOGD("Focus entered window: %s in display %" PRId32,
3454 newFocusedWindowHandle->getName().c_str(), displayId);
3455 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003456 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003457 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458 }
Robert Carrf759f162018-11-13 12:57:11 -08003459
3460 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003461 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463 }
3464
Arthur Hungb92218b2018-08-14 12:00:21 +08003465 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3466 if (stateIndex >= 0) {
3467 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003468 for (size_t i = 0; i < state.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003469 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003470 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003471 if (DEBUG_FOCUS) {
3472 ALOGD("Touched window was removed: %s in display %" PRId32,
3473 touchedWindow.windowHandle->getName().c_str(), displayId);
3474 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003475 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003476 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003477 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003478 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003479 "touched window was removed");
3480 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3481 options);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003482 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003483 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003484 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003485 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487 }
3488 }
3489
3490 // Release information for windows that are no longer present.
3491 // This ensures that unused input channels are released promptly.
3492 // Otherwise, they might stick around until the window handle is destroyed
3493 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003494 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003495 if (!hasWindowHandleLocked(oldWindowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003496 if (DEBUG_FOCUS) {
3497 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
3498 }
Arthur Hung3b413f22018-10-26 18:05:34 +08003499 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500 }
3501 }
3502 } // release lock
3503
3504 // Wake up poll loop since it may need to make new input dispatching choices.
3505 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003506
3507 if (setInputWindowsListener) {
3508 setInputWindowsListener->onSetInputWindowsFinished();
3509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510}
3511
3512void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003513 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003514 if (DEBUG_FOCUS) {
3515 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3516 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003519 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520
Tiger Huang721e26f2018-07-24 22:26:19 +08003521 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3522 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003523 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003524 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3525 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003528 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003530 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003532 oldFocusedApplicationHandle.clear();
3533 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 } // release lock
3536
3537 // Wake up poll loop since it may need to make new input dispatching choices.
3538 mLooper->wake();
3539}
3540
Tiger Huang721e26f2018-07-24 22:26:19 +08003541/**
3542 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3543 * the display not specified.
3544 *
3545 * We track any unreleased events for each window. If a window loses the ability to receive the
3546 * released event, we will send a cancel event to it. So when the focused display is changed, we
3547 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3548 * display. The display-specified events won't be affected.
3549 */
3550void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003551 if (DEBUG_FOCUS) {
3552 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3553 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003554 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003555 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003556
3557 if (mFocusedDisplayId != displayId) {
3558 sp<InputWindowHandle> oldFocusedWindowHandle =
3559 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3560 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003561 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003562 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003563 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003564 CancelationOptions
3565 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3566 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003567 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003568 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3569 }
3570 }
3571 mFocusedDisplayId = displayId;
3572
3573 // Sanity check
3574 sp<InputWindowHandle> newFocusedWindowHandle =
3575 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003576 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003577
Tiger Huang721e26f2018-07-24 22:26:19 +08003578 if (newFocusedWindowHandle == nullptr) {
3579 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3580 if (!mFocusedWindowHandlesByDisplay.empty()) {
3581 ALOGE("But another display has a focused window:");
3582 for (auto& it : mFocusedWindowHandlesByDisplay) {
3583 const int32_t displayId = it.first;
3584 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003585 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3586 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003587 }
3588 }
3589 }
3590 }
3591
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003592 if (DEBUG_FOCUS) {
3593 logDispatchStateLocked();
3594 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003595 } // release lock
3596
3597 // Wake up poll loop since it may need to make new input dispatching choices.
3598 mLooper->wake();
3599}
3600
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003602 if (DEBUG_FOCUS) {
3603 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605
3606 bool changed;
3607 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003608 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609
3610 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3611 if (mDispatchFrozen && !frozen) {
3612 resetANRTimeoutsLocked();
3613 }
3614
3615 if (mDispatchEnabled && !enabled) {
3616 resetAndDropEverythingLocked("dispatcher is being disabled");
3617 }
3618
3619 mDispatchEnabled = enabled;
3620 mDispatchFrozen = frozen;
3621 changed = true;
3622 } else {
3623 changed = false;
3624 }
3625
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003626 if (DEBUG_FOCUS) {
3627 logDispatchStateLocked();
3628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 } // release lock
3630
3631 if (changed) {
3632 // Wake up poll loop since it may need to make new input dispatching choices.
3633 mLooper->wake();
3634 }
3635}
3636
3637void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003638 if (DEBUG_FOCUS) {
3639 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641
3642 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003643 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644
3645 if (mInputFilterEnabled == enabled) {
3646 return;
3647 }
3648
3649 mInputFilterEnabled = enabled;
3650 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3651 } // release lock
3652
3653 // Wake up poll loop since there might be work to do to drop everything.
3654 mLooper->wake();
3655}
3656
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003657void InputDispatcher::setInTouchMode(bool inTouchMode) {
3658 std::scoped_lock lock(mLock);
3659 mInTouchMode = inTouchMode;
3660}
3661
chaviwfbe5d9c2018-12-26 12:23:37 -08003662bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3663 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003664 if (DEBUG_FOCUS) {
3665 ALOGD("Trivial transfer to same window.");
3666 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003667 return true;
3668 }
3669
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003671 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672
chaviwfbe5d9c2018-12-26 12:23:37 -08003673 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3674 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003675 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003676 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 return false;
3678 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003679 if (DEBUG_FOCUS) {
3680 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3681 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003684 if (DEBUG_FOCUS) {
3685 ALOGD("Cannot transfer focus because windows are on different displays.");
3686 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 return false;
3688 }
3689
3690 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003691 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3692 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3693 for (size_t i = 0; i < state.windows.size(); i++) {
3694 const TouchedWindow& touchedWindow = state.windows[i];
3695 if (touchedWindow.windowHandle == fromWindowHandle) {
3696 int32_t oldTargetFlags = touchedWindow.targetFlags;
3697 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003699 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003701 int32_t newTargetFlags = oldTargetFlags &
3702 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3703 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003704 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705
Jeff Brownf086ddb2014-02-11 14:28:48 -08003706 found = true;
3707 goto Found;
3708 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709 }
3710 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003711 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003713 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003714 if (DEBUG_FOCUS) {
3715 ALOGD("Focus transfer failed because from window did not have focus.");
3716 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717 return false;
3718 }
3719
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003720 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3721 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003722 if (fromConnection != nullptr && toConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003724 CancelationOptions
3725 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3726 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3728 }
3729
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003730 if (DEBUG_FOCUS) {
3731 logDispatchStateLocked();
3732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 } // release lock
3734
3735 // Wake up poll loop since it may need to make new input dispatching choices.
3736 mLooper->wake();
3737 return true;
3738}
3739
3740void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003741 if (DEBUG_FOCUS) {
3742 ALOGD("Resetting and dropping all events (%s).", reason);
3743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744
3745 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3746 synthesizeCancelationEventsForAllConnectionsLocked(options);
3747
3748 resetKeyRepeatLocked();
3749 releasePendingEventLocked();
3750 drainInboundQueueLocked();
3751 resetANRTimeoutsLocked();
3752
Jeff Brownf086ddb2014-02-11 14:28:48 -08003753 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003755 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756}
3757
3758void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003759 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 dumpDispatchStateLocked(dump);
3761
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003762 std::istringstream stream(dump);
3763 std::string line;
3764
3765 while (std::getline(stream, line, '\n')) {
3766 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 }
3768}
3769
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003770void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003771 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3772 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3773 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003774 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775
Tiger Huang721e26f2018-07-24 22:26:19 +08003776 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3777 dump += StringPrintf(INDENT "FocusedApplications:\n");
3778 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3779 const int32_t displayId = it.first;
3780 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003781 dump += StringPrintf(INDENT2 "displayId=%" PRId32
3782 ", name='%s', dispatchingTimeout=%0.3fms\n",
3783 displayId, applicationHandle->getName().c_str(),
3784 applicationHandle->getDispatchingTimeout(
3785 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3786 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08003787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003789 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003791
3792 if (!mFocusedWindowHandlesByDisplay.empty()) {
3793 dump += StringPrintf(INDENT "FocusedWindows:\n");
3794 for (auto& it : mFocusedWindowHandlesByDisplay) {
3795 const int32_t displayId = it.first;
3796 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003797 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3798 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003799 }
3800 } else {
3801 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803
Jeff Brownf086ddb2014-02-11 14:28:48 -08003804 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003805 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003806 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3807 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003808 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003809 state.displayId, toString(state.down), toString(state.split),
3810 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003811 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003812 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003813 for (size_t i = 0; i < state.windows.size(); i++) {
3814 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003815 dump += StringPrintf(INDENT4
3816 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3817 i, touchedWindow.windowHandle->getName().c_str(),
3818 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003819 }
3820 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003821 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003822 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003823 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003824 dump += INDENT3 "Portal windows:\n";
3825 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003826 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003827 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3828 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003829 }
3830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 }
3832 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003833 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 }
3835
Arthur Hungb92218b2018-08-14 12:00:21 +08003836 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003837 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003838 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003839 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003840 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003841 dump += INDENT2 "Windows:\n";
3842 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003843 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003844 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003845
Arthur Hungb92218b2018-08-14 12:00:21 +08003846 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003847 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08003848 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
3849 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003850 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08003851 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003852 i, windowInfo->name.c_str(), windowInfo->displayId,
3853 windowInfo->portalToDisplayId,
3854 toString(windowInfo->paused),
3855 toString(windowInfo->hasFocus),
3856 toString(windowInfo->hasWallpaper),
3857 toString(windowInfo->visible),
3858 toString(windowInfo->canReceiveKeys),
3859 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08003860 windowInfo->layoutParamsType, windowInfo->frameLeft,
3861 windowInfo->frameTop, windowInfo->frameRight,
3862 windowInfo->frameBottom, windowInfo->globalScaleFactor,
3863 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003864 dumpRegion(dump, windowInfo->touchableRegion);
3865 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3866 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003867 windowInfo->ownerPid, windowInfo->ownerUid,
3868 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08003869 }
3870 } else {
3871 dump += INDENT2 "Windows: <none>\n";
3872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873 }
3874 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003875 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 }
3877
Michael Wright3dd60e22019-03-27 22:06:44 +00003878 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003879 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003880 const std::vector<Monitor>& monitors = it.second;
3881 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3882 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003883 }
3884 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003885 const std::vector<Monitor>& monitors = it.second;
3886 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3887 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003890 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891 }
3892
3893 nsecs_t currentTime = now();
3894
3895 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003896 if (!mRecentQueue.empty()) {
3897 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
3898 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003899 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003901 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 }
3903 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003904 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905 }
3906
3907 // Dump event currently being dispatched.
3908 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003909 dump += INDENT "PendingEvent:\n";
3910 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003912 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003913 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003915 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916 }
3917
3918 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003919 if (!mInboundQueue.empty()) {
3920 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
3921 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003922 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003924 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 }
3926 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003927 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 }
3929
Michael Wright78f24442014-08-06 15:55:28 -07003930 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003931 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003932 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3933 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3934 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003935 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3936 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07003937 }
3938 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003939 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003940 }
3941
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003942 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003943 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003944 for (const auto& pair : mConnectionsByFd) {
3945 const sp<Connection>& connection = pair.second;
3946 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
3947 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3948 pair.first, connection->getInputChannelName().c_str(),
3949 connection->getWindowName().c_str(), connection->getStatusLabel(),
3950 toString(connection->monitor),
3951 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003953 if (!connection->outboundQueue.empty()) {
3954 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
3955 connection->outboundQueue.size());
3956 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 dump.append(INDENT4);
3958 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003959 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003960 entry->targetFlags, entry->resolvedAction,
3961 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962 }
3963 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003964 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965 }
3966
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003967 if (!connection->waitQueue.empty()) {
3968 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
3969 connection->waitQueue.size());
3970 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003971 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003973 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003974 "age=%0.1fms, wait=%0.1fms\n",
3975 entry->targetFlags, entry->resolvedAction,
3976 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3977 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 }
3979 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003980 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 }
3982 }
3983 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003984 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985 }
3986
3987 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003988 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003989 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003991 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 }
3993
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003994 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003995 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003996 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003997 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998}
3999
Michael Wright3dd60e22019-03-27 22:06:44 +00004000void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4001 const size_t numMonitors = monitors.size();
4002 for (size_t i = 0; i < numMonitors; i++) {
4003 const Monitor& monitor = monitors[i];
4004 const sp<InputChannel>& channel = monitor.inputChannel;
4005 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4006 dump += "\n";
4007 }
4008}
4009
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004010status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004012 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013#endif
4014
4015 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004016 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004017 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004018 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004020 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 return BAD_VALUE;
4022 }
4023
Michael Wright3dd60e22019-03-27 22:06:44 +00004024 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025
4026 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004027 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004028 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4031 } // release lock
4032
4033 // Wake the looper because some connections have changed.
4034 mLooper->wake();
4035 return OK;
4036}
4037
Michael Wright3dd60e22019-03-27 22:06:44 +00004038status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004039 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004040 { // acquire lock
4041 std::scoped_lock _l(mLock);
4042
4043 if (displayId < 0) {
4044 ALOGW("Attempted to register input monitor without a specified display.");
4045 return BAD_VALUE;
4046 }
4047
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004048 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004049 ALOGW("Attempted to register input monitor without an identifying token.");
4050 return BAD_VALUE;
4051 }
4052
4053 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
4054
4055 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004056 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004057 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004058
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004059 auto& monitorsByDisplay =
4060 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004061 monitorsByDisplay[displayId].emplace_back(inputChannel);
4062
4063 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004064 }
4065 // Wake the looper because some connections have changed.
4066 mLooper->wake();
4067 return OK;
4068}
4069
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4071#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004072 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073#endif
4074
4075 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004076 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077
4078 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4079 if (status) {
4080 return status;
4081 }
4082 } // release lock
4083
4084 // Wake the poll loop because removing the connection may have changed the current
4085 // synchronization state.
4086 mLooper->wake();
4087 return OK;
4088}
4089
4090status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004091 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004092 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004093 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004095 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096 return BAD_VALUE;
4097 }
4098
John Recke0710582019-09-26 13:46:12 -07004099 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004100 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004101 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004102
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 if (connection->monitor) {
4104 removeMonitorChannelLocked(inputChannel);
4105 }
4106
4107 mLooper->removeFd(inputChannel->getFd());
4108
4109 nsecs_t currentTime = now();
4110 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4111
4112 connection->status = Connection::STATUS_ZOMBIE;
4113 return OK;
4114}
4115
4116void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004117 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4118 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4119}
4120
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004121void InputDispatcher::removeMonitorChannelLocked(
4122 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004123 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004124 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004125 std::vector<Monitor>& monitors = it->second;
4126 const size_t numMonitors = monitors.size();
4127 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004128 if (monitors[i].inputChannel == inputChannel) {
4129 monitors.erase(monitors.begin() + i);
4130 break;
4131 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004132 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004133 if (monitors.empty()) {
4134 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004135 } else {
4136 ++it;
4137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 }
4139}
4140
Michael Wright3dd60e22019-03-27 22:06:44 +00004141status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4142 { // acquire lock
4143 std::scoped_lock _l(mLock);
4144 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4145
4146 if (!foundDisplayId) {
4147 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4148 return BAD_VALUE;
4149 }
4150 int32_t displayId = foundDisplayId.value();
4151
4152 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4153 if (stateIndex < 0) {
4154 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4155 return BAD_VALUE;
4156 }
4157
4158 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4159 std::optional<int32_t> foundDeviceId;
4160 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004161 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004162 foundDeviceId = state.deviceId;
4163 }
4164 }
4165 if (!foundDeviceId || !state.down) {
4166 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004168 return BAD_VALUE;
4169 }
4170 int32_t deviceId = foundDeviceId.value();
4171
4172 // Send cancel events to all the input channels we're stealing from.
4173 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004174 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004175 options.deviceId = deviceId;
4176 options.displayId = displayId;
4177 for (const TouchedWindow& window : state.windows) {
4178 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004179 if (channel != nullptr) {
4180 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4181 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004182 }
4183 // Then clear the current touch state so we stop dispatching to them as well.
4184 state.filterNonMonitors();
4185 }
4186 return OK;
4187}
4188
Michael Wright3dd60e22019-03-27 22:06:44 +00004189std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4190 const sp<IBinder>& token) {
4191 for (const auto& it : mGestureMonitorsByDisplay) {
4192 const std::vector<Monitor>& monitors = it.second;
4193 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004194 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004195 return it.first;
4196 }
4197 }
4198 }
4199 return std::nullopt;
4200}
4201
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004202sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4203 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004204 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004205 }
4206
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004207 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004208 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004209 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004210 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 }
4212 }
Robert Carr4e670e52018-08-15 13:26:12 -07004213
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004214 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215}
4216
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004217void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4218 const sp<Connection>& connection, uint32_t seq,
4219 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004220 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4221 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 commandEntry->connection = connection;
4223 commandEntry->eventTime = currentTime;
4224 commandEntry->seq = seq;
4225 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004226 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227}
4228
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004229void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4230 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004232 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004234 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4235 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004237 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238}
4239
chaviw0c06c6e2019-01-09 13:27:07 -08004240void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004241 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004242 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4243 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004244 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4245 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004246 commandEntry->oldToken = oldToken;
4247 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004248 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004249}
4250
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004251void InputDispatcher::onANRLocked(nsecs_t currentTime,
4252 const sp<InputApplicationHandle>& applicationHandle,
4253 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4254 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4256 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4257 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004258 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4259 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4260 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261
4262 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004263 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 struct tm tm;
4265 localtime_r(&t, &tm);
4266 char timestr[64];
4267 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4268 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004269 mLastANRState += INDENT "ANR:\n";
4270 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004271 mLastANRState +=
4272 StringPrintf(INDENT2 "Window: %s\n",
4273 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004274 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4275 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4276 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 dumpDispatchStateLocked(mLastANRState);
4278
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004279 std::unique_ptr<CommandEntry> commandEntry =
4280 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004282 commandEntry->inputChannel =
4283 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004285 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286}
4287
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004288void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 mLock.unlock();
4290
4291 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4292
4293 mLock.lock();
4294}
4295
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004296void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 sp<Connection> connection = commandEntry->connection;
4298
4299 if (connection->status != Connection::STATUS_ZOMBIE) {
4300 mLock.unlock();
4301
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004302 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303
4304 mLock.lock();
4305 }
4306}
4307
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004308void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004309 sp<IBinder> oldToken = commandEntry->oldToken;
4310 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004311 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004312 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004313 mLock.lock();
4314}
4315
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004316void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004317 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004318 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 mLock.unlock();
4320
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004321 nsecs_t newTimeout =
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004322 mPolicy->notifyANR(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323
4324 mLock.lock();
4325
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004326 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327}
4328
4329void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4330 CommandEntry* commandEntry) {
4331 KeyEntry* entry = commandEntry->keyEntry;
4332
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004333 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334
4335 mLock.unlock();
4336
Michael Wright2b3c3302018-03-02 17:19:13 +00004337 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004338 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004339 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004340 : nullptr;
4341 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004342 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4343 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004344 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346
4347 mLock.lock();
4348
4349 if (delay < 0) {
4350 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4351 } else if (!delay) {
4352 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4353 } else {
4354 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4355 entry->interceptKeyWakeupTime = now() + delay;
4356 }
4357 entry->release();
4358}
4359
chaviwfd6d3512019-03-25 13:23:49 -07004360void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4361 mLock.unlock();
4362 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4363 mLock.lock();
4364}
4365
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004366void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004368 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004370 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371
4372 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004373 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004374 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004375 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004377 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004378
4379 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4380 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4381 std::string msg =
4382 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4383 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4384 dispatchEntry->eventEntry->appendDescription(msg);
4385 ALOGI("%s", msg.c_str());
4386 }
4387
4388 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004389 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004390 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4391 restartEvent =
4392 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004393 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004394 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4395 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4396 handled);
4397 } else {
4398 restartEvent = false;
4399 }
4400
4401 // Dequeue the event and start the next cycle.
4402 // Note that because the lock might have been released, it is possible that the
4403 // contents of the wait queue to have been drained, so we need to double-check
4404 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004405 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4406 if (dispatchEntryIt != connection->waitQueue.end()) {
4407 dispatchEntry = *dispatchEntryIt;
4408 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004409 traceWaitQueueLength(connection);
4410 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004411 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004412 traceOutboundQueueLength(connection);
4413 } else {
4414 releaseDispatchEntry(dispatchEntry);
4415 }
4416 }
4417
4418 // Start the next dispatch cycle for this connection.
4419 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420}
4421
4422bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004423 DispatchEntry* dispatchEntry,
4424 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004425 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004426 if (!handled) {
4427 // Report the key as unhandled, since the fallback was not handled.
4428 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4429 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004430 return false;
4431 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004433 // Get the fallback key state.
4434 // Clear it out after dispatching the UP.
4435 int32_t originalKeyCode = keyEntry->keyCode;
4436 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4437 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4438 connection->inputState.removeFallbackKey(originalKeyCode);
4439 }
4440
4441 if (handled || !dispatchEntry->hasForegroundTarget()) {
4442 // If the application handles the original key for which we previously
4443 // generated a fallback or if the window is not a foreground window,
4444 // then cancel the associated fallback key, if any.
4445 if (fallbackKeyCode != -1) {
4446 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004448 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004449 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4450 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4451 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004453 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004454 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455
4456 mLock.unlock();
4457
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004458 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004459 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460
4461 mLock.lock();
4462
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004463 // Cancel the fallback key.
4464 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004465 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004466 "application handled the original non-fallback key "
4467 "or is no longer a foreground target, "
4468 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469 options.keyCode = fallbackKeyCode;
4470 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004472 connection->inputState.removeFallbackKey(originalKeyCode);
4473 }
4474 } else {
4475 // If the application did not handle a non-fallback key, first check
4476 // that we are in a good state to perform unhandled key event processing
4477 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004478 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004479 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004481 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004482 "since this is not an initial down. "
4483 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4484 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004486 return false;
4487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004489 // Dispatch the unhandled key to the policy.
4490#if DEBUG_OUTBOUND_EVENT_DETAILS
4491 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004492 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4493 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004494#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004495 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004496
4497 mLock.unlock();
4498
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004499 bool fallback =
4500 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4501 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004502
4503 mLock.lock();
4504
4505 if (connection->status != Connection::STATUS_NORMAL) {
4506 connection->inputState.removeFallbackKey(originalKeyCode);
4507 return false;
4508 }
4509
4510 // Latch the fallback keycode for this key on an initial down.
4511 // The fallback keycode cannot change at any other point in the lifecycle.
4512 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004514 fallbackKeyCode = event.getKeyCode();
4515 } else {
4516 fallbackKeyCode = AKEYCODE_UNKNOWN;
4517 }
4518 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4519 }
4520
4521 ALOG_ASSERT(fallbackKeyCode != -1);
4522
4523 // Cancel the fallback key if the policy decides not to send it anymore.
4524 // We will continue to dispatch the key to the policy but we will no
4525 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004526 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4527 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004528#if DEBUG_OUTBOUND_EVENT_DETAILS
4529 if (fallback) {
4530 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004531 "as a fallback for %d, but on the DOWN it had requested "
4532 "to send %d instead. Fallback canceled.",
4533 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004534 } else {
4535 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004536 "but on the DOWN it had requested to send %d. "
4537 "Fallback canceled.",
4538 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004539 }
4540#endif
4541
4542 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4543 "canceling fallback, policy no longer desires it");
4544 options.keyCode = fallbackKeyCode;
4545 synthesizeCancelationEventsForConnectionLocked(connection, options);
4546
4547 fallback = false;
4548 fallbackKeyCode = AKEYCODE_UNKNOWN;
4549 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004550 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004551 }
4552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553
4554#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004555 {
4556 std::string msg;
4557 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4558 connection->inputState.getFallbackKeys();
4559 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004560 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004562 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004563 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004564 }
4565#endif
4566
4567 if (fallback) {
4568 // Restart the dispatch cycle using the fallback key.
4569 keyEntry->eventTime = event.getEventTime();
4570 keyEntry->deviceId = event.getDeviceId();
4571 keyEntry->source = event.getSource();
4572 keyEntry->displayId = event.getDisplayId();
4573 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4574 keyEntry->keyCode = fallbackKeyCode;
4575 keyEntry->scanCode = event.getScanCode();
4576 keyEntry->metaState = event.getMetaState();
4577 keyEntry->repeatCount = event.getRepeatCount();
4578 keyEntry->downTime = event.getDownTime();
4579 keyEntry->syntheticRepeat = false;
4580
4581#if DEBUG_OUTBOUND_EVENT_DETAILS
4582 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004583 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4584 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004585#endif
4586 return true; // restart the event
4587 } else {
4588#if DEBUG_OUTBOUND_EVENT_DETAILS
4589 ALOGD("Unhandled key event: No fallback key.");
4590#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004591
4592 // Report the key as unhandled, since there is no fallback key.
4593 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594 }
4595 }
4596 return false;
4597}
4598
4599bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004600 DispatchEntry* dispatchEntry,
4601 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602 return false;
4603}
4604
4605void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4606 mLock.unlock();
4607
4608 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4609
4610 mLock.lock();
4611}
4612
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004613KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4614 KeyEvent event;
4615 event.initialize(entry.deviceId, entry.source, entry.displayId, entry.action, entry.flags,
4616 entry.keyCode, entry.scanCode, entry.metaState, entry.repeatCount,
4617 entry.downTime, entry.eventTime);
4618 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619}
4620
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004621void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004622 int32_t injectionResult,
4623 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624 // TODO Write some statistics about how long we spend waiting.
4625}
4626
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004627/**
4628 * Report the touch event latency to the statsd server.
4629 * Input events are reported for statistics if:
4630 * - This is a touchscreen event
4631 * - InputFilter is not enabled
4632 * - Event is not injected or synthesized
4633 *
4634 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4635 * from getting aggregated with the "old" data.
4636 */
4637void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4638 REQUIRES(mLock) {
4639 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4640 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4641 if (!reportForStatistics) {
4642 return;
4643 }
4644
4645 if (mTouchStatistics.shouldReport()) {
4646 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4647 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4648 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4649 mTouchStatistics.reset();
4650 }
4651 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4652 mTouchStatistics.addValue(latencyMicros);
4653}
4654
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655void InputDispatcher::traceInboundQueueLengthLocked() {
4656 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004657 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658 }
4659}
4660
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004661void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662 if (ATRACE_ENABLED()) {
4663 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004664 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004665 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666 }
4667}
4668
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004669void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004670 if (ATRACE_ENABLED()) {
4671 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004672 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004673 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674 }
4675}
4676
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004677void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004678 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004680 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 dumpDispatchStateLocked(dump);
4682
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004683 if (!mLastANRState.empty()) {
4684 dump += "\nInput Dispatcher State at time of last ANR:\n";
4685 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686 }
4687}
4688
4689void InputDispatcher::monitor() {
4690 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004691 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004693 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694}
4695
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004696/**
4697 * Wake up the dispatcher and wait until it processes all events and commands.
4698 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4699 * this method can be safely called from any thread, as long as you've ensured that
4700 * the work you are interested in completing has already been queued.
4701 */
4702bool InputDispatcher::waitForIdle() {
4703 /**
4704 * Timeout should represent the longest possible time that a device might spend processing
4705 * events and commands.
4706 */
4707 constexpr std::chrono::duration TIMEOUT = 100ms;
4708 std::unique_lock lock(mLock);
4709 mLooper->wake();
4710 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4711 return result == std::cv_status::no_timeout;
4712}
4713
Garfield Tane84e6f92019-08-29 17:28:41 -07004714} // namespace android::inputdispatcher