blob: 0178811f0f43e775edcfc31b1d1961b77e490588 [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
chaviw5d22a232019-12-11 16:47:32 -0800259static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
260 EventEntry* eventEntry,
261 int32_t inputTargetFlags) {
262 if (inputTarget.useDefaultPointerInfo()) {
263 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
264 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
265 inputTargetFlags, pointerInfo.xOffset,
266 pointerInfo.yOffset, inputTarget.globalScaleFactor,
267 pointerInfo.windowXScale, pointerInfo.windowYScale);
268 }
269
270 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
271 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
272
273 PointerCoords pointerCoords[MAX_POINTERS];
274
275 // Use the first pointer information to normalize all other pointers. This could be any pointer
276 // as long as all other pointers are normalized to the same value and the final DispatchEntry
277 // uses the offset and scale for the normalized pointer.
278 const PointerInfo& firstPointerInfo =
279 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
280
281 // Iterate through all pointers in the event to normalize against the first.
282 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
283 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
284 uint32_t pointerId = uint32_t(pointerProperties.id);
285 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
286
287 // The scale factor is the ratio of the current pointers scale to the normalized scale.
288 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
289 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
290
291 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
292 // First apply the current pointers offset to set the window at 0,0
293 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
294 // Next scale the coordinates.
295 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
296 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
297 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
298 -firstPointerInfo.yOffset);
299 }
300
301 MotionEntry* combinedMotionEntry =
302 new MotionEntry(motionEntry.sequenceNum, motionEntry.eventTime, motionEntry.deviceId,
303 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
304 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
305 motionEntry.metaState, motionEntry.buttonState,
306 motionEntry.classification, motionEntry.edgeFlags,
307 motionEntry.xPrecision, motionEntry.yPrecision,
308 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
309 motionEntry.downTime, motionEntry.pointerCount,
310 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
311 0 /* yOffset */);
312
313 return std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
314 inputTargetFlags, firstPointerInfo.xOffset,
315 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
316 firstPointerInfo.windowXScale,
317 firstPointerInfo.windowYScale);
318}
319
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700320// --- InputDispatcherThread ---
321
322class InputDispatcher::InputDispatcherThread : public Thread {
323public:
324 explicit InputDispatcherThread(InputDispatcher* dispatcher)
325 : Thread(/* canCallJava */ true), mDispatcher(dispatcher) {}
326
327 ~InputDispatcherThread() {}
328
329private:
330 InputDispatcher* mDispatcher;
331
332 virtual bool threadLoop() override {
333 mDispatcher->dispatchOnce();
334 return true;
335 }
336};
337
Michael Wrightd02c5b62014-02-10 15:10:22 -0800338// --- InputDispatcher ---
339
Garfield Tan00f511d2019-06-12 16:55:40 -0700340InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
341 : mPolicy(policy),
342 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700343 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tan00f511d2019-06-12 16:55:40 -0700344 mAppSwitchSawKeyDown(false),
345 mAppSwitchDueTime(LONG_LONG_MAX),
346 mNextUnblockedEvent(nullptr),
347 mDispatchEnabled(false),
348 mDispatchFrozen(false),
349 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800350 // mInTouchMode will be initialized by the WindowManager to the default device config.
351 // To avoid leaking stack in case that call never comes, and for tests,
352 // initialize it here anyways.
353 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700354 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
355 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800356 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800357 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800358
Yi Kong9b14ac62018-07-17 13:48:38 -0700359 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800360
361 policy->getDispatcherConfiguration(&mConfig);
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700362
363 mThread = new InputDispatcherThread(this);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800364}
365
366InputDispatcher::~InputDispatcher() {
367 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800368 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800369
370 resetKeyRepeatLocked();
371 releasePendingEventLocked();
372 drainInboundQueueLocked();
373 }
374
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700375 while (!mConnectionsByFd.empty()) {
376 sp<Connection> connection = mConnectionsByFd.begin()->second;
377 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800378 }
379}
380
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700381status_t InputDispatcher::start() {
382 if (mThread->isRunning()) {
383 return ALREADY_EXISTS;
384 }
385 return mThread->run("InputDispatcher", PRIORITY_URGENT_DISPLAY);
386}
387
388status_t InputDispatcher::stop() {
389 if (!mThread->isRunning()) {
390 return OK;
391 }
392 if (gettid() == mThread->getTid()) {
393 ALOGE("InputDispatcher can only be stopped from outside of the InputDispatcherThread!");
394 return INVALID_OPERATION;
395 }
396 // Directly calling requestExitAndWait() causes the thread to not exit
397 // if mLooper is waiting for a long timeout.
398 mThread->requestExit();
399 mLooper->wake();
400 return mThread->requestExitAndWait();
401}
402
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403void InputDispatcher::dispatchOnce() {
404 nsecs_t nextWakeupTime = LONG_LONG_MAX;
405 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800406 std::scoped_lock _l(mLock);
407 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800408
409 // Run a dispatch loop if there are no pending commands.
410 // The dispatch loop might enqueue commands to run afterwards.
411 if (!haveCommandsLocked()) {
412 dispatchOnceInnerLocked(&nextWakeupTime);
413 }
414
415 // Run all pending commands if there are any.
416 // If any commands were run then force the next poll to wake up immediately.
417 if (runCommandsLockedInterruptible()) {
418 nextWakeupTime = LONG_LONG_MIN;
419 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800420
421 // We are about to enter an infinitely long sleep, because we have no commands or
422 // pending or queued events
423 if (nextWakeupTime == LONG_LONG_MAX) {
424 mDispatcherEnteredIdle.notify_all();
425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426 } // release lock
427
428 // Wait for callback or timeout or wake. (make sure we round up, not down)
429 nsecs_t currentTime = now();
430 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
431 mLooper->pollOnce(timeoutMillis);
432}
433
434void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
435 nsecs_t currentTime = now();
436
Jeff Browndc5992e2014-04-11 01:27:26 -0700437 // Reset the key repeat timer whenever normal dispatch is suspended while the
438 // device is in a non-interactive state. This is to ensure that we abort a key
439 // repeat if the device is just coming out of sleep.
440 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800441 resetKeyRepeatLocked();
442 }
443
444 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
445 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100446 if (DEBUG_FOCUS) {
447 ALOGD("Dispatch frozen. Waiting some more.");
448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449 return;
450 }
451
452 // Optimize latency of app switches.
453 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
454 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
455 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
456 if (mAppSwitchDueTime < *nextWakeupTime) {
457 *nextWakeupTime = mAppSwitchDueTime;
458 }
459
460 // Ready to start a new event.
461 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700462 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700463 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464 if (isAppSwitchDue) {
465 // The inbound queue is empty so the app switch key we were waiting
466 // for will never arrive. Stop waiting for it.
467 resetPendingAppSwitchLocked(false);
468 isAppSwitchDue = false;
469 }
470
471 // Synthesize a key repeat if appropriate.
472 if (mKeyRepeatState.lastKeyEntry) {
473 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
474 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
475 } else {
476 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
477 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
478 }
479 }
480 }
481
482 // Nothing to do if there is no pending event.
483 if (!mPendingEvent) {
484 return;
485 }
486 } else {
487 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700488 mPendingEvent = mInboundQueue.front();
489 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490 traceInboundQueueLengthLocked();
491 }
492
493 // Poke user activity for this event.
494 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700495 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496 }
497
498 // Get ready to dispatch the event.
499 resetANRTimeoutsLocked();
500 }
501
502 // Now we have an event to dispatch.
503 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700504 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700506 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800507 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700508 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700510 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 }
512
513 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700514 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515 }
516
517 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700518 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700519 ConfigurationChangedEntry* typedEntry =
520 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
521 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700522 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700523 break;
524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700526 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700527 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
528 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700529 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700530 break;
531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700533 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700534 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
535 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700536 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700537 resetPendingAppSwitchLocked(true);
538 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700539 } else if (dropReason == DropReason::NOT_DROPPED) {
540 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700541 }
542 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700543 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700544 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700545 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700546 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
547 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700548 }
549 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
550 break;
551 }
552
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700553 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700554 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700555 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
556 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700558 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700559 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700560 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700561 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
562 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700563 }
564 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
565 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 }
568
569 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700570 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700571 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572 }
Michael Wright3a981722015-06-10 15:26:13 +0100573 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574
575 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700576 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577 }
578}
579
580bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700581 bool needWake = mInboundQueue.empty();
582 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800583 traceInboundQueueLengthLocked();
584
585 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700586 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700587 // Optimize app switch latency.
588 // If the application takes too long to catch up then we drop all events preceding
589 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700590 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700591 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700592 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700593 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700594 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700595 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700597 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700599 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700600 mAppSwitchSawKeyDown = false;
601 needWake = true;
602 }
603 }
604 }
605 break;
606 }
607
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700608 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700609 // Optimize case where the current application is unresponsive and the user
610 // decides to touch a window in a different application.
611 // If the application takes too long to catch up then we drop all events preceding
612 // the touch into the other window.
613 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
614 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
615 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
616 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
617 mInputTargetWaitApplicationToken != nullptr) {
618 int32_t displayId = motionEntry->displayId;
619 int32_t x =
620 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
621 int32_t y =
622 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
623 sp<InputWindowHandle> touchedWindowHandle =
624 findTouchedWindowAtLocked(displayId, x, y);
625 if (touchedWindowHandle != nullptr &&
626 touchedWindowHandle->getApplicationToken() !=
627 mInputTargetWaitApplicationToken) {
628 // User touched a different application than the one we are waiting on.
629 // Flag the event, and start pruning the input queue.
630 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631 needWake = true;
632 }
633 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700634 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800635 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700636 case EventEntry::Type::CONFIGURATION_CHANGED:
637 case EventEntry::Type::DEVICE_RESET: {
638 // nothing to do
639 break;
640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800641 }
642
643 return needWake;
644}
645
646void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
647 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700648 mRecentQueue.push_back(entry);
649 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
650 mRecentQueue.front()->release();
651 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652 }
653}
654
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700655sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
656 int32_t y, bool addOutsideTargets,
657 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800659 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
660 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 const InputWindowInfo* windowInfo = windowHandle->getInfo();
662 if (windowInfo->displayId == displayId) {
663 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664
665 if (windowInfo->visible) {
666 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700667 bool isTouchModal = (flags &
668 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
669 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800671 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700672 if (portalToDisplayId != ADISPLAY_ID_NONE &&
673 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800674 if (addPortalWindows) {
675 // For the monitoring channels of the display.
676 mTempTouchState.addPortalWindow(windowHandle);
677 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700678 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
679 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 // Found window.
682 return windowHandle;
683 }
684 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800685
686 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700687 mTempTouchState.addOrUpdateWindow(windowHandle,
688 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
689 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800690 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 }
693 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700694 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695}
696
Garfield Tane84e6f92019-08-29 17:28:41 -0700697std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000698 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
699 std::vector<TouchedMonitor> touchedMonitors;
700
701 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
702 addGestureMonitors(monitors, touchedMonitors);
703 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
704 const InputWindowInfo* windowInfo = portalWindow->getInfo();
705 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700706 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
707 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000708 }
709 return touchedMonitors;
710}
711
712void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700713 std::vector<TouchedMonitor>& outTouchedMonitors,
714 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000715 if (monitors.empty()) {
716 return;
717 }
718 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
719 for (const Monitor& monitor : monitors) {
720 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
721 }
722}
723
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700724void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725 const char* reason;
726 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700727 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700729 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700731 reason = "inbound event was dropped because the policy consumed it";
732 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700733 case DropReason::DISABLED:
734 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700735 ALOGI("Dropped event because input dispatch is disabled.");
736 }
737 reason = "inbound event was dropped because input dispatch is disabled";
738 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700739 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700740 ALOGI("Dropped event because of pending overdue app switch.");
741 reason = "inbound event was dropped because of pending overdue app switch";
742 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700743 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700744 ALOGI("Dropped event because the current application is not responding and the user "
745 "has started interacting with a different application.");
746 reason = "inbound event was dropped because the current application is not responding "
747 "and the user has started interacting with a different application";
748 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700749 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700750 ALOGI("Dropped event because it is stale.");
751 reason = "inbound event was dropped because it is stale";
752 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700753 case DropReason::NOT_DROPPED: {
754 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700755 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757 }
758
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700759 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700760 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800761 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
762 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700763 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700765 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700766 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
767 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700768 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
769 synthesizeCancelationEventsForAllConnectionsLocked(options);
770 } else {
771 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
772 synthesizeCancelationEventsForAllConnectionsLocked(options);
773 }
774 break;
775 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700776 case EventEntry::Type::CONFIGURATION_CHANGED:
777 case EventEntry::Type::DEVICE_RESET: {
778 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
779 break;
780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 }
782}
783
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800784static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700785 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
786 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787}
788
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700789bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
790 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
791 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
792 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793}
794
795bool InputDispatcher::isAppSwitchPendingLocked() {
796 return mAppSwitchDueTime != LONG_LONG_MAX;
797}
798
799void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
800 mAppSwitchDueTime = LONG_LONG_MAX;
801
802#if DEBUG_APP_SWITCH
803 if (handled) {
804 ALOGD("App switch has arrived.");
805 } else {
806 ALOGD("App switch was abandoned.");
807 }
808#endif
809}
810
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700812 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813}
814
815bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700816 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800817 return false;
818 }
819
820 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700821 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700822 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700824 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825
826 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700827 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800828 return true;
829}
830
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700831void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
832 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833}
834
835void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700836 while (!mInboundQueue.empty()) {
837 EventEntry* entry = mInboundQueue.front();
838 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 releaseInboundEventLocked(entry);
840 }
841 traceInboundQueueLengthLocked();
842}
843
844void InputDispatcher::releasePendingEventLocked() {
845 if (mPendingEvent) {
846 resetANRTimeoutsLocked();
847 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700848 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 }
850}
851
852void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
853 InjectionState* injectionState = entry->injectionState;
854 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
855#if DEBUG_DISPATCH_CYCLE
856 ALOGD("Injected inbound event was dropped.");
857#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800858 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 }
860 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700861 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 }
863 addRecentEventLocked(entry);
864 entry->release();
865}
866
867void InputDispatcher::resetKeyRepeatLocked() {
868 if (mKeyRepeatState.lastKeyEntry) {
869 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700870 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 }
872}
873
Garfield Tane84e6f92019-08-29 17:28:41 -0700874KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
876
877 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700878 uint32_t policyFlags = entry->policyFlags &
879 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 if (entry->refCount == 1) {
881 entry->recycle();
882 entry->eventTime = currentTime;
883 entry->policyFlags = policyFlags;
884 entry->repeatCount += 1;
885 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700886 KeyEntry* newEntry =
887 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId,
888 entry->source, entry->displayId, policyFlags, entry->action,
889 entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
890 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891
892 mKeyRepeatState.lastKeyEntry = newEntry;
893 entry->release();
894
895 entry = newEntry;
896 }
897 entry->syntheticRepeat = true;
898
899 // Increment reference count since we keep a reference to the event in
900 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
901 entry->refCount += 1;
902
903 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
904 return entry;
905}
906
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700907bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
908 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700910 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911#endif
912
913 // Reset key repeating in case a keyboard device was added or removed or something.
914 resetKeyRepeatLocked();
915
916 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700917 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
918 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700920 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921 return true;
922}
923
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700924bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700926 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700927 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928#endif
929
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700930 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 options.deviceId = entry->deviceId;
932 synthesizeCancelationEventsForAllConnectionsLocked(options);
933 return true;
934}
935
936bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700937 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700939 if (!entry->dispatchInProgress) {
940 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
941 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
942 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
943 if (mKeyRepeatState.lastKeyEntry &&
944 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 // We have seen two identical key downs in a row which indicates that the device
946 // driver is automatically generating key repeats itself. We take note of the
947 // repeat here, but we disable our own next key repeat timer since it is clear that
948 // we will not need to synthesize key repeats ourselves.
949 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
950 resetKeyRepeatLocked();
951 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
952 } else {
953 // Not a repeat. Save key down state in case we do see a repeat later.
954 resetKeyRepeatLocked();
955 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
956 }
957 mKeyRepeatState.lastKeyEntry = entry;
958 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700959 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 resetKeyRepeatLocked();
961 }
962
963 if (entry->repeatCount == 1) {
964 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
965 } else {
966 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
967 }
968
969 entry->dispatchInProgress = true;
970
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700971 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 }
973
974 // Handle case where the policy asked us to try again later last time.
975 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
976 if (currentTime < entry->interceptKeyWakeupTime) {
977 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
978 *nextWakeupTime = entry->interceptKeyWakeupTime;
979 }
980 return false; // wait until next wakeup
981 }
982 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
983 entry->interceptKeyWakeupTime = 0;
984 }
985
986 // Give the policy a chance to intercept the key.
987 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
988 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700989 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -0700990 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800991 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700992 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +0800993 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700994 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995 }
996 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700997 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 entry->refCount += 1;
999 return false; // wait for the command to run
1000 } else {
1001 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1002 }
1003 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001004 if (*dropReason == DropReason::NOT_DROPPED) {
1005 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 }
1007 }
1008
1009 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001010 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001011 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001012 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001013 : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08001014 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 return true;
1016 }
1017
1018 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001019 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001020 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001021 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1023 return false;
1024 }
1025
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001026 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1028 return true;
1029 }
1030
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001031 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001032 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033
1034 // Dispatch the key.
1035 dispatchEventLocked(currentTime, entry, inputTargets);
1036 return true;
1037}
1038
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001039void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001041 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001042 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1043 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001044 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1045 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1046 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047#endif
1048}
1049
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001050bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1051 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001052 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001054 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 entry->dispatchInProgress = true;
1056
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001057 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 }
1059
1060 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001061 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001062 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001063 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001064 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 return true;
1066 }
1067
1068 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1069
1070 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001071 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072
1073 bool conflictingPointerActions = false;
1074 int32_t injectionResult;
1075 if (isPointerEvent) {
1076 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001078 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001079 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 } else {
1081 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001082 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001083 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
1085 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1086 return false;
1087 }
1088
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001089 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001091 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001092 CancelationOptions::Mode mode(isPointerEvent
1093 ? CancelationOptions::CANCEL_POINTER_EVENTS
1094 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001095 CancelationOptions options(mode, "input event injection failed");
1096 synthesizeCancelationEventsForMonitorsLocked(options);
1097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098 return true;
1099 }
1100
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001101 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001102 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001103
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001104 if (isPointerEvent) {
1105 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
1106 if (stateIndex >= 0) {
1107 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001108 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001109 // The event has gone through these portal windows, so we add monitoring targets of
1110 // the corresponding displays as well.
1111 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001112 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001113 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001115 }
1116 }
1117 }
1118 }
1119
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 // Dispatch the motion.
1121 if (conflictingPointerActions) {
1122 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001123 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 synthesizeCancelationEventsForAllConnectionsLocked(options);
1125 }
1126 dispatchEventLocked(currentTime, entry, inputTargets);
1127 return true;
1128}
1129
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001130void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001132 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001133 ", policyFlags=0x%x, "
1134 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1135 "metaState=0x%x, buttonState=0x%x,"
1136 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001137 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1138 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1139 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001141 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001143 "x=%f, y=%f, pressure=%f, size=%f, "
1144 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1145 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001146 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1147 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1148 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1149 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1150 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1151 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1152 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1153 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1154 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1155 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 }
1157#endif
1158}
1159
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001160void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1161 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001162 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163#if DEBUG_DISPATCH_CYCLE
1164 ALOGD("dispatchEventToCurrentInputTargets");
1165#endif
1166
1167 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1168
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001169 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001171 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001172 sp<Connection> connection =
1173 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001174 if (connection != nullptr) {
chaviw5d22a232019-12-11 16:47:32 -08001175 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001177 if (DEBUG_FOCUS) {
1178 ALOGD("Dropping event delivery to target with channel '%s' because it "
1179 "is no longer registered with the input dispatcher.",
1180 inputTarget.inputChannel->getName().c_str());
1181 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 }
1183 }
1184}
1185
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001186int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001187 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001189 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001190 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001192 if (DEBUG_FOCUS) {
1193 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1194 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1196 mInputTargetWaitStartTime = currentTime;
1197 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1198 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001199 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 }
1201 } else {
1202 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001203 if (DEBUG_FOCUS) {
1204 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
1205 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001208 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001210 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001211 timeout =
1212 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 } else {
1214 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1215 }
1216
1217 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1218 mInputTargetWaitStartTime = currentTime;
1219 mInputTargetWaitTimeoutTime = currentTime + timeout;
1220 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001221 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222
Yi Kong9b14ac62018-07-17 13:48:38 -07001223 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001224 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 }
Robert Carr740167f2018-10-11 19:03:41 -07001226 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1227 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 }
1229 }
1230 }
1231
1232 if (mInputTargetWaitTimeoutExpired) {
1233 return INPUT_EVENT_INJECTION_TIMED_OUT;
1234 }
1235
1236 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001237 onANRLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001238 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239
1240 // Force poll loop to wake up immediately on next iteration once we get the
1241 // ANR response back from the policy.
1242 *nextWakeupTime = LONG_LONG_MIN;
1243 return INPUT_EVENT_INJECTION_PENDING;
1244 } else {
1245 // Force poll loop to wake up when timeout is due.
1246 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1247 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1248 }
1249 return INPUT_EVENT_INJECTION_PENDING;
1250 }
1251}
1252
Robert Carr803535b2018-08-02 16:38:15 -07001253void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1254 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1255 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1256 state.removeWindowByToken(token);
1257 }
1258}
1259
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001260void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001261 nsecs_t newTimeout, const sp<IBinder>& inputConnectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 if (newTimeout > 0) {
1263 // Extend the timeout.
1264 mInputTargetWaitTimeoutTime = now() + newTimeout;
1265 } else {
1266 // Give up.
1267 mInputTargetWaitTimeoutExpired = true;
1268
1269 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001270 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001271 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001272 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001274 if (connection->status == Connection::STATUS_NORMAL) {
1275 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1276 "application not responding");
1277 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 }
1279 }
1280 }
1281}
1282
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001283nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1285 return currentTime - mInputTargetWaitStartTime;
1286 }
1287 return 0;
1288}
1289
1290void InputDispatcher::resetANRTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001291 if (DEBUG_FOCUS) {
1292 ALOGD("Resetting ANR timeouts.");
1293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294
1295 // Reset input target wait timeout.
1296 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001297 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298}
1299
Tiger Huang721e26f2018-07-24 22:26:19 +08001300/**
1301 * Get the display id that the given event should go to. If this event specifies a valid display id,
1302 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1303 * Focused display is the display that the user most recently interacted with.
1304 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001305int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001306 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001307 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001308 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001309 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1310 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001311 break;
1312 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001313 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001314 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1315 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001316 break;
1317 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001318 case EventEntry::Type::CONFIGURATION_CHANGED:
1319 case EventEntry::Type::DEVICE_RESET: {
1320 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001321 return ADISPLAY_ID_NONE;
1322 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001323 }
1324 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1325}
1326
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001328 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001329 std::vector<InputTarget>& inputTargets,
1330 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001332 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333
Tiger Huang721e26f2018-07-24 22:26:19 +08001334 int32_t displayId = getTargetDisplayId(entry);
1335 sp<InputWindowHandle> focusedWindowHandle =
1336 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1337 sp<InputApplicationHandle> focusedApplicationHandle =
1338 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1339
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 // If there is no currently focused window and no focused application
1341 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001342 if (focusedWindowHandle == nullptr) {
1343 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001344 injectionResult =
1345 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1346 nullptr, nextWakeupTime,
1347 "Waiting because no window has focus but there is "
1348 "a focused application that may eventually add a "
1349 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 goto Unresponsive;
1351 }
1352
Arthur Hung3b413f22018-10-26 18:05:34 +08001353 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001354 "%" PRId32 ".",
1355 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1357 goto Failed;
1358 }
1359
1360 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001361 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1363 goto Failed;
1364 }
1365
Jeff Brownffb49772014-10-10 19:01:34 -07001366 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001367 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001368 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001369 injectionResult =
1370 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1371 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 goto Unresponsive;
1373 }
1374
1375 // Success! Output targets.
1376 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001377 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001378 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1379 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380
1381 // Done.
1382Failed:
1383Unresponsive:
1384 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001385 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001386 if (DEBUG_FOCUS) {
1387 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1388 "timeSpentWaitingForApplication=%0.1fms",
1389 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391 return injectionResult;
1392}
1393
1394int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001395 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001396 std::vector<InputTarget>& inputTargets,
1397 nsecs_t* nextWakeupTime,
1398 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001399 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 enum InjectionPermission {
1401 INJECTION_PERMISSION_UNKNOWN,
1402 INJECTION_PERMISSION_GRANTED,
1403 INJECTION_PERMISSION_DENIED
1404 };
1405
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406 // For security reasons, we defer updating the touch state until we are sure that
1407 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001408 int32_t displayId = entry.displayId;
1409 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1411
1412 // Update the touch state as needed based on the properties of the touch event.
1413 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1414 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1415 sp<InputWindowHandle> newHoverWindowHandle;
1416
Jeff Brownf086ddb2014-02-11 14:28:48 -08001417 // Copy current touch state into mTempTouchState.
1418 // This state is always reset at the end of this function, so if we don't find state
1419 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001420 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001421 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1422 if (oldStateIndex >= 0) {
1423 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1424 mTempTouchState.copyFrom(*oldState);
1425 }
1426
1427 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001428 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001429 (mTempTouchState.deviceId != entry.deviceId || mTempTouchState.source != entry.source ||
1430 mTempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001431 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1432 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1433 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1434 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1435 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001436 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437 bool wrongDevice = false;
1438 if (newGesture) {
1439 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001440 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001441 if (DEBUG_FOCUS) {
1442 ALOGD("Dropping event because a pointer for a different device is already down "
1443 "in display %" PRId32,
1444 displayId);
1445 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001446 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1448 switchedDevice = false;
1449 wrongDevice = true;
1450 goto Failed;
1451 }
1452 mTempTouchState.reset();
1453 mTempTouchState.down = down;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001454 mTempTouchState.deviceId = entry.deviceId;
1455 mTempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 mTempTouchState.displayId = displayId;
1457 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001458 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001459 if (DEBUG_FOCUS) {
1460 ALOGI("Dropping move event because a pointer for a different device is already active "
1461 "in display %" PRId32,
1462 displayId);
1463 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001464 // TODO: test multiple simultaneous input streams.
1465 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1466 switchedDevice = false;
1467 wrongDevice = true;
1468 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 }
1470
1471 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1472 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1473
Garfield Tan00f511d2019-06-12 16:55:40 -07001474 int32_t x;
1475 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001477 // Always dispatch mouse events to cursor position.
1478 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001479 x = int32_t(entry.xCursorPosition);
1480 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001481 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001482 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1483 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001484 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001485 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001486 sp<InputWindowHandle> newTouchedWindowHandle =
1487 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1488 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001489
1490 std::vector<TouchedMonitor> newGestureMonitors = isDown
1491 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1492 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001495 if (newTouchedWindowHandle != nullptr &&
1496 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001497 // New window supports splitting, but we should never split mouse events.
1498 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 } else if (isSplit) {
1500 // New window does not support splitting but we have already split events.
1501 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001502 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 }
1504
1505 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001506 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 // Try to assign the pointer to the first foreground window we find, if there is one.
1508 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001509 }
1510
1511 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1512 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001513 "(%d, %d) in display %" PRId32 ".",
1514 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001515 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1516 goto Failed;
1517 }
1518
1519 if (newTouchedWindowHandle != nullptr) {
1520 // Set target flags.
1521 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1522 if (isSplit) {
1523 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001525 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1526 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1527 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1528 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1529 }
1530
1531 // Update hover state.
1532 if (isHoverAction) {
1533 newHoverWindowHandle = newTouchedWindowHandle;
1534 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1535 newHoverWindowHandle = mLastHoverWindowHandle;
1536 }
1537
1538 // Update the temporary touch state.
1539 BitSet32 pointerIds;
1540 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001541 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001542 pointerIds.markBit(pointerId);
1543 }
1544 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 }
1546
Michael Wright3dd60e22019-03-27 22:06:44 +00001547 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 } else {
1549 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1550
1551 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001552 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001553 if (DEBUG_FOCUS) {
1554 ALOGD("Dropping event because the pointer is not down or we previously "
1555 "dropped the pointer down event in display %" PRId32,
1556 displayId);
1557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1559 goto Failed;
1560 }
1561
1562 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001563 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001564 mTempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001565 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1566 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567
1568 sp<InputWindowHandle> oldTouchedWindowHandle =
1569 mTempTouchState.getFirstForegroundWindowHandle();
1570 sp<InputWindowHandle> newTouchedWindowHandle =
1571 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001572 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1573 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001574 if (DEBUG_FOCUS) {
1575 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1576 oldTouchedWindowHandle->getName().c_str(),
1577 newTouchedWindowHandle->getName().c_str(), displayId);
1578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 // Make a slippery exit from the old window.
1580 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001581 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1582 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583
1584 // Make a slippery entrance into the new window.
1585 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1586 isSplit = true;
1587 }
1588
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001589 int32_t targetFlags =
1590 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 if (isSplit) {
1592 targetFlags |= InputTarget::FLAG_SPLIT;
1593 }
1594 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1595 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1596 }
1597
1598 BitSet32 pointerIds;
1599 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001600 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601 }
1602 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1603 }
1604 }
1605 }
1606
1607 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1608 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001609 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610#if DEBUG_HOVER
1611 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001612 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613#endif
1614 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001615 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1616 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617 }
1618
1619 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001620 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621#if DEBUG_HOVER
1622 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001623 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624#endif
1625 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001626 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1627 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 }
1629 }
1630
1631 // Check permission to inject into all touched foreground windows and ensure there
1632 // is at least one touched foreground window.
1633 {
1634 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001635 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1637 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001638 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1640 injectionPermission = INJECTION_PERMISSION_DENIED;
1641 goto Failed;
1642 }
1643 }
1644 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001645 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1646 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001647 if (DEBUG_FOCUS) {
1648 ALOGD("Dropping event because there is no touched foreground window in display "
1649 "%" PRId32 " or gesture monitor to receive it.",
1650 displayId);
1651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1653 goto Failed;
1654 }
1655
1656 // Permission granted to injection into all touched foreground windows.
1657 injectionPermission = INJECTION_PERMISSION_GRANTED;
1658 }
1659
1660 // Check whether windows listening for outside touches are owned by the same UID. If it is
1661 // set the policy flag that we will not reveal coordinate information to this window.
1662 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1663 sp<InputWindowHandle> foregroundWindowHandle =
1664 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001665 if (foregroundWindowHandle) {
1666 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1667 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1668 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1669 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1670 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1671 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001672 InputTarget::FLAG_ZERO_COORDS,
1673 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001674 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 }
1676 }
1677 }
1678 }
1679
1680 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001681 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001683 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001684 std::string reason =
1685 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1686 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001687 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001688 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1689 touchedWindow.windowHandle,
1690 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691 goto Unresponsive;
1692 }
1693 }
1694 }
1695
1696 // If this is the first pointer going down and the touched window has a wallpaper
1697 // then also add the touched wallpaper windows so they are locked in for the duration
1698 // of the touch gesture.
1699 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1700 // engine only supports touch events. We would need to add a mechanism similar
1701 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1702 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1703 sp<InputWindowHandle> foregroundWindowHandle =
1704 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001705 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001706 const std::vector<sp<InputWindowHandle>> windowHandles =
1707 getWindowHandlesLocked(displayId);
1708 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001710 if (info->displayId == displayId &&
1711 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1712 mTempTouchState
1713 .addOrUpdateWindow(windowHandle,
1714 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1715 InputTarget::
1716 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1717 InputTarget::FLAG_DISPATCH_AS_IS,
1718 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 }
1720 }
1721 }
1722 }
1723
1724 // Success! Output targets.
1725 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1726
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001727 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001729 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 }
1731
Michael Wright3dd60e22019-03-27 22:06:44 +00001732 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1733 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001734 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001735 }
1736
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 // Drop the outside or hover touch windows since we will not care about them
1738 // in the next iteration.
1739 mTempTouchState.filterNonAsIsTouchWindows();
1740
1741Failed:
1742 // Check injection permission once and for all.
1743 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001744 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 injectionPermission = INJECTION_PERMISSION_GRANTED;
1746 } else {
1747 injectionPermission = INJECTION_PERMISSION_DENIED;
1748 }
1749 }
1750
1751 // Update final pieces of touch state if the injector had permission.
1752 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1753 if (!wrongDevice) {
1754 if (switchedDevice) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001755 if (DEBUG_FOCUS) {
1756 ALOGD("Conflicting pointer actions: Switched to a different device.");
1757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 *outConflictingPointerActions = true;
1759 }
1760
1761 if (isHoverAction) {
1762 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001763 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001764 if (DEBUG_FOCUS) {
1765 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1766 "down.");
1767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768 *outConflictingPointerActions = true;
1769 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001770 mTempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001771 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1772 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001773 mTempTouchState.deviceId = entry.deviceId;
1774 mTempTouchState.source = entry.source;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001775 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001777 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1778 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001780 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1782 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001783 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001784 if (DEBUG_FOCUS) {
1785 ALOGD("Conflicting pointer actions: Down received while already down.");
1786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 *outConflictingPointerActions = true;
1788 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1790 // One pointer went up.
1791 if (isSplit) {
1792 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001793 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001795 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001796 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1798 touchedWindow.pointerIds.clearBit(pointerId);
1799 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001800 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 continue;
1802 }
1803 }
1804 i += 1;
1805 }
1806 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001807 }
1808
1809 // Save changes unless the action was scroll in which case the temporary touch
1810 // state was only valid for this one action.
1811 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1812 if (mTempTouchState.displayId >= 0) {
1813 if (oldStateIndex >= 0) {
1814 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1815 } else {
1816 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1817 }
1818 } else if (oldStateIndex >= 0) {
1819 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 }
1822
1823 // Update hover state.
1824 mLastHoverWindowHandle = newHoverWindowHandle;
1825 }
1826 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001827 if (DEBUG_FOCUS) {
1828 ALOGD("Not updating touch focus because injection was denied.");
1829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830 }
1831
1832Unresponsive:
1833 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1834 mTempTouchState.reset();
1835
1836 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001837 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001838 if (DEBUG_FOCUS) {
1839 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1840 "timeSpentWaitingForApplication=%0.1fms",
1841 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 return injectionResult;
1844}
1845
1846void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001847 int32_t targetFlags, BitSet32 pointerIds,
1848 std::vector<InputTarget>& inputTargets) {
chaviw5d22a232019-12-11 16:47:32 -08001849 std::vector<InputTarget>::iterator it =
1850 std::find_if(inputTargets.begin(), inputTargets.end(),
1851 [&windowHandle](const InputTarget& inputTarget) {
1852 return inputTarget.inputChannel->getConnectionToken() ==
1853 windowHandle->getToken();
1854 });
Arthur Hungceeb5d72018-12-05 16:14:18 +08001855
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw5d22a232019-12-11 16:47:32 -08001857
1858 if (it == inputTargets.end()) {
1859 InputTarget inputTarget;
1860 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1861 if (inputChannel == nullptr) {
1862 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1863 return;
1864 }
1865 inputTarget.inputChannel = inputChannel;
1866 inputTarget.flags = targetFlags;
1867 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
1868 inputTargets.push_back(inputTarget);
1869 it = inputTargets.end() - 1;
1870 }
1871
1872 ALOG_ASSERT(it->flags == targetFlags);
1873 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
1874
1875 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
1876 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877}
1878
Michael Wright3dd60e22019-03-27 22:06:44 +00001879void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001880 int32_t displayId, float xOffset,
1881 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001882 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1883 mGlobalMonitorsByDisplay.find(displayId);
1884
1885 if (it != mGlobalMonitorsByDisplay.end()) {
1886 const std::vector<Monitor>& monitors = it->second;
1887 for (const Monitor& monitor : monitors) {
1888 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 }
1891}
1892
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001893void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1894 float yOffset,
1895 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001896 InputTarget target;
1897 target.inputChannel = monitor.inputChannel;
1898 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw5d22a232019-12-11 16:47:32 -08001899 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00001900 inputTargets.push_back(target);
1901}
1902
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001904 const InjectionState* injectionState) {
1905 if (injectionState &&
1906 (windowHandle == nullptr ||
1907 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1908 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001909 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001911 "owned by uid %d",
1912 injectionState->injectorPid, injectionState->injectorUid,
1913 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914 } else {
1915 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001916 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 }
1918 return false;
1919 }
1920 return true;
1921}
1922
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001923bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1924 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001926 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1927 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 if (otherHandle == windowHandle) {
1929 break;
1930 }
1931
1932 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001933 if (otherInfo->displayId == displayId && otherInfo->visible &&
1934 !otherInfo->isTrustedOverlay() && otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 return true;
1936 }
1937 }
1938 return false;
1939}
1940
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001941bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1942 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001943 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001944 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001945 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001946 if (otherHandle == windowHandle) {
1947 break;
1948 }
1949
1950 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001951 if (otherInfo->displayId == displayId && otherInfo->visible &&
1952 !otherInfo->isTrustedOverlay() && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001953 return true;
1954 }
1955 }
1956 return false;
1957}
1958
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001959std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
1960 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001961 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07001962 // If the window is paused then keep waiting.
1963 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001964 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001965 }
1966
1967 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001968 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001969 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001970 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001971 "registered with the input dispatcher. The window may be in the "
1972 "process of being removed.",
1973 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001974 }
1975
1976 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07001977 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001978 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001979 "The window may be in the process of being removed.",
1980 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07001981 }
1982
1983 // If the connection is backed up then keep waiting.
1984 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001985 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001986 "Outbound queue length: %zu. Wait queue length: %zu.",
1987 targetType, connection->outboundQueue.size(),
1988 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07001989 }
1990
1991 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001992 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07001993 // If the event is a key event, then we must wait for all previous events to
1994 // complete before delivering it because previous events may have the
1995 // side-effect of transferring focus to a different window and we want to
1996 // ensure that the following keys are sent to the new window.
1997 //
1998 // Suppose the user touches a button in a window then immediately presses "A".
1999 // If the button causes a pop-up window to appear then we want to ensure that
2000 // the "A" key is delivered to the new pop-up window. This is because users
2001 // often anticipate pending UI changes when typing on a keyboard.
2002 // To obtain this behavior, we must serialize key events with respect to all
2003 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002004 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002005 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002006 "finished processing all of the input events that were previously "
2007 "delivered to it. Outbound queue length: %zu. Wait queue length: "
2008 "%zu.",
2009 targetType, connection->outboundQueue.size(),
2010 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 }
Jeff Brownffb49772014-10-10 19:01:34 -07002012 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 // Touch events can always be sent to a window immediately because the user intended
2014 // to touch whatever was visible at the time. Even if focus changes or a new
2015 // window appears moments later, the touch event was meant to be delivered to
2016 // whatever window happened to be on screen at the time.
2017 //
2018 // Generic motion events, such as trackball or joystick events are a little trickier.
2019 // Like key events, generic motion events are delivered to the focused window.
2020 // Unlike key events, generic motion events don't tend to transfer focus to other
2021 // windows and it is not important for them to be serialized. So we prefer to deliver
2022 // generic motion events as soon as possible to improve efficiency and reduce lag
2023 // through batching.
2024 //
2025 // The one case where we pause input event delivery is when the wait queue is piling
2026 // up with lots of events because the application is not responding.
2027 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002028 if (!connection->waitQueue.empty() &&
2029 currentTime >=
2030 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002031 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002032 "finished processing certain input events that were delivered to "
2033 "it over "
2034 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
2035 "%0.1fms.",
2036 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
2037 connection->waitQueue.size(),
2038 (currentTime - connection->waitQueue.front()->deliveryTime) *
2039 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 }
2041 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002042 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043}
2044
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002045std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002046 const sp<InputApplicationHandle>& applicationHandle,
2047 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002048 if (applicationHandle != nullptr) {
2049 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002050 std::string label(applicationHandle->getName());
2051 label += " - ";
2052 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 return label;
2054 } else {
2055 return applicationHandle->getName();
2056 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002057 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 return windowHandle->getName();
2059 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002060 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 }
2062}
2063
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002064void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002065 int32_t displayId = getTargetDisplayId(eventEntry);
2066 sp<InputWindowHandle> focusedWindowHandle =
2067 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2068 if (focusedWindowHandle != nullptr) {
2069 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2071#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002072 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073#endif
2074 return;
2075 }
2076 }
2077
2078 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002079 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002080 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002081 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2082 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002083 return;
2084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002086 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002087 eventType = USER_ACTIVITY_EVENT_TOUCH;
2088 }
2089 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002091 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002092 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2093 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002094 return;
2095 }
2096 eventType = USER_ACTIVITY_EVENT_BUTTON;
2097 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002099 case EventEntry::Type::CONFIGURATION_CHANGED:
2100 case EventEntry::Type::DEVICE_RESET: {
2101 LOG_ALWAYS_FATAL("%s events are not user activity",
2102 EventEntry::typeToString(eventEntry.type));
2103 break;
2104 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 }
2106
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002107 std::unique_ptr<CommandEntry> commandEntry =
2108 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002109 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002111 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112}
2113
2114void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002115 const sp<Connection>& connection,
2116 EventEntry* eventEntry,
chaviw5d22a232019-12-11 16:47:32 -08002117 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002118 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002119 std::string message =
2120 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
2121 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002122 ATRACE_NAME(message.c_str());
2123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124#if DEBUG_DISPATCH_CYCLE
2125 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002126 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
2127 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
chaviw5d22a232019-12-11 16:47:32 -08002128 connection->getInputChannelName().c_str(), inputTarget.flags, inputTarget.xOffset,
2129 inputTarget.yOffset, inputTarget.globalScaleFactor, inputTarget.windowXScale,
2130 inputTarget.windowYScale, inputTarget.pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131#endif
2132
2133 // Skip this event if the connection status is not normal.
2134 // We don't want to enqueue additional outbound events if the connection is broken.
2135 if (connection->status != Connection::STATUS_NORMAL) {
2136#if DEBUG_DISPATCH_CYCLE
2137 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002138 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139#endif
2140 return;
2141 }
2142
2143 // Split a motion event if needed.
chaviw5d22a232019-12-11 16:47:32 -08002144 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002145 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002147 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
chaviw5d22a232019-12-11 16:47:32 -08002148 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002149 MotionEntry* splitMotionEntry =
chaviw5d22a232019-12-11 16:47:32 -08002150 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151 if (!splitMotionEntry) {
2152 return; // split event was dropped
2153 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002154 if (DEBUG_FOCUS) {
2155 ALOGD("channel '%s' ~ Split motion event.",
2156 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002157 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002158 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002159 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 splitMotionEntry->release();
2161 return;
2162 }
2163 }
2164
2165 // Not splitting. Enqueue dispatch entries for the event as is.
2166 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2167}
2168
2169void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002170 const sp<Connection>& connection,
2171 EventEntry* eventEntry,
chaviw5d22a232019-12-11 16:47:32 -08002172 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002173 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002174 std::string message =
2175 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32
2176 ")",
2177 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002178 ATRACE_NAME(message.c_str());
2179 }
2180
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002181 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182
2183 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002184 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002185 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002186 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002187 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002188 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002189 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002190 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002191 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002192 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002193 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002194 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002195 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196
2197 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002198 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 startDispatchCycleLocked(currentTime, connection);
2200 }
2201}
2202
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002203void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2204 EventEntry* eventEntry,
chaviw5d22a232019-12-11 16:47:32 -08002205 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002206 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002207 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002208 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2209 connection->getInputChannelName().c_str(),
2210 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002211 ATRACE_NAME(message.c_str());
2212 }
chaviw5d22a232019-12-11 16:47:32 -08002213 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 if (!(inputTargetFlags & dispatchMode)) {
2215 return;
2216 }
2217 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2218
2219 // This is a new event.
2220 // Enqueue a new dispatch entry onto the outbound queue for this connection.
chaviw5d22a232019-12-11 16:47:32 -08002221 std::unique_ptr<DispatchEntry> dispatchEntry =
2222 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223
2224 // Apply target flags and update the connection's input state.
2225 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002226 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002227 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*eventEntry);
2228 dispatchEntry->resolvedAction = keyEntry.action;
2229 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002231 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2232 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002234 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2235 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002237 return; // skip the inconsistent event
2238 }
2239 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002242 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002243 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002244 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2245 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2246 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2247 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2248 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2249 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2250 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2251 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2252 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2253 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2254 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002255 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002256 }
2257 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002258 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2259 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002261 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2262 "event",
2263 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002265 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002268 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002269 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2270 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2271 }
2272 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2273 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2274 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002276 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2277 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002279 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2280 "event",
2281 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002283 return; // skip the inconsistent event
2284 }
2285
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002286 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
chaviw5d22a232019-12-11 16:47:32 -08002287 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002288
2289 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002291 case EventEntry::Type::CONFIGURATION_CHANGED:
2292 case EventEntry::Type::DEVICE_RESET: {
2293 LOG_ALWAYS_FATAL("%s events should not go to apps",
2294 EventEntry::typeToString(eventEntry->type));
2295 break;
2296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 }
2298
2299 // Remember that we are waiting for this dispatch to complete.
2300 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002301 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302 }
2303
2304 // Enqueue the dispatch entry.
chaviw5d22a232019-12-11 16:47:32 -08002305 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002306 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002307}
2308
chaviwfd6d3512019-03-25 13:23:49 -07002309void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002310 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002311 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002312 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2313 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002314 return;
2315 }
2316
2317 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2318 if (inputWindowHandle == nullptr) {
2319 return;
2320 }
2321
chaviw8c9cf542019-03-25 13:02:48 -07002322 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002323 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002324
2325 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2326
2327 if (!hasFocusChanged) {
2328 return;
2329 }
2330
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002331 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2332 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002333 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002334 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335}
2336
2337void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002338 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002339 if (ATRACE_ENABLED()) {
2340 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002341 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002342 ATRACE_NAME(message.c_str());
2343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002345 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346#endif
2347
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002348 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2349 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350 dispatchEntry->deliveryTime = currentTime;
2351
2352 // Publish the event.
2353 status_t status;
2354 EventEntry* eventEntry = dispatchEntry->eventEntry;
2355 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002356 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002357 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002359 // Publish the key event.
2360 status = connection->inputPublisher
2361 .publishKeyEvent(dispatchEntry->seq, keyEntry->deviceId,
2362 keyEntry->source, keyEntry->displayId,
2363 dispatchEntry->resolvedAction,
2364 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2365 keyEntry->scanCode, keyEntry->metaState,
2366 keyEntry->repeatCount, keyEntry->downTime,
2367 keyEntry->eventTime);
2368 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369 }
2370
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002371 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002372 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002374 PointerCoords scaledCoords[MAX_POINTERS];
2375 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2376
2377 // Set the X and Y offset depending on the input source.
2378 float xOffset, yOffset;
2379 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2380 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2381 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2382 float wxs = dispatchEntry->windowXScale;
2383 float wys = dispatchEntry->windowYScale;
2384 xOffset = dispatchEntry->xOffset * wxs;
2385 yOffset = dispatchEntry->yOffset * wys;
2386 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
2387 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2388 scaledCoords[i] = motionEntry->pointerCoords[i];
2389 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
2390 }
2391 usingCoords = scaledCoords;
2392 }
2393 } else {
2394 xOffset = 0.0f;
2395 yOffset = 0.0f;
2396
2397 // We don't want the dispatch target to know.
2398 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2399 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2400 scaledCoords[i].clear();
2401 }
2402 usingCoords = scaledCoords;
2403 }
2404 }
2405
2406 // Publish the motion event.
2407 status = connection->inputPublisher
2408 .publishMotionEvent(dispatchEntry->seq, motionEntry->deviceId,
2409 motionEntry->source, motionEntry->displayId,
2410 dispatchEntry->resolvedAction,
2411 motionEntry->actionButton,
2412 dispatchEntry->resolvedFlags,
2413 motionEntry->edgeFlags, motionEntry->metaState,
2414 motionEntry->buttonState,
2415 motionEntry->classification, xOffset, yOffset,
2416 motionEntry->xPrecision,
2417 motionEntry->yPrecision,
2418 motionEntry->xCursorPosition,
2419 motionEntry->yCursorPosition,
2420 motionEntry->downTime, motionEntry->eventTime,
2421 motionEntry->pointerCount,
2422 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002423 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002424 break;
2425 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002426 case EventEntry::Type::CONFIGURATION_CHANGED:
2427 case EventEntry::Type::DEVICE_RESET: {
2428 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2429 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002430 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002431 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432 }
2433
2434 // Check the result.
2435 if (status) {
2436 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002437 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002439 "This is unexpected because the wait queue is empty, so the pipe "
2440 "should be empty and we shouldn't have any problems writing an "
2441 "event to it, status=%d",
2442 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2444 } else {
2445 // Pipe is full and we are waiting for the app to finish process some events
2446 // before sending more events to it.
2447#if DEBUG_DISPATCH_CYCLE
2448 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002449 "waiting for the application to catch up",
2450 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451#endif
2452 connection->inputPublisherBlocked = true;
2453 }
2454 } else {
2455 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002456 "status=%d",
2457 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2459 }
2460 return;
2461 }
2462
2463 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002464 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2465 connection->outboundQueue.end(),
2466 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002467 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002468 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002469 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 }
2471}
2472
2473void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002474 const sp<Connection>& connection, uint32_t seq,
2475 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476#if DEBUG_DISPATCH_CYCLE
2477 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002478 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479#endif
2480
2481 connection->inputPublisherBlocked = false;
2482
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002483 if (connection->status == Connection::STATUS_BROKEN ||
2484 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485 return;
2486 }
2487
2488 // Notify other system components and prepare to start the next dispatch cycle.
2489 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2490}
2491
2492void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002493 const sp<Connection>& connection,
2494 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495#if DEBUG_DISPATCH_CYCLE
2496 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002497 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498#endif
2499
2500 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002501 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002502 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002503 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002504 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505
2506 // The connection appears to be unrecoverably broken.
2507 // Ignore already broken or zombie connections.
2508 if (connection->status == Connection::STATUS_NORMAL) {
2509 connection->status = Connection::STATUS_BROKEN;
2510
2511 if (notify) {
2512 // Notify other system components.
2513 onDispatchCycleBrokenLocked(currentTime, connection);
2514 }
2515 }
2516}
2517
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002518void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2519 while (!queue.empty()) {
2520 DispatchEntry* dispatchEntry = queue.front();
2521 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002522 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523 }
2524}
2525
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002526void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002528 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529 }
2530 delete dispatchEntry;
2531}
2532
2533int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2534 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2535
2536 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002537 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002539 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002541 "fd=%d, events=0x%x",
2542 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543 return 0; // remove the callback
2544 }
2545
2546 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002547 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2549 if (!(events & ALOOPER_EVENT_INPUT)) {
2550 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002551 "events=0x%x",
2552 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 return 1;
2554 }
2555
2556 nsecs_t currentTime = now();
2557 bool gotOne = false;
2558 status_t status;
2559 for (;;) {
2560 uint32_t seq;
2561 bool handled;
2562 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2563 if (status) {
2564 break;
2565 }
2566 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2567 gotOne = true;
2568 }
2569 if (gotOne) {
2570 d->runCommandsLockedInterruptible();
2571 if (status == WOULD_BLOCK) {
2572 return 1;
2573 }
2574 }
2575
2576 notify = status != DEAD_OBJECT || !connection->monitor;
2577 if (notify) {
2578 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002579 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 }
2581 } else {
2582 // Monitor channels are never explicitly unregistered.
2583 // We do it automatically when the remote endpoint is closed so don't warn
2584 // about them.
2585 notify = !connection->monitor;
2586 if (notify) {
2587 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002588 "events=0x%x",
2589 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002590 }
2591 }
2592
2593 // Unregister the channel.
2594 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2595 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002596 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597}
2598
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002599void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002601 for (const auto& pair : mConnectionsByFd) {
2602 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 }
2604}
2605
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002606void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002607 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002608 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2609 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2610}
2611
2612void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2613 const CancelationOptions& options,
2614 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2615 for (const auto& it : monitorsByDisplay) {
2616 const std::vector<Monitor>& monitors = it.second;
2617 for (const Monitor& monitor : monitors) {
2618 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002619 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002620 }
2621}
2622
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2624 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002625 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002626 if (connection == nullptr) {
2627 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002629
2630 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631}
2632
2633void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2634 const sp<Connection>& connection, const CancelationOptions& options) {
2635 if (connection->status == Connection::STATUS_BROKEN) {
2636 return;
2637 }
2638
2639 nsecs_t currentTime = now();
2640
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002641 std::vector<EventEntry*> cancelationEvents =
2642 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002644 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002646 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002647 "with reality: %s, mode=%d.",
2648 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2649 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650#endif
2651 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002652 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 switch (cancelationEventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002654 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002655 logOutboundKeyDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002656 static_cast<const KeyEntry&>(*cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002657 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002658 }
2659 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002660 logOutboundMotionDetails("cancel - ",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002661 static_cast<const MotionEntry&>(
2662 *cancelationEventEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002663 break;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002664 }
2665 case EventEntry::Type::CONFIGURATION_CHANGED:
2666 case EventEntry::Type::DEVICE_RESET: {
2667 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2668 EventEntry::typeToString(cancelationEventEntry->type));
2669 break;
2670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 }
2672
2673 InputTarget target;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002674 sp<InputWindowHandle> windowHandle =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002675 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002676 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw5d22a232019-12-11 16:47:32 -08002678 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2679 windowInfo->windowXScale, windowInfo->windowYScale);
Robert Carre07e1032018-11-26 12:55:53 -08002680 target.globalScaleFactor = windowInfo->globalScaleFactor;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681 }
2682 target.inputChannel = connection->inputChannel;
2683 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2684
chaviw8c9cf542019-03-25 13:02:48 -07002685 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
chaviw5d22a232019-12-11 16:47:32 -08002686 target, InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687
2688 cancelationEventEntry->release();
2689 }
2690
2691 startDispatchCycleLocked(currentTime, connection);
2692 }
2693}
2694
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002695MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002696 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 ALOG_ASSERT(pointerIds.value != 0);
2698
2699 uint32_t splitPointerIndexMap[MAX_POINTERS];
2700 PointerProperties splitPointerProperties[MAX_POINTERS];
2701 PointerCoords splitPointerCoords[MAX_POINTERS];
2702
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002703 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704 uint32_t splitPointerCount = 0;
2705
2706 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002707 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002709 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 uint32_t pointerId = uint32_t(pointerProperties.id);
2711 if (pointerIds.hasBit(pointerId)) {
2712 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2713 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2714 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002715 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716 splitPointerCount += 1;
2717 }
2718 }
2719
2720 if (splitPointerCount != pointerIds.count()) {
2721 // This is bad. We are missing some of the pointers that we expected to deliver.
2722 // Most likely this indicates that we received an ACTION_MOVE events that has
2723 // different pointer ids than we expected based on the previous ACTION_DOWN
2724 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2725 // in this way.
2726 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002727 "we expected there to be %d pointers. This probably means we received "
2728 "a broken sequence of pointer ids from the input device.",
2729 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002730 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002731 }
2732
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002733 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002735 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2736 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2738 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002739 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740 uint32_t pointerId = uint32_t(pointerProperties.id);
2741 if (pointerIds.hasBit(pointerId)) {
2742 if (pointerIds.count() == 1) {
2743 // The first/last pointer went down/up.
2744 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002745 ? AMOTION_EVENT_ACTION_DOWN
2746 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747 } else {
2748 // A secondary pointer went down/up.
2749 uint32_t splitPointerIndex = 0;
2750 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2751 splitPointerIndex += 1;
2752 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002753 action = maskedAction |
2754 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755 }
2756 } else {
2757 // An unrelated pointer changed.
2758 action = AMOTION_EVENT_ACTION_MOVE;
2759 }
2760 }
2761
Garfield Tan00f511d2019-06-12 16:55:40 -07002762 MotionEntry* splitMotionEntry =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002763 new MotionEntry(originalMotionEntry.sequenceNum, originalMotionEntry.eventTime,
2764 originalMotionEntry.deviceId, originalMotionEntry.source,
2765 originalMotionEntry.displayId, originalMotionEntry.policyFlags, action,
2766 originalMotionEntry.actionButton, originalMotionEntry.flags,
2767 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2768 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2769 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2770 originalMotionEntry.xCursorPosition,
2771 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002772 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002774 if (originalMotionEntry.injectionState) {
2775 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776 splitMotionEntry->injectionState->refCount += 1;
2777 }
2778
2779 return splitMotionEntry;
2780}
2781
2782void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2783#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002784 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785#endif
2786
2787 bool needWake;
2788 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002789 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790
Prabir Pradhan42611e02018-11-27 14:04:02 -08002791 ConfigurationChangedEntry* newEntry =
2792 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 needWake = enqueueInboundEventLocked(newEntry);
2794 } // release lock
2795
2796 if (needWake) {
2797 mLooper->wake();
2798 }
2799}
2800
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002801/**
2802 * If one of the meta shortcuts is detected, process them here:
2803 * Meta + Backspace -> generate BACK
2804 * Meta + Enter -> generate HOME
2805 * This will potentially overwrite keyCode and metaState.
2806 */
2807void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002808 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002809 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2810 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2811 if (keyCode == AKEYCODE_DEL) {
2812 newKeyCode = AKEYCODE_BACK;
2813 } else if (keyCode == AKEYCODE_ENTER) {
2814 newKeyCode = AKEYCODE_HOME;
2815 }
2816 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002817 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002818 struct KeyReplacement replacement = {keyCode, deviceId};
2819 mReplacedKeys.add(replacement, newKeyCode);
2820 keyCode = newKeyCode;
2821 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2822 }
2823 } else if (action == AKEY_EVENT_ACTION_UP) {
2824 // In order to maintain a consistent stream of up and down events, check to see if the key
2825 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2826 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002827 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002828 struct KeyReplacement replacement = {keyCode, deviceId};
2829 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2830 if (index >= 0) {
2831 keyCode = mReplacedKeys.valueAt(index);
2832 mReplacedKeys.removeItemsAt(index);
2833 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2834 }
2835 }
2836}
2837
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2839#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002840 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2841 "policyFlags=0x%x, action=0x%x, "
2842 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2843 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2844 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2845 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846#endif
2847 if (!validateKeyEvent(args->action)) {
2848 return;
2849 }
2850
2851 uint32_t policyFlags = args->policyFlags;
2852 int32_t flags = args->flags;
2853 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002854 // InputDispatcher tracks and generates key repeats on behalf of
2855 // whatever notifies it, so repeatCount should always be set to 0
2856 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002857 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2858 policyFlags |= POLICY_FLAG_VIRTUAL;
2859 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2860 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861 if (policyFlags & POLICY_FLAG_FUNCTION) {
2862 metaState |= AMETA_FUNCTION_ON;
2863 }
2864
2865 policyFlags |= POLICY_FLAG_TRUSTED;
2866
Michael Wright78f24442014-08-06 15:55:28 -07002867 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002868 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002869
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870 KeyEvent event;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002871 event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2872 args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873
Michael Wright2b3c3302018-03-02 17:19:13 +00002874 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002876 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2877 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002878 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881 bool needWake;
2882 { // acquire lock
2883 mLock.lock();
2884
2885 if (shouldSendKeyToInputFilterLocked(args)) {
2886 mLock.unlock();
2887
2888 policyFlags |= POLICY_FLAG_FILTERED;
2889 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2890 return; // event was consumed by the filter
2891 }
2892
2893 mLock.lock();
2894 }
2895
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002896 KeyEntry* newEntry =
2897 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2898 args->displayId, policyFlags, args->action, flags, keyCode,
2899 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900
2901 needWake = enqueueInboundEventLocked(newEntry);
2902 mLock.unlock();
2903 } // release lock
2904
2905 if (needWake) {
2906 mLooper->wake();
2907 }
2908}
2909
2910bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2911 return mInputFilterEnabled;
2912}
2913
2914void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2915#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002916 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan00f511d2019-06-12 16:55:40 -07002917 ", policyFlags=0x%x, "
2918 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
2919 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07002920 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan00f511d2019-06-12 16:55:40 -07002921 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2922 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Jaewan Kim372fbe42019-10-02 10:58:46 +09002923 args->edgeFlags, args->xPrecision, args->yPrecision, args->xCursorPosition,
Garfield Tan00f511d2019-06-12 16:55:40 -07002924 args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 for (uint32_t i = 0; i < args->pointerCount; i++) {
2926 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002927 "x=%f, y=%f, pressure=%f, size=%f, "
2928 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2929 "orientation=%f",
2930 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2931 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2932 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2933 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2934 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2935 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2936 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2937 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2938 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2939 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 }
2941#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002942 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2943 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002944 return;
2945 }
2946
2947 uint32_t policyFlags = args->policyFlags;
2948 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002949
2950 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002951 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002952 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2953 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002954 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956
2957 bool needWake;
2958 { // acquire lock
2959 mLock.lock();
2960
2961 if (shouldSendMotionToInputFilterLocked(args)) {
2962 mLock.unlock();
2963
2964 MotionEvent event;
Garfield Tan00f511d2019-06-12 16:55:40 -07002965 event.initialize(args->deviceId, args->source, args->displayId, args->action,
2966 args->actionButton, args->flags, args->edgeFlags, args->metaState,
2967 args->buttonState, args->classification, 0, 0, args->xPrecision,
2968 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2969 args->downTime, args->eventTime, args->pointerCount,
2970 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971
2972 policyFlags |= POLICY_FLAG_FILTERED;
2973 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2974 return; // event was consumed by the filter
2975 }
2976
2977 mLock.lock();
2978 }
2979
2980 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07002981 MotionEntry* newEntry =
2982 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2983 args->displayId, policyFlags, args->action, args->actionButton,
2984 args->flags, args->metaState, args->buttonState,
2985 args->classification, args->edgeFlags, args->xPrecision,
2986 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2987 args->downTime, args->pointerCount, args->pointerProperties,
2988 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002989
2990 needWake = enqueueInboundEventLocked(newEntry);
2991 mLock.unlock();
2992 } // release lock
2993
2994 if (needWake) {
2995 mLooper->wake();
2996 }
2997}
2998
2999bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003000 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001}
3002
3003void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3004#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003005 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003006 "switchMask=0x%08x",
3007 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003008#endif
3009
3010 uint32_t policyFlags = args->policyFlags;
3011 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003012 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013}
3014
3015void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3016#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003017 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3018 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019#endif
3020
3021 bool needWake;
3022 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003023 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024
Prabir Pradhan42611e02018-11-27 14:04:02 -08003025 DeviceResetEntry* newEntry =
3026 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003027 needWake = enqueueInboundEventLocked(newEntry);
3028 } // release lock
3029
3030 if (needWake) {
3031 mLooper->wake();
3032 }
3033}
3034
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003035int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3036 int32_t injectorUid, int32_t syncMode,
3037 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038#if DEBUG_INBOUND_EVENT_DETAILS
3039 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003040 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
3041 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042#endif
3043
3044 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
3045
3046 policyFlags |= POLICY_FLAG_INJECTED;
3047 if (hasInjectionPermission(injectorPid, injectorUid)) {
3048 policyFlags |= POLICY_FLAG_TRUSTED;
3049 }
3050
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003051 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003053 case AINPUT_EVENT_TYPE_KEY: {
3054 KeyEvent keyEvent;
3055 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
3056 int32_t action = keyEvent.getAction();
3057 if (!validateKeyEvent(action)) {
3058 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003059 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003060
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003061 int32_t flags = keyEvent.getFlags();
3062 int32_t keyCode = keyEvent.getKeyCode();
3063 int32_t metaState = keyEvent.getMetaState();
3064 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
3065 /*byref*/ keyCode, /*byref*/ metaState);
3066 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
3067 keyEvent.getDisplayId(), action, flags, keyCode,
3068 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
3069 keyEvent.getDownTime(), keyEvent.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003071 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3072 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003073 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003074
3075 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3076 android::base::Timer t;
3077 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3078 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3079 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3080 std::to_string(t.duration().count()).c_str());
3081 }
3082 }
3083
3084 mLock.lock();
3085 KeyEntry* injectedEntry =
3086 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
3087 keyEvent.getDeviceId(), keyEvent.getSource(),
3088 keyEvent.getDisplayId(), policyFlags, action, flags,
3089 keyEvent.getKeyCode(), keyEvent.getScanCode(),
3090 keyEvent.getMetaState(), keyEvent.getRepeatCount(),
3091 keyEvent.getDownTime());
3092 injectedEntries.push(injectedEntry);
3093 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094 }
3095
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003096 case AINPUT_EVENT_TYPE_MOTION: {
3097 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3098 int32_t action = motionEvent->getAction();
3099 size_t pointerCount = motionEvent->getPointerCount();
3100 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3101 int32_t actionButton = motionEvent->getActionButton();
3102 int32_t displayId = motionEvent->getDisplayId();
3103 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3104 return INPUT_EVENT_INJECTION_FAILED;
3105 }
3106
3107 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3108 nsecs_t eventTime = motionEvent->getEventTime();
3109 android::base::Timer t;
3110 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3111 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3112 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3113 std::to_string(t.duration().count()).c_str());
3114 }
3115 }
3116
3117 mLock.lock();
3118 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3119 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3120 MotionEntry* injectedEntry =
Garfield Tan00f511d2019-06-12 16:55:40 -07003121 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3122 motionEvent->getDeviceId(), motionEvent->getSource(),
3123 motionEvent->getDisplayId(), policyFlags, action, actionButton,
3124 motionEvent->getFlags(), motionEvent->getMetaState(),
3125 motionEvent->getButtonState(), motionEvent->getClassification(),
3126 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3127 motionEvent->getYPrecision(),
3128 motionEvent->getRawXCursorPosition(),
3129 motionEvent->getRawYCursorPosition(),
3130 motionEvent->getDownTime(), uint32_t(pointerCount),
3131 pointerProperties, samplePointerCoords,
3132 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003133 injectedEntries.push(injectedEntry);
3134 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3135 sampleEventTimes += 1;
3136 samplePointerCoords += pointerCount;
3137 MotionEntry* nextInjectedEntry =
3138 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
3139 motionEvent->getDeviceId(), motionEvent->getSource(),
3140 motionEvent->getDisplayId(), policyFlags, action,
3141 actionButton, motionEvent->getFlags(),
3142 motionEvent->getMetaState(), motionEvent->getButtonState(),
3143 motionEvent->getClassification(),
3144 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3145 motionEvent->getYPrecision(),
3146 motionEvent->getRawXCursorPosition(),
3147 motionEvent->getRawYCursorPosition(),
3148 motionEvent->getDownTime(), uint32_t(pointerCount),
3149 pointerProperties, samplePointerCoords,
3150 motionEvent->getXOffset(), motionEvent->getYOffset());
3151 injectedEntries.push(nextInjectedEntry);
3152 }
3153 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003156 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003157 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003158 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 }
3160
3161 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3162 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3163 injectionState->injectionIsAsync = true;
3164 }
3165
3166 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003167 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168
3169 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003170 while (!injectedEntries.empty()) {
3171 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3172 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173 }
3174
3175 mLock.unlock();
3176
3177 if (needWake) {
3178 mLooper->wake();
3179 }
3180
3181 int32_t injectionResult;
3182 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003183 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184
3185 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3186 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3187 } else {
3188 for (;;) {
3189 injectionResult = injectionState->injectionResult;
3190 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3191 break;
3192 }
3193
3194 nsecs_t remainingTimeout = endTime - now();
3195 if (remainingTimeout <= 0) {
3196#if DEBUG_INJECTION
3197 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003198 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199#endif
3200 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3201 break;
3202 }
3203
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003204 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 }
3206
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003207 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3208 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 while (injectionState->pendingForegroundDispatches != 0) {
3210#if DEBUG_INJECTION
3211 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213#endif
3214 nsecs_t remainingTimeout = endTime - now();
3215 if (remainingTimeout <= 0) {
3216#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003217 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3218 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219#endif
3220 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3221 break;
3222 }
3223
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003224 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 }
3226 }
3227 }
3228
3229 injectionState->release();
3230 } // release lock
3231
3232#if DEBUG_INJECTION
3233 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003234 "injectorPid=%d, injectorUid=%d",
3235 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236#endif
3237
3238 return injectionResult;
3239}
3240
3241bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003242 return injectorUid == 0 ||
3243 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244}
3245
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003246void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247 InjectionState* injectionState = entry->injectionState;
3248 if (injectionState) {
3249#if DEBUG_INJECTION
3250 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003251 "injectorPid=%d, injectorUid=%d",
3252 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253#endif
3254
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003255 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256 // Log the outcome since the injector did not wait for the injection result.
3257 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003258 case INPUT_EVENT_INJECTION_SUCCEEDED:
3259 ALOGV("Asynchronous input event injection succeeded.");
3260 break;
3261 case INPUT_EVENT_INJECTION_FAILED:
3262 ALOGW("Asynchronous input event injection failed.");
3263 break;
3264 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3265 ALOGW("Asynchronous input event injection permission denied.");
3266 break;
3267 case INPUT_EVENT_INJECTION_TIMED_OUT:
3268 ALOGW("Asynchronous input event injection timed out.");
3269 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270 }
3271 }
3272
3273 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003274 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275 }
3276}
3277
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003278void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279 InjectionState* injectionState = entry->injectionState;
3280 if (injectionState) {
3281 injectionState->pendingForegroundDispatches += 1;
3282 }
3283}
3284
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003285void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286 InjectionState* injectionState = entry->injectionState;
3287 if (injectionState) {
3288 injectionState->pendingForegroundDispatches -= 1;
3289
3290 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003291 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292 }
3293 }
3294}
3295
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003296std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3297 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003298 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003299}
3300
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003302 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003303 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003304 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3305 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003306 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003307 return windowHandle;
3308 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 }
3310 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003311 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312}
3313
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003314bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003315 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003316 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3317 for (const sp<InputWindowHandle>& handle : windowHandles) {
3318 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003319 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003320 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003321 ", but it should belong to display %" PRId32,
3322 windowHandle->getName().c_str(), it.first,
3323 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003324 }
3325 return true;
3326 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327 }
3328 }
3329 return false;
3330}
3331
Robert Carr5c8a0262018-10-03 16:30:44 -07003332sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3333 size_t count = mInputChannelsByToken.count(token);
3334 if (count == 0) {
3335 return nullptr;
3336 }
3337 return mInputChannelsByToken.at(token);
3338}
3339
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003340void InputDispatcher::updateWindowHandlesForDisplayLocked(
3341 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3342 if (inputWindowHandles.empty()) {
3343 // Remove all handles on a display if there are no windows left.
3344 mWindowHandlesByDisplay.erase(displayId);
3345 return;
3346 }
3347
3348 // Since we compare the pointer of input window handles across window updates, we need
3349 // to make sure the handle object for the same window stays unchanged across updates.
3350 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003351 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003352 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003353 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003354 }
3355
3356 std::vector<sp<InputWindowHandle>> newHandles;
3357 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3358 if (!handle->updateInfo()) {
3359 // handle no longer valid
3360 continue;
3361 }
3362
3363 const InputWindowInfo* info = handle->getInfo();
3364 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3365 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3366 const bool noInputChannel =
3367 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3368 const bool canReceiveInput =
3369 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3370 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3371 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003372 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003373 handle->getName().c_str());
3374 }
3375 continue;
3376 }
3377
3378 if (info->displayId != displayId) {
3379 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3380 handle->getName().c_str(), displayId, info->displayId);
3381 continue;
3382 }
3383
chaviwaf87b3e2019-10-01 16:59:28 -07003384 if (oldHandlesById.find(handle->getId()) != oldHandlesById.end()) {
3385 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003386 oldHandle->updateFrom(handle);
3387 newHandles.push_back(oldHandle);
3388 } else {
3389 newHandles.push_back(handle);
3390 }
3391 }
3392
3393 // Insert or replace
3394 mWindowHandlesByDisplay[displayId] = newHandles;
3395}
3396
Arthur Hungb92218b2018-08-14 12:00:21 +08003397/**
3398 * Called from InputManagerService, update window handle list by displayId that can receive input.
3399 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3400 * If set an empty list, remove all handles from the specific display.
3401 * For focused handle, check if need to change and send a cancel event to previous one.
3402 * For removed handle, check if need to send a cancel event if already in touch.
3403 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003404void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003405 int32_t displayId,
3406 const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003407 if (DEBUG_FOCUS) {
3408 std::string windowList;
3409 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3410 windowList += iwh->getName() + " ";
3411 }
3412 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003415 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416
Arthur Hungb92218b2018-08-14 12:00:21 +08003417 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003418 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3419 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003421 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
3422
Tiger Huang721e26f2018-07-24 22:26:19 +08003423 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 bool foundHoveredWindow = false;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003425 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3426 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3427 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3428 windowHandle->getInfo()->visible) {
3429 newFocusedWindowHandle = windowHandle;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003430 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003431 if (windowHandle == mLastHoverWindowHandle) {
3432 foundHoveredWindow = true;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434 }
3435
3436 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003437 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 }
3439
Tiger Huang721e26f2018-07-24 22:26:19 +08003440 sp<InputWindowHandle> oldFocusedWindowHandle =
3441 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3442
chaviwaf87b3e2019-10-01 16:59:28 -07003443 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003444 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003445 if (DEBUG_FOCUS) {
3446 ALOGD("Focus left window: %s in display %" PRId32,
3447 oldFocusedWindowHandle->getName().c_str(), displayId);
3448 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003449 sp<InputChannel> focusedInputChannel =
3450 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003451 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003453 "focus left window");
3454 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003456 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003458 if (newFocusedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003459 if (DEBUG_FOCUS) {
3460 ALOGD("Focus entered window: %s in display %" PRId32,
3461 newFocusedWindowHandle->getName().c_str(), displayId);
3462 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003463 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003464 }
Robert Carrf759f162018-11-13 12:57:11 -08003465
3466 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003467 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469 }
3470
Arthur Hungb92218b2018-08-14 12:00:21 +08003471 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3472 if (stateIndex >= 0) {
3473 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003474 for (size_t i = 0; i < state.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003475 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003476 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003477 if (DEBUG_FOCUS) {
3478 ALOGD("Touched window was removed: %s in display %" PRId32,
3479 touchedWindow.windowHandle->getName().c_str(), displayId);
3480 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003481 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003482 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003483 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003484 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003485 "touched window was removed");
3486 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3487 options);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003488 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003489 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003490 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003491 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493 }
3494 }
3495
3496 // Release information for windows that are no longer present.
3497 // This ensures that unused input channels are released promptly.
3498 // Otherwise, they might stick around until the window handle is destroyed
3499 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003500 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003501 if (!hasWindowHandleLocked(oldWindowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003502 if (DEBUG_FOCUS) {
3503 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
3504 }
Arthur Hung3b413f22018-10-26 18:05:34 +08003505 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506 }
3507 }
3508 } // release lock
3509
3510 // Wake up poll loop since it may need to make new input dispatching choices.
3511 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003512
3513 if (setInputWindowsListener) {
3514 setInputWindowsListener->onSetInputWindowsFinished();
3515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516}
3517
3518void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003519 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003520 if (DEBUG_FOCUS) {
3521 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3522 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3523 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003525 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526
Tiger Huang721e26f2018-07-24 22:26:19 +08003527 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3528 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003529 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003530 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3531 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003534 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003536 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003538 oldFocusedApplicationHandle.clear();
3539 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003541 } // release lock
3542
3543 // Wake up poll loop since it may need to make new input dispatching choices.
3544 mLooper->wake();
3545}
3546
Tiger Huang721e26f2018-07-24 22:26:19 +08003547/**
3548 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3549 * the display not specified.
3550 *
3551 * We track any unreleased events for each window. If a window loses the ability to receive the
3552 * released event, we will send a cancel event to it. So when the focused display is changed, we
3553 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3554 * display. The display-specified events won't be affected.
3555 */
3556void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003557 if (DEBUG_FOCUS) {
3558 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3559 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003560 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003561 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003562
3563 if (mFocusedDisplayId != displayId) {
3564 sp<InputWindowHandle> oldFocusedWindowHandle =
3565 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3566 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003567 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003568 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003569 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003570 CancelationOptions
3571 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3572 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003573 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003574 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3575 }
3576 }
3577 mFocusedDisplayId = displayId;
3578
3579 // Sanity check
3580 sp<InputWindowHandle> newFocusedWindowHandle =
3581 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003582 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003583
Tiger Huang721e26f2018-07-24 22:26:19 +08003584 if (newFocusedWindowHandle == nullptr) {
3585 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3586 if (!mFocusedWindowHandlesByDisplay.empty()) {
3587 ALOGE("But another display has a focused window:");
3588 for (auto& it : mFocusedWindowHandlesByDisplay) {
3589 const int32_t displayId = it.first;
3590 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003591 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3592 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003593 }
3594 }
3595 }
3596 }
3597
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003598 if (DEBUG_FOCUS) {
3599 logDispatchStateLocked();
3600 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003601 } // release lock
3602
3603 // Wake up poll loop since it may need to make new input dispatching choices.
3604 mLooper->wake();
3605}
3606
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003608 if (DEBUG_FOCUS) {
3609 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611
3612 bool changed;
3613 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003614 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615
3616 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3617 if (mDispatchFrozen && !frozen) {
3618 resetANRTimeoutsLocked();
3619 }
3620
3621 if (mDispatchEnabled && !enabled) {
3622 resetAndDropEverythingLocked("dispatcher is being disabled");
3623 }
3624
3625 mDispatchEnabled = enabled;
3626 mDispatchFrozen = frozen;
3627 changed = true;
3628 } else {
3629 changed = false;
3630 }
3631
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003632 if (DEBUG_FOCUS) {
3633 logDispatchStateLocked();
3634 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 } // release lock
3636
3637 if (changed) {
3638 // Wake up poll loop since it may need to make new input dispatching choices.
3639 mLooper->wake();
3640 }
3641}
3642
3643void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003644 if (DEBUG_FOCUS) {
3645 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647
3648 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003649 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650
3651 if (mInputFilterEnabled == enabled) {
3652 return;
3653 }
3654
3655 mInputFilterEnabled = enabled;
3656 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3657 } // release lock
3658
3659 // Wake up poll loop since there might be work to do to drop everything.
3660 mLooper->wake();
3661}
3662
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003663void InputDispatcher::setInTouchMode(bool inTouchMode) {
3664 std::scoped_lock lock(mLock);
3665 mInTouchMode = inTouchMode;
3666}
3667
chaviwfbe5d9c2018-12-26 12:23:37 -08003668bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3669 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003670 if (DEBUG_FOCUS) {
3671 ALOGD("Trivial transfer to same window.");
3672 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003673 return true;
3674 }
3675
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003677 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678
chaviwfbe5d9c2018-12-26 12:23:37 -08003679 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3680 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003681 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003682 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 return false;
3684 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003685 if (DEBUG_FOCUS) {
3686 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3687 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003690 if (DEBUG_FOCUS) {
3691 ALOGD("Cannot transfer focus because windows are on different displays.");
3692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 return false;
3694 }
3695
3696 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003697 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3698 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3699 for (size_t i = 0; i < state.windows.size(); i++) {
3700 const TouchedWindow& touchedWindow = state.windows[i];
3701 if (touchedWindow.windowHandle == fromWindowHandle) {
3702 int32_t oldTargetFlags = touchedWindow.targetFlags;
3703 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003705 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003707 int32_t newTargetFlags = oldTargetFlags &
3708 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3709 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003710 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711
Jeff Brownf086ddb2014-02-11 14:28:48 -08003712 found = true;
3713 goto Found;
3714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 }
3716 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003717 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003719 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003720 if (DEBUG_FOCUS) {
3721 ALOGD("Focus transfer failed because from window did not have focus.");
3722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723 return false;
3724 }
3725
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003726 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3727 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003728 if (fromConnection != nullptr && toConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003730 CancelationOptions
3731 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3732 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3734 }
3735
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003736 if (DEBUG_FOCUS) {
3737 logDispatchStateLocked();
3738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 } // release lock
3740
3741 // Wake up poll loop since it may need to make new input dispatching choices.
3742 mLooper->wake();
3743 return true;
3744}
3745
3746void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003747 if (DEBUG_FOCUS) {
3748 ALOGD("Resetting and dropping all events (%s).", reason);
3749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750
3751 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3752 synthesizeCancelationEventsForAllConnectionsLocked(options);
3753
3754 resetKeyRepeatLocked();
3755 releasePendingEventLocked();
3756 drainInboundQueueLocked();
3757 resetANRTimeoutsLocked();
3758
Jeff Brownf086ddb2014-02-11 14:28:48 -08003759 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003761 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762}
3763
3764void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003765 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 dumpDispatchStateLocked(dump);
3767
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003768 std::istringstream stream(dump);
3769 std::string line;
3770
3771 while (std::getline(stream, line, '\n')) {
3772 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 }
3774}
3775
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003776void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003777 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3778 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3779 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003780 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781
Tiger Huang721e26f2018-07-24 22:26:19 +08003782 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3783 dump += StringPrintf(INDENT "FocusedApplications:\n");
3784 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3785 const int32_t displayId = it.first;
3786 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003787 dump += StringPrintf(INDENT2 "displayId=%" PRId32
3788 ", name='%s', dispatchingTimeout=%0.3fms\n",
3789 displayId, applicationHandle->getName().c_str(),
3790 applicationHandle->getDispatchingTimeout(
3791 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3792 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08003793 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003795 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003797
3798 if (!mFocusedWindowHandlesByDisplay.empty()) {
3799 dump += StringPrintf(INDENT "FocusedWindows:\n");
3800 for (auto& it : mFocusedWindowHandlesByDisplay) {
3801 const int32_t displayId = it.first;
3802 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003803 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3804 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003805 }
3806 } else {
3807 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809
Jeff Brownf086ddb2014-02-11 14:28:48 -08003810 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003811 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003812 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3813 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003814 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003815 state.displayId, toString(state.down), toString(state.split),
3816 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003817 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003818 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003819 for (size_t i = 0; i < state.windows.size(); i++) {
3820 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003821 dump += StringPrintf(INDENT4
3822 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3823 i, touchedWindow.windowHandle->getName().c_str(),
3824 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003825 }
3826 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003827 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003828 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003829 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003830 dump += INDENT3 "Portal windows:\n";
3831 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003832 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003833 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3834 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003835 }
3836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837 }
3838 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003839 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 }
3841
Arthur Hungb92218b2018-08-14 12:00:21 +08003842 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003843 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003844 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003845 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003846 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003847 dump += INDENT2 "Windows:\n";
3848 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003849 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003850 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851
Arthur Hungb92218b2018-08-14 12:00:21 +08003852 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003853 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08003854 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
3855 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003856 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08003857 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003858 i, windowInfo->name.c_str(), windowInfo->displayId,
3859 windowInfo->portalToDisplayId,
3860 toString(windowInfo->paused),
3861 toString(windowInfo->hasFocus),
3862 toString(windowInfo->hasWallpaper),
3863 toString(windowInfo->visible),
3864 toString(windowInfo->canReceiveKeys),
3865 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08003866 windowInfo->layoutParamsType, windowInfo->frameLeft,
3867 windowInfo->frameTop, windowInfo->frameRight,
3868 windowInfo->frameBottom, windowInfo->globalScaleFactor,
3869 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003870 dumpRegion(dump, windowInfo->touchableRegion);
3871 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3872 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003873 windowInfo->ownerPid, windowInfo->ownerUid,
3874 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08003875 }
3876 } else {
3877 dump += INDENT2 "Windows: <none>\n";
3878 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 }
3880 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003881 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882 }
3883
Michael Wright3dd60e22019-03-27 22:06:44 +00003884 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003885 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003886 const std::vector<Monitor>& monitors = it.second;
3887 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3888 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003889 }
3890 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003891 const std::vector<Monitor>& monitors = it.second;
3892 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3893 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003896 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897 }
3898
3899 nsecs_t currentTime = now();
3900
3901 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003902 if (!mRecentQueue.empty()) {
3903 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
3904 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003905 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003907 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 }
3909 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003910 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911 }
3912
3913 // Dump event currently being dispatched.
3914 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003915 dump += INDENT "PendingEvent:\n";
3916 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003918 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003919 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003921 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922 }
3923
3924 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003925 if (!mInboundQueue.empty()) {
3926 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
3927 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003928 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003930 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 }
3932 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003933 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934 }
3935
Michael Wright78f24442014-08-06 15:55:28 -07003936 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003937 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003938 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3939 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3940 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003941 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3942 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07003943 }
3944 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003945 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003946 }
3947
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003948 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003949 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003950 for (const auto& pair : mConnectionsByFd) {
3951 const sp<Connection>& connection = pair.second;
3952 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
3953 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3954 pair.first, connection->getInputChannelName().c_str(),
3955 connection->getWindowName().c_str(), connection->getStatusLabel(),
3956 toString(connection->monitor),
3957 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003959 if (!connection->outboundQueue.empty()) {
3960 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
3961 connection->outboundQueue.size());
3962 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 dump.append(INDENT4);
3964 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003965 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003966 entry->targetFlags, entry->resolvedAction,
3967 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 }
3969 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003970 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 }
3972
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003973 if (!connection->waitQueue.empty()) {
3974 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
3975 connection->waitQueue.size());
3976 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003977 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003979 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003980 "age=%0.1fms, wait=%0.1fms\n",
3981 entry->targetFlags, entry->resolvedAction,
3982 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3983 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 }
3985 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003986 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987 }
3988 }
3989 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003990 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 }
3992
3993 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003994 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003995 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003997 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998 }
3999
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004000 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004001 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004002 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004003 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004}
4005
Michael Wright3dd60e22019-03-27 22:06:44 +00004006void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4007 const size_t numMonitors = monitors.size();
4008 for (size_t i = 0; i < numMonitors; i++) {
4009 const Monitor& monitor = monitors[i];
4010 const sp<InputChannel>& channel = monitor.inputChannel;
4011 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4012 dump += "\n";
4013 }
4014}
4015
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004016status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004018 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019#endif
4020
4021 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004022 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004023 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004024 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004026 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027 return BAD_VALUE;
4028 }
4029
Michael Wright3dd60e22019-03-27 22:06:44 +00004030 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031
4032 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004033 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004034 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4037 } // release lock
4038
4039 // Wake the looper because some connections have changed.
4040 mLooper->wake();
4041 return OK;
4042}
4043
Michael Wright3dd60e22019-03-27 22:06:44 +00004044status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004045 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004046 { // acquire lock
4047 std::scoped_lock _l(mLock);
4048
4049 if (displayId < 0) {
4050 ALOGW("Attempted to register input monitor without a specified display.");
4051 return BAD_VALUE;
4052 }
4053
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004054 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004055 ALOGW("Attempted to register input monitor without an identifying token.");
4056 return BAD_VALUE;
4057 }
4058
4059 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
4060
4061 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004062 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004063 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004064
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004065 auto& monitorsByDisplay =
4066 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004067 monitorsByDisplay[displayId].emplace_back(inputChannel);
4068
4069 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004070 }
4071 // Wake the looper because some connections have changed.
4072 mLooper->wake();
4073 return OK;
4074}
4075
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4077#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004078 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079#endif
4080
4081 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004082 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083
4084 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4085 if (status) {
4086 return status;
4087 }
4088 } // release lock
4089
4090 // Wake the poll loop because removing the connection may have changed the current
4091 // synchronization state.
4092 mLooper->wake();
4093 return OK;
4094}
4095
4096status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004097 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004098 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004099 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004101 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102 return BAD_VALUE;
4103 }
4104
John Recke0710582019-09-26 13:46:12 -07004105 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004106 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004107 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004108
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 if (connection->monitor) {
4110 removeMonitorChannelLocked(inputChannel);
4111 }
4112
4113 mLooper->removeFd(inputChannel->getFd());
4114
4115 nsecs_t currentTime = now();
4116 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4117
4118 connection->status = Connection::STATUS_ZOMBIE;
4119 return OK;
4120}
4121
4122void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004123 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4124 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4125}
4126
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004127void InputDispatcher::removeMonitorChannelLocked(
4128 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004129 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004130 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004131 std::vector<Monitor>& monitors = it->second;
4132 const size_t numMonitors = monitors.size();
4133 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004134 if (monitors[i].inputChannel == inputChannel) {
4135 monitors.erase(monitors.begin() + i);
4136 break;
4137 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004138 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004139 if (monitors.empty()) {
4140 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004141 } else {
4142 ++it;
4143 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 }
4145}
4146
Michael Wright3dd60e22019-03-27 22:06:44 +00004147status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4148 { // acquire lock
4149 std::scoped_lock _l(mLock);
4150 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4151
4152 if (!foundDisplayId) {
4153 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4154 return BAD_VALUE;
4155 }
4156 int32_t displayId = foundDisplayId.value();
4157
4158 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4159 if (stateIndex < 0) {
4160 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4161 return BAD_VALUE;
4162 }
4163
4164 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4165 std::optional<int32_t> foundDeviceId;
4166 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004167 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004168 foundDeviceId = state.deviceId;
4169 }
4170 }
4171 if (!foundDeviceId || !state.down) {
4172 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004173 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004174 return BAD_VALUE;
4175 }
4176 int32_t deviceId = foundDeviceId.value();
4177
4178 // Send cancel events to all the input channels we're stealing from.
4179 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004181 options.deviceId = deviceId;
4182 options.displayId = displayId;
4183 for (const TouchedWindow& window : state.windows) {
4184 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004185 if (channel != nullptr) {
4186 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4187 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004188 }
4189 // Then clear the current touch state so we stop dispatching to them as well.
4190 state.filterNonMonitors();
4191 }
4192 return OK;
4193}
4194
Michael Wright3dd60e22019-03-27 22:06:44 +00004195std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4196 const sp<IBinder>& token) {
4197 for (const auto& it : mGestureMonitorsByDisplay) {
4198 const std::vector<Monitor>& monitors = it.second;
4199 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004200 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004201 return it.first;
4202 }
4203 }
4204 }
4205 return std::nullopt;
4206}
4207
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004208sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4209 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004210 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004211 }
4212
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004213 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004214 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004215 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004216 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 }
4218 }
Robert Carr4e670e52018-08-15 13:26:12 -07004219
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004220 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221}
4222
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004223void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4224 const sp<Connection>& connection, uint32_t seq,
4225 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004226 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4227 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 commandEntry->connection = connection;
4229 commandEntry->eventTime = currentTime;
4230 commandEntry->seq = seq;
4231 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004232 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233}
4234
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004235void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4236 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004238 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004240 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4241 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004243 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244}
4245
chaviw0c06c6e2019-01-09 13:27:07 -08004246void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004247 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004248 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4249 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004250 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4251 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004252 commandEntry->oldToken = oldToken;
4253 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004254 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004255}
4256
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004257void InputDispatcher::onANRLocked(nsecs_t currentTime,
4258 const sp<InputApplicationHandle>& applicationHandle,
4259 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4260 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4262 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4263 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004264 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4265 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4266 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267
4268 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004269 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 struct tm tm;
4271 localtime_r(&t, &tm);
4272 char timestr[64];
4273 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4274 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004275 mLastANRState += INDENT "ANR:\n";
4276 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004277 mLastANRState +=
4278 StringPrintf(INDENT2 "Window: %s\n",
4279 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004280 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4281 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4282 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 dumpDispatchStateLocked(mLastANRState);
4284
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004285 std::unique_ptr<CommandEntry> commandEntry =
4286 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004288 commandEntry->inputChannel =
4289 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004291 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292}
4293
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004294void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 mLock.unlock();
4296
4297 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4298
4299 mLock.lock();
4300}
4301
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004302void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303 sp<Connection> connection = commandEntry->connection;
4304
4305 if (connection->status != Connection::STATUS_ZOMBIE) {
4306 mLock.unlock();
4307
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004308 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309
4310 mLock.lock();
4311 }
4312}
4313
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004314void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004315 sp<IBinder> oldToken = commandEntry->oldToken;
4316 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004317 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004318 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004319 mLock.lock();
4320}
4321
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004322void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004323 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004324 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 mLock.unlock();
4326
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004327 nsecs_t newTimeout =
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004328 mPolicy->notifyANR(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329
4330 mLock.lock();
4331
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004332 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333}
4334
4335void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4336 CommandEntry* commandEntry) {
4337 KeyEntry* entry = commandEntry->keyEntry;
4338
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004339 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340
4341 mLock.unlock();
4342
Michael Wright2b3c3302018-03-02 17:19:13 +00004343 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004344 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004345 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004346 : nullptr;
4347 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004348 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4349 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004350 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352
4353 mLock.lock();
4354
4355 if (delay < 0) {
4356 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4357 } else if (!delay) {
4358 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4359 } else {
4360 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4361 entry->interceptKeyWakeupTime = now() + delay;
4362 }
4363 entry->release();
4364}
4365
chaviwfd6d3512019-03-25 13:23:49 -07004366void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4367 mLock.unlock();
4368 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4369 mLock.lock();
4370}
4371
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004372void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004374 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004376 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377
4378 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004379 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004380 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004381 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004383 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004384
4385 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4386 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4387 std::string msg =
4388 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4389 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4390 dispatchEntry->eventEntry->appendDescription(msg);
4391 ALOGI("%s", msg.c_str());
4392 }
4393
4394 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004395 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004396 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4397 restartEvent =
4398 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004399 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004400 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4401 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4402 handled);
4403 } else {
4404 restartEvent = false;
4405 }
4406
4407 // Dequeue the event and start the next cycle.
4408 // Note that because the lock might have been released, it is possible that the
4409 // contents of the wait queue to have been drained, so we need to double-check
4410 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004411 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4412 if (dispatchEntryIt != connection->waitQueue.end()) {
4413 dispatchEntry = *dispatchEntryIt;
4414 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004415 traceWaitQueueLength(connection);
4416 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004417 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004418 traceOutboundQueueLength(connection);
4419 } else {
4420 releaseDispatchEntry(dispatchEntry);
4421 }
4422 }
4423
4424 // Start the next dispatch cycle for this connection.
4425 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426}
4427
4428bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004429 DispatchEntry* dispatchEntry,
4430 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004431 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004432 if (!handled) {
4433 // Report the key as unhandled, since the fallback was not handled.
4434 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4435 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004436 return false;
4437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004439 // Get the fallback key state.
4440 // Clear it out after dispatching the UP.
4441 int32_t originalKeyCode = keyEntry->keyCode;
4442 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4443 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4444 connection->inputState.removeFallbackKey(originalKeyCode);
4445 }
4446
4447 if (handled || !dispatchEntry->hasForegroundTarget()) {
4448 // If the application handles the original key for which we previously
4449 // generated a fallback or if the window is not a foreground window,
4450 // then cancel the associated fallback key, if any.
4451 if (fallbackKeyCode != -1) {
4452 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004454 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004455 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4456 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4457 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004459 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004460 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461
4462 mLock.unlock();
4463
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004464 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004465 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466
4467 mLock.lock();
4468
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004469 // Cancel the fallback key.
4470 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004472 "application handled the original non-fallback key "
4473 "or is no longer a foreground target, "
4474 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475 options.keyCode = fallbackKeyCode;
4476 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004478 connection->inputState.removeFallbackKey(originalKeyCode);
4479 }
4480 } else {
4481 // If the application did not handle a non-fallback key, first check
4482 // that we are in a good state to perform unhandled key event processing
4483 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004484 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004485 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004487 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004488 "since this is not an initial down. "
4489 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4490 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004492 return false;
4493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004494
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004495 // Dispatch the unhandled key to the policy.
4496#if DEBUG_OUTBOUND_EVENT_DETAILS
4497 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004498 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4499 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004500#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004501 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004502
4503 mLock.unlock();
4504
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004505 bool fallback =
4506 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4507 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004508
4509 mLock.lock();
4510
4511 if (connection->status != Connection::STATUS_NORMAL) {
4512 connection->inputState.removeFallbackKey(originalKeyCode);
4513 return false;
4514 }
4515
4516 // Latch the fallback keycode for this key on an initial down.
4517 // The fallback keycode cannot change at any other point in the lifecycle.
4518 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004520 fallbackKeyCode = event.getKeyCode();
4521 } else {
4522 fallbackKeyCode = AKEYCODE_UNKNOWN;
4523 }
4524 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4525 }
4526
4527 ALOG_ASSERT(fallbackKeyCode != -1);
4528
4529 // Cancel the fallback key if the policy decides not to send it anymore.
4530 // We will continue to dispatch the key to the policy but we will no
4531 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004532 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4533 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004534#if DEBUG_OUTBOUND_EVENT_DETAILS
4535 if (fallback) {
4536 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004537 "as a fallback for %d, but on the DOWN it had requested "
4538 "to send %d instead. Fallback canceled.",
4539 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004540 } else {
4541 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004542 "but on the DOWN it had requested to send %d. "
4543 "Fallback canceled.",
4544 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004545 }
4546#endif
4547
4548 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4549 "canceling fallback, policy no longer desires it");
4550 options.keyCode = fallbackKeyCode;
4551 synthesizeCancelationEventsForConnectionLocked(connection, options);
4552
4553 fallback = false;
4554 fallbackKeyCode = AKEYCODE_UNKNOWN;
4555 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004556 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004557 }
4558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559
4560#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004561 {
4562 std::string msg;
4563 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4564 connection->inputState.getFallbackKeys();
4565 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004566 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004568 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004569 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004570 }
4571#endif
4572
4573 if (fallback) {
4574 // Restart the dispatch cycle using the fallback key.
4575 keyEntry->eventTime = event.getEventTime();
4576 keyEntry->deviceId = event.getDeviceId();
4577 keyEntry->source = event.getSource();
4578 keyEntry->displayId = event.getDisplayId();
4579 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4580 keyEntry->keyCode = fallbackKeyCode;
4581 keyEntry->scanCode = event.getScanCode();
4582 keyEntry->metaState = event.getMetaState();
4583 keyEntry->repeatCount = event.getRepeatCount();
4584 keyEntry->downTime = event.getDownTime();
4585 keyEntry->syntheticRepeat = false;
4586
4587#if DEBUG_OUTBOUND_EVENT_DETAILS
4588 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004589 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4590 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004591#endif
4592 return true; // restart the event
4593 } else {
4594#if DEBUG_OUTBOUND_EVENT_DETAILS
4595 ALOGD("Unhandled key event: No fallback key.");
4596#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004597
4598 // Report the key as unhandled, since there is no fallback key.
4599 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600 }
4601 }
4602 return false;
4603}
4604
4605bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004606 DispatchEntry* dispatchEntry,
4607 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608 return false;
4609}
4610
4611void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4612 mLock.unlock();
4613
4614 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4615
4616 mLock.lock();
4617}
4618
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004619KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4620 KeyEvent event;
4621 event.initialize(entry.deviceId, entry.source, entry.displayId, entry.action, entry.flags,
4622 entry.keyCode, entry.scanCode, entry.metaState, entry.repeatCount,
4623 entry.downTime, entry.eventTime);
4624 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625}
4626
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004627void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004628 int32_t injectionResult,
4629 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 // TODO Write some statistics about how long we spend waiting.
4631}
4632
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004633/**
4634 * Report the touch event latency to the statsd server.
4635 * Input events are reported for statistics if:
4636 * - This is a touchscreen event
4637 * - InputFilter is not enabled
4638 * - Event is not injected or synthesized
4639 *
4640 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4641 * from getting aggregated with the "old" data.
4642 */
4643void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4644 REQUIRES(mLock) {
4645 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4646 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4647 if (!reportForStatistics) {
4648 return;
4649 }
4650
4651 if (mTouchStatistics.shouldReport()) {
4652 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4653 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4654 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4655 mTouchStatistics.reset();
4656 }
4657 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4658 mTouchStatistics.addValue(latencyMicros);
4659}
4660
Michael Wrightd02c5b62014-02-10 15:10:22 -08004661void InputDispatcher::traceInboundQueueLengthLocked() {
4662 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004663 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004664 }
4665}
4666
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004667void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668 if (ATRACE_ENABLED()) {
4669 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004670 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004671 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004672 }
4673}
4674
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004675void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004676 if (ATRACE_ENABLED()) {
4677 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004678 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004679 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680 }
4681}
4682
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004683void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004684 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004685
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004686 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687 dumpDispatchStateLocked(dump);
4688
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004689 if (!mLastANRState.empty()) {
4690 dump += "\nInput Dispatcher State at time of last ANR:\n";
4691 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692 }
4693}
4694
4695void InputDispatcher::monitor() {
4696 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004697 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004699 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700}
4701
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004702/**
4703 * Wake up the dispatcher and wait until it processes all events and commands.
4704 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4705 * this method can be safely called from any thread, as long as you've ensured that
4706 * the work you are interested in completing has already been queued.
4707 */
4708bool InputDispatcher::waitForIdle() {
4709 /**
4710 * Timeout should represent the longest possible time that a device might spend processing
4711 * events and commands.
4712 */
4713 constexpr std::chrono::duration TIMEOUT = 100ms;
4714 std::unique_lock lock(mLock);
4715 mLooper->wake();
4716 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4717 return result == std::cv_status::no_timeout;
4718}
4719
Garfield Tane84e6f92019-08-29 17:28:41 -07004720} // namespace android::inputdispatcher