blob: 0982ea7915a68ad0993aabc491bff863f82ab126 [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>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080063#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <log/log.h>
Gang Wang342c9272020-01-13 13:15:04 -050065#include <openssl/hmac.h>
66#include <openssl/rand.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070067#include <powermanager/PowerManager.h>
68#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080069
70#define INDENT " "
71#define INDENT2 " "
72#define INDENT3 " "
73#define INDENT4 " "
74
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080075using android::base::StringPrintf;
76
Garfield Tane84e6f92019-08-29 17:28:41 -070077namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
79// Default input dispatching timeout if there is no focused application or paused window
80// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000081constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Amount of time to allow for all pending events to be processed when an app switch
84// key is on the way. This is used to preempt input dispatch and drop input events
85// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000086constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow for an event to be dispatched (measured since its eventTime)
89// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92// Amount of time to allow touch events to be streamed out to a connection before requiring
93// that the first event be finished. This value extends the ANR timeout by the specified
94// amount. For example, if streaming is allowed to get ahead by one second relative to the
95// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000096constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
98// 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 +000099constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
100
101// Log a warning when an interception call takes longer than this to process.
102constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
104// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107static inline nsecs_t now() {
108 return systemTime(SYSTEM_TIME_MONOTONIC);
109}
110
111static inline const char* toString(bool value) {
112 return value ? "true" : "false";
113}
114
115static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700116 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
117 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118}
119
120static bool isValidKeyAction(int32_t action) {
121 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700122 case AKEY_EVENT_ACTION_DOWN:
123 case AKEY_EVENT_ACTION_UP:
124 return true;
125 default:
126 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127 }
128}
129
130static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 ALOGE("Key event has invalid action code 0x%x", action);
133 return false;
134 }
135 return true;
136}
137
Michael Wright7b159c92015-05-14 14:48:03 +0100138static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 case AMOTION_EVENT_ACTION_DOWN:
141 case AMOTION_EVENT_ACTION_UP:
142 case AMOTION_EVENT_ACTION_CANCEL:
143 case AMOTION_EVENT_ACTION_MOVE:
144 case AMOTION_EVENT_ACTION_OUTSIDE:
145 case AMOTION_EVENT_ACTION_HOVER_ENTER:
146 case AMOTION_EVENT_ACTION_HOVER_MOVE:
147 case AMOTION_EVENT_ACTION_HOVER_EXIT:
148 case AMOTION_EVENT_ACTION_SCROLL:
149 return true;
150 case AMOTION_EVENT_ACTION_POINTER_DOWN:
151 case AMOTION_EVENT_ACTION_POINTER_UP: {
152 int32_t index = getMotionEventActionPointerIndex(action);
153 return index >= 0 && index < pointerCount;
154 }
155 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
156 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
157 return actionButton != 0;
158 default:
159 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160 }
161}
162
Michael Wright7b159c92015-05-14 14:48:03 +0100163static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 const PointerProperties* pointerProperties) {
165 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 ALOGE("Motion event has invalid action code 0x%x", action);
167 return false;
168 }
169 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000170 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700171 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 return false;
173 }
174 BitSet32 pointerIdBits;
175 for (size_t i = 0; i < pointerCount; i++) {
176 int32_t id = pointerProperties[i].id;
177 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
179 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 return false;
181 }
182 if (pointerIdBits.hasBit(id)) {
183 ALOGE("Motion event has duplicate pointer id %d", id);
184 return false;
185 }
186 pointerIdBits.markBit(id);
187 }
188 return true;
189}
190
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800191static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800193 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 return;
195 }
196
197 bool first = true;
198 Region::const_iterator cur = region.begin();
199 Region::const_iterator const tail = region.end();
200 while (cur != tail) {
201 if (first) {
202 first = false;
203 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800204 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800206 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 cur++;
208 }
209}
210
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700211/**
212 * Find the entry in std::unordered_map by key, and return it.
213 * If the entry is not found, return a default constructed entry.
214 *
215 * Useful when the entries are vectors, since an empty vector will be returned
216 * if the entry is not found.
217 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
218 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700219template <typename K, typename V>
220static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700221 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700222 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800223}
224
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700225/**
226 * Find the entry in std::unordered_map by value, and remove it.
227 * If more than one entry has the same value, then all matching
228 * key-value pairs will be removed.
229 *
230 * Return true if at least one value has been removed.
231 */
232template <typename K, typename V>
233static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
234 bool removed = false;
235 for (auto it = map.begin(); it != map.end();) {
236 if (it->second == value) {
237 it = map.erase(it);
238 removed = true;
239 } else {
240 it++;
241 }
242 }
243 return removed;
244}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245
chaviwaf87b3e2019-10-01 16:59:28 -0700246static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
247 if (first == second) {
248 return true;
249 }
250
251 if (first == nullptr || second == nullptr) {
252 return false;
253 }
254
255 return first->getToken() == second->getToken();
256}
257
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800258static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
259 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
260}
261
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000262static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
263 EventEntry* eventEntry,
264 int32_t inputTargetFlags) {
265 if (inputTarget.useDefaultPointerInfo()) {
266 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
267 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
268 inputTargetFlags, pointerInfo.xOffset,
269 pointerInfo.yOffset, inputTarget.globalScaleFactor,
270 pointerInfo.windowXScale, pointerInfo.windowYScale);
271 }
272
273 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
274 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
275
276 PointerCoords pointerCoords[motionEntry.pointerCount];
277
278 // Use the first pointer information to normalize all other pointers. This could be any pointer
279 // as long as all other pointers are normalized to the same value and the final DispatchEntry
280 // uses the offset and scale for the normalized pointer.
281 const PointerInfo& firstPointerInfo =
282 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
283
284 // Iterate through all pointers in the event to normalize against the first.
285 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
286 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
287 uint32_t pointerId = uint32_t(pointerProperties.id);
288 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
289
290 // The scale factor is the ratio of the current pointers scale to the normalized scale.
291 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
292 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
293
294 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
295 // First apply the current pointers offset to set the window at 0,0
296 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
297 // Next scale the coordinates.
298 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
299 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
300 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
301 -firstPointerInfo.yOffset);
302 }
303
304 MotionEntry* combinedMotionEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800305 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000306 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
307 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
308 motionEntry.metaState, motionEntry.buttonState,
309 motionEntry.classification, motionEntry.edgeFlags,
310 motionEntry.xPrecision, motionEntry.yPrecision,
311 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
312 motionEntry.downTime, motionEntry.pointerCount,
313 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
314 0 /* yOffset */);
315
316 if (motionEntry.injectionState) {
317 combinedMotionEntry->injectionState = motionEntry.injectionState;
318 combinedMotionEntry->injectionState->refCount += 1;
319 }
320
321 std::unique_ptr<DispatchEntry> dispatchEntry =
322 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
323 inputTargetFlags, firstPointerInfo.xOffset,
324 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
325 firstPointerInfo.windowXScale,
326 firstPointerInfo.windowYScale);
327 combinedMotionEntry->release();
328 return dispatchEntry;
329}
330
Gang Wang342c9272020-01-13 13:15:04 -0500331static std::array<uint8_t, 128> getRandomKey() {
332 std::array<uint8_t, 128> key;
333 if (RAND_bytes(key.data(), key.size()) != 1) {
334 LOG_ALWAYS_FATAL("Can't generate HMAC key");
335 }
336 return key;
337}
338
339// --- HmacKeyManager ---
340
341HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
342
343std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
344 size_t size;
345 switch (event.type) {
346 case VerifiedInputEvent::Type::KEY: {
347 size = sizeof(VerifiedKeyEvent);
348 break;
349 }
350 case VerifiedInputEvent::Type::MOTION: {
351 size = sizeof(VerifiedMotionEvent);
352 break;
353 }
354 }
355 std::vector<uint8_t> data;
356 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
357 data.assign(start, start + size);
358 return sign(data);
359}
360
361std::array<uint8_t, 32> HmacKeyManager::sign(const std::vector<uint8_t>& data) const {
362 // SHA256 always generates 32-bytes result
363 std::array<uint8_t, 32> hash;
364 unsigned int hashLen = 0;
365 uint8_t* result = HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data.data(), data.size(),
366 hash.data(), &hashLen);
367 if (result == nullptr) {
368 ALOGE("Could not sign the data using HMAC");
369 return INVALID_HMAC;
370 }
371
372 if (hashLen != hash.size()) {
373 ALOGE("HMAC-SHA256 has unexpected length");
374 return INVALID_HMAC;
375 }
376
377 return hash;
378}
379
Michael Wrightd02c5b62014-02-10 15:10:22 -0800380// --- InputDispatcher ---
381
Garfield Tan00f511d2019-06-12 16:55:40 -0700382InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
383 : mPolicy(policy),
384 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700385 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tan1c7bc862020-01-28 13:24:04 -0800386 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700387 mAppSwitchSawKeyDown(false),
388 mAppSwitchDueTime(LONG_LONG_MAX),
389 mNextUnblockedEvent(nullptr),
390 mDispatchEnabled(false),
391 mDispatchFrozen(false),
392 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800393 // mInTouchMode will be initialized by the WindowManager to the default device config.
394 // To avoid leaking stack in case that call never comes, and for tests,
395 // initialize it here anyways.
396 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700397 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
398 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800399 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800400 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800401
Yi Kong9b14ac62018-07-17 13:48:38 -0700402 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403
404 policy->getDispatcherConfiguration(&mConfig);
405}
406
407InputDispatcher::~InputDispatcher() {
408 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800409 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800410
411 resetKeyRepeatLocked();
412 releasePendingEventLocked();
413 drainInboundQueueLocked();
414 }
415
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700416 while (!mConnectionsByFd.empty()) {
417 sp<Connection> connection = mConnectionsByFd.begin()->second;
418 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419 }
420}
421
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700422status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700423 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700424 return ALREADY_EXISTS;
425 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700426 mThread = std::make_unique<InputThread>(
427 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
428 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700429}
430
431status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700432 if (mThread && mThread->isCallingThread()) {
433 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700434 return INVALID_OPERATION;
435 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700436 mThread.reset();
437 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700438}
439
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440void InputDispatcher::dispatchOnce() {
441 nsecs_t nextWakeupTime = LONG_LONG_MAX;
442 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800443 std::scoped_lock _l(mLock);
444 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800445
446 // Run a dispatch loop if there are no pending commands.
447 // The dispatch loop might enqueue commands to run afterwards.
448 if (!haveCommandsLocked()) {
449 dispatchOnceInnerLocked(&nextWakeupTime);
450 }
451
452 // Run all pending commands if there are any.
453 // If any commands were run then force the next poll to wake up immediately.
454 if (runCommandsLockedInterruptible()) {
455 nextWakeupTime = LONG_LONG_MIN;
456 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800457
458 // We are about to enter an infinitely long sleep, because we have no commands or
459 // pending or queued events
460 if (nextWakeupTime == LONG_LONG_MAX) {
461 mDispatcherEnteredIdle.notify_all();
462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463 } // release lock
464
465 // Wait for callback or timeout or wake. (make sure we round up, not down)
466 nsecs_t currentTime = now();
467 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
468 mLooper->pollOnce(timeoutMillis);
469}
470
471void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
472 nsecs_t currentTime = now();
473
Jeff Browndc5992e2014-04-11 01:27:26 -0700474 // Reset the key repeat timer whenever normal dispatch is suspended while the
475 // device is in a non-interactive state. This is to ensure that we abort a key
476 // repeat if the device is just coming out of sleep.
477 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478 resetKeyRepeatLocked();
479 }
480
481 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
482 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100483 if (DEBUG_FOCUS) {
484 ALOGD("Dispatch frozen. Waiting some more.");
485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800486 return;
487 }
488
489 // Optimize latency of app switches.
490 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
491 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
492 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
493 if (mAppSwitchDueTime < *nextWakeupTime) {
494 *nextWakeupTime = mAppSwitchDueTime;
495 }
496
497 // Ready to start a new event.
498 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700499 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700500 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800501 if (isAppSwitchDue) {
502 // The inbound queue is empty so the app switch key we were waiting
503 // for will never arrive. Stop waiting for it.
504 resetPendingAppSwitchLocked(false);
505 isAppSwitchDue = false;
506 }
507
508 // Synthesize a key repeat if appropriate.
509 if (mKeyRepeatState.lastKeyEntry) {
510 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
511 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
512 } else {
513 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
514 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
515 }
516 }
517 }
518
519 // Nothing to do if there is no pending event.
520 if (!mPendingEvent) {
521 return;
522 }
523 } else {
524 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700525 mPendingEvent = mInboundQueue.front();
526 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 traceInboundQueueLengthLocked();
528 }
529
530 // Poke user activity for this event.
531 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700532 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533 }
534
535 // Get ready to dispatch the event.
536 resetANRTimeoutsLocked();
537 }
538
539 // Now we have an event to dispatch.
540 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700541 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800542 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700543 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700545 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800546 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700547 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548 }
549
550 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700551 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 }
553
554 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700555 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700556 ConfigurationChangedEntry* typedEntry =
557 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
558 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700559 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700560 break;
561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700563 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700564 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
565 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700566 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700567 break;
568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800569
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100570 case EventEntry::Type::FOCUS: {
571 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
572 dispatchFocusLocked(currentTime, typedEntry);
573 done = true;
574 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
575 break;
576 }
577
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700578 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700579 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
580 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700581 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700582 resetPendingAppSwitchLocked(true);
583 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700584 } else if (dropReason == DropReason::NOT_DROPPED) {
585 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700586 }
587 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700588 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700589 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700590 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700591 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
592 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700593 }
594 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
595 break;
596 }
597
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700598 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700599 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700600 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
601 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700603 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700604 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700605 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700606 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
607 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700608 }
609 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
610 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612 }
613
614 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700615 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700616 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 }
Michael Wright3a981722015-06-10 15:26:13 +0100618 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800619
620 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700621 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 }
623}
624
625bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700626 bool needWake = mInboundQueue.empty();
627 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628 traceInboundQueueLengthLocked();
629
630 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700631 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700632 // Optimize app switch latency.
633 // If the application takes too long to catch up then we drop all events preceding
634 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700635 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700636 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700637 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700638 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700639 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700640 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800641#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700642 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800643#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700644 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700645 mAppSwitchSawKeyDown = false;
646 needWake = true;
647 }
648 }
649 }
650 break;
651 }
652
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700653 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700654 // Optimize case where the current application is unresponsive and the user
655 // decides to touch a window in a different application.
656 // If the application takes too long to catch up then we drop all events preceding
657 // the touch into the other window.
658 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
659 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
660 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
661 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
662 mInputTargetWaitApplicationToken != nullptr) {
663 int32_t displayId = motionEntry->displayId;
664 int32_t x =
665 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
666 int32_t y =
667 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
668 sp<InputWindowHandle> touchedWindowHandle =
669 findTouchedWindowAtLocked(displayId, x, y);
670 if (touchedWindowHandle != nullptr &&
671 touchedWindowHandle->getApplicationToken() !=
672 mInputTargetWaitApplicationToken) {
673 // User touched a different application than the one we are waiting on.
674 // Flag the event, and start pruning the input queue.
675 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 needWake = true;
677 }
678 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700679 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700681 case EventEntry::Type::CONFIGURATION_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100682 case EventEntry::Type::DEVICE_RESET:
683 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700684 // nothing to do
685 break;
686 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800687 }
688
689 return needWake;
690}
691
692void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
693 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700694 mRecentQueue.push_back(entry);
695 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
696 mRecentQueue.front()->release();
697 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
699}
700
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700701sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
702 int32_t y, bool addOutsideTargets,
703 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800705 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
706 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 const InputWindowInfo* windowInfo = windowHandle->getInfo();
708 if (windowInfo->displayId == displayId) {
709 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710
711 if (windowInfo->visible) {
712 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700713 bool isTouchModal = (flags &
714 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
715 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800717 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700718 if (portalToDisplayId != ADISPLAY_ID_NONE &&
719 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800720 if (addPortalWindows) {
721 // For the monitoring channels of the display.
722 mTempTouchState.addPortalWindow(windowHandle);
723 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700724 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
725 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800726 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727 // Found window.
728 return windowHandle;
729 }
730 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800731
732 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700733 mTempTouchState.addOrUpdateWindow(windowHandle,
734 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
735 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 }
739 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700740 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741}
742
Garfield Tane84e6f92019-08-29 17:28:41 -0700743std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000744 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
745 std::vector<TouchedMonitor> touchedMonitors;
746
747 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
748 addGestureMonitors(monitors, touchedMonitors);
749 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
750 const InputWindowInfo* windowInfo = portalWindow->getInfo();
751 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700752 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
753 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000754 }
755 return touchedMonitors;
756}
757
758void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700759 std::vector<TouchedMonitor>& outTouchedMonitors,
760 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000761 if (monitors.empty()) {
762 return;
763 }
764 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
765 for (const Monitor& monitor : monitors) {
766 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
767 }
768}
769
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700770void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771 const char* reason;
772 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700773 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700775 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 reason = "inbound event was dropped because the policy consumed it";
778 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700779 case DropReason::DISABLED:
780 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700781 ALOGI("Dropped event because input dispatch is disabled.");
782 }
783 reason = "inbound event was dropped because input dispatch is disabled";
784 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700785 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700786 ALOGI("Dropped event because of pending overdue app switch.");
787 reason = "inbound event was dropped because of pending overdue app switch";
788 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700789 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700790 ALOGI("Dropped event because the current application is not responding and the user "
791 "has started interacting with a different application.");
792 reason = "inbound event was dropped because the current application is not responding "
793 "and the user has started interacting with a different application";
794 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700795 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700796 ALOGI("Dropped event because it is stale.");
797 reason = "inbound event was dropped because it is stale";
798 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700799 case DropReason::NOT_DROPPED: {
800 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700801 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 }
804
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700805 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700806 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
808 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700811 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700812 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
813 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700814 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
815 synthesizeCancelationEventsForAllConnectionsLocked(options);
816 } else {
817 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
818 synthesizeCancelationEventsForAllConnectionsLocked(options);
819 }
820 break;
821 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100822 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700823 case EventEntry::Type::CONFIGURATION_CHANGED:
824 case EventEntry::Type::DEVICE_RESET: {
825 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
826 break;
827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800828 }
829}
830
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800831static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700832 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
833 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834}
835
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700836bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
837 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
838 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
839 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840}
841
842bool InputDispatcher::isAppSwitchPendingLocked() {
843 return mAppSwitchDueTime != LONG_LONG_MAX;
844}
845
846void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
847 mAppSwitchDueTime = LONG_LONG_MAX;
848
849#if DEBUG_APP_SWITCH
850 if (handled) {
851 ALOGD("App switch has arrived.");
852 } else {
853 ALOGD("App switch was abandoned.");
854 }
855#endif
856}
857
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700859 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860}
861
862bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700863 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 return false;
865 }
866
867 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700868 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700869 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700871 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872
873 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700874 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 return true;
876}
877
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700878void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
879 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880}
881
882void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700883 while (!mInboundQueue.empty()) {
884 EventEntry* entry = mInboundQueue.front();
885 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 releaseInboundEventLocked(entry);
887 }
888 traceInboundQueueLengthLocked();
889}
890
891void InputDispatcher::releasePendingEventLocked() {
892 if (mPendingEvent) {
893 resetANRTimeoutsLocked();
894 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700895 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
897}
898
899void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
900 InjectionState* injectionState = entry->injectionState;
901 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
902#if DEBUG_DISPATCH_CYCLE
903 ALOGD("Injected inbound event was dropped.");
904#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800905 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 }
907 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700908 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 }
910 addRecentEventLocked(entry);
911 entry->release();
912}
913
914void InputDispatcher::resetKeyRepeatLocked() {
915 if (mKeyRepeatState.lastKeyEntry) {
916 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700917 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800918 }
919}
920
Garfield Tane84e6f92019-08-29 17:28:41 -0700921KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
923
924 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700925 uint32_t policyFlags = entry->policyFlags &
926 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 if (entry->refCount == 1) {
928 entry->recycle();
Garfield Tan1c7bc862020-01-28 13:24:04 -0800929 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 entry->eventTime = currentTime;
931 entry->policyFlags = policyFlags;
932 entry->repeatCount += 1;
933 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700934 KeyEntry* newEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -0800935 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800936 entry->displayId, policyFlags, entry->action, entry->flags,
937 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700938 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939
940 mKeyRepeatState.lastKeyEntry = newEntry;
941 entry->release();
942
943 entry = newEntry;
944 }
945 entry->syntheticRepeat = true;
946
947 // Increment reference count since we keep a reference to the event in
948 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
949 entry->refCount += 1;
950
951 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
952 return entry;
953}
954
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700955bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
956 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700958 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959#endif
960
961 // Reset key repeating in case a keyboard device was added or removed or something.
962 resetKeyRepeatLocked();
963
964 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700965 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
966 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700968 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 return true;
970}
971
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700972bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700974 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700975 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976#endif
977
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700978 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 options.deviceId = entry->deviceId;
980 synthesizeCancelationEventsForAllConnectionsLocked(options);
981 return true;
982}
983
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100984void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
985 FocusEntry* focusEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -0800986 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100987 enqueueInboundEventLocked(focusEntry);
988}
989
990void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
991 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
992 if (channel == nullptr) {
993 return; // Window has gone away
994 }
995 InputTarget target;
996 target.inputChannel = channel;
997 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
998 entry->dispatchInProgress = true;
999
1000 dispatchEventLocked(currentTime, entry, {target});
1001}
1002
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001004 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001006 if (!entry->dispatchInProgress) {
1007 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1008 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1009 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1010 if (mKeyRepeatState.lastKeyEntry &&
1011 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 // We have seen two identical key downs in a row which indicates that the device
1013 // driver is automatically generating key repeats itself. We take note of the
1014 // repeat here, but we disable our own next key repeat timer since it is clear that
1015 // we will not need to synthesize key repeats ourselves.
1016 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1017 resetKeyRepeatLocked();
1018 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1019 } else {
1020 // Not a repeat. Save key down state in case we do see a repeat later.
1021 resetKeyRepeatLocked();
1022 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1023 }
1024 mKeyRepeatState.lastKeyEntry = entry;
1025 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001026 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 resetKeyRepeatLocked();
1028 }
1029
1030 if (entry->repeatCount == 1) {
1031 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1032 } else {
1033 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1034 }
1035
1036 entry->dispatchInProgress = true;
1037
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001038 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
1040
1041 // Handle case where the policy asked us to try again later last time.
1042 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1043 if (currentTime < entry->interceptKeyWakeupTime) {
1044 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1045 *nextWakeupTime = entry->interceptKeyWakeupTime;
1046 }
1047 return false; // wait until next wakeup
1048 }
1049 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1050 entry->interceptKeyWakeupTime = 0;
1051 }
1052
1053 // Give the policy a chance to intercept the key.
1054 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1055 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001056 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001057 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001058 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001059 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001060 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001061 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 }
1063 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001064 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 entry->refCount += 1;
1066 return false; // wait for the command to run
1067 } else {
1068 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1069 }
1070 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001071 if (*dropReason == DropReason::NOT_DROPPED) {
1072 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
1074 }
1075
1076 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001077 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001081 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 return true;
1083 }
1084
1085 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001086 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001087 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001088 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1090 return false;
1091 }
1092
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001093 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1095 return true;
1096 }
1097
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001098 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001099 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100
1101 // Dispatch the key.
1102 dispatchEventLocked(currentTime, entry, inputTargets);
1103 return true;
1104}
1105
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001106void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001108 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001109 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1110 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001111 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1112 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1113 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114#endif
1115}
1116
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001117bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1118 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001119 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001121 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 entry->dispatchInProgress = true;
1123
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001124 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 }
1126
1127 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001128 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001130 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001131 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 return true;
1133 }
1134
1135 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1136
1137 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001138 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139
1140 bool conflictingPointerActions = false;
1141 int32_t injectionResult;
1142 if (isPointerEvent) {
1143 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001144 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001145 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001146 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 } else {
1148 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001149 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001150 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 }
1152 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1153 return false;
1154 }
1155
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001156 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001158 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001159 CancelationOptions::Mode mode(isPointerEvent
1160 ? CancelationOptions::CANCEL_POINTER_EVENTS
1161 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001162 CancelationOptions options(mode, "input event injection failed");
1163 synthesizeCancelationEventsForMonitorsLocked(options);
1164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165 return true;
1166 }
1167
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001168 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001169 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001171 if (isPointerEvent) {
1172 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
1173 if (stateIndex >= 0) {
1174 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001175 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001176 // The event has gone through these portal windows, so we add monitoring targets of
1177 // the corresponding displays as well.
1178 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001179 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001180 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001181 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001182 }
1183 }
1184 }
1185 }
1186
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 // Dispatch the motion.
1188 if (conflictingPointerActions) {
1189 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001190 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 synthesizeCancelationEventsForAllConnectionsLocked(options);
1192 }
1193 dispatchEventLocked(currentTime, entry, inputTargets);
1194 return true;
1195}
1196
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001197void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001199 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001200 ", policyFlags=0x%x, "
1201 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1202 "metaState=0x%x, buttonState=0x%x,"
1203 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001204 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1205 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1206 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001208 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 "x=%f, y=%f, pressure=%f, size=%f, "
1211 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1212 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001213 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1214 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1215 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1216 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1217 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1218 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1219 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1220 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1221 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1222 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 }
1224#endif
1225}
1226
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001227void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1228 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001229 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230#if DEBUG_DISPATCH_CYCLE
1231 ALOGD("dispatchEventToCurrentInputTargets");
1232#endif
1233
1234 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1235
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001236 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001238 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001239 sp<Connection> connection =
1240 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001241 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001242 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001244 if (DEBUG_FOCUS) {
1245 ALOGD("Dropping event delivery to target with channel '%s' because it "
1246 "is no longer registered with the input dispatcher.",
1247 inputTarget.inputChannel->getName().c_str());
1248 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 }
1250 }
1251}
1252
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001253int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001254 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001256 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001257 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001259 if (DEBUG_FOCUS) {
1260 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1263 mInputTargetWaitStartTime = currentTime;
1264 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1265 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001266 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 }
1268 } else {
1269 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001270 if (DEBUG_FOCUS) {
1271 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
1272 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001275 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001277 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001278 timeout =
1279 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 } else {
1281 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1282 }
1283
1284 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1285 mInputTargetWaitStartTime = currentTime;
1286 mInputTargetWaitTimeoutTime = currentTime + timeout;
1287 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001288 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289
Yi Kong9b14ac62018-07-17 13:48:38 -07001290 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001291 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 }
Robert Carr740167f2018-10-11 19:03:41 -07001293 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1294 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 }
1296 }
1297 }
1298
1299 if (mInputTargetWaitTimeoutExpired) {
1300 return INPUT_EVENT_INJECTION_TIMED_OUT;
1301 }
1302
1303 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001304 onANRLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001305 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306
1307 // Force poll loop to wake up immediately on next iteration once we get the
1308 // ANR response back from the policy.
1309 *nextWakeupTime = LONG_LONG_MIN;
1310 return INPUT_EVENT_INJECTION_PENDING;
1311 } else {
1312 // Force poll loop to wake up when timeout is due.
1313 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1314 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1315 }
1316 return INPUT_EVENT_INJECTION_PENDING;
1317 }
1318}
1319
Robert Carr803535b2018-08-02 16:38:15 -07001320void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1321 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1322 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1323 state.removeWindowByToken(token);
1324 }
1325}
1326
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001327void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001328 nsecs_t newTimeout, const sp<IBinder>& inputConnectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 if (newTimeout > 0) {
1330 // Extend the timeout.
1331 mInputTargetWaitTimeoutTime = now() + newTimeout;
1332 } else {
1333 // Give up.
1334 mInputTargetWaitTimeoutExpired = true;
1335
1336 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001337 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001338 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001339 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001341 if (connection->status == Connection::STATUS_NORMAL) {
1342 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1343 "application not responding");
1344 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 }
1346 }
1347 }
1348}
1349
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001350nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1352 return currentTime - mInputTargetWaitStartTime;
1353 }
1354 return 0;
1355}
1356
1357void InputDispatcher::resetANRTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001358 if (DEBUG_FOCUS) {
1359 ALOGD("Resetting ANR timeouts.");
1360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361
1362 // Reset input target wait timeout.
1363 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001364 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365}
1366
Tiger Huang721e26f2018-07-24 22:26:19 +08001367/**
1368 * Get the display id that the given event should go to. If this event specifies a valid display id,
1369 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1370 * Focused display is the display that the user most recently interacted with.
1371 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001372int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001373 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001374 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001375 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001376 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1377 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001378 break;
1379 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001380 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001381 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1382 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001383 break;
1384 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001385 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001386 case EventEntry::Type::CONFIGURATION_CHANGED:
1387 case EventEntry::Type::DEVICE_RESET: {
1388 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001389 return ADISPLAY_ID_NONE;
1390 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001391 }
1392 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1393}
1394
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001396 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001397 std::vector<InputTarget>& inputTargets,
1398 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001400 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401
Tiger Huang721e26f2018-07-24 22:26:19 +08001402 int32_t displayId = getTargetDisplayId(entry);
1403 sp<InputWindowHandle> focusedWindowHandle =
1404 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1405 sp<InputApplicationHandle> focusedApplicationHandle =
1406 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1407
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 // If there is no currently focused window and no focused application
1409 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001410 if (focusedWindowHandle == nullptr) {
1411 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001412 injectionResult =
1413 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1414 nullptr, nextWakeupTime,
1415 "Waiting because no window has focus but there is "
1416 "a focused application that may eventually add a "
1417 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001418 goto Unresponsive;
1419 }
1420
Arthur Hung3b413f22018-10-26 18:05:34 +08001421 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001422 "%" PRId32 ".",
1423 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1425 goto Failed;
1426 }
1427
1428 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001429 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1431 goto Failed;
1432 }
1433
Jeff Brownffb49772014-10-10 19:01:34 -07001434 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001435 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001436 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001437 injectionResult =
1438 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1439 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440 goto Unresponsive;
1441 }
1442
1443 // Success! Output targets.
1444 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001445 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001446 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1447 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448
1449 // Done.
1450Failed:
1451Unresponsive:
1452 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001453 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001454 if (DEBUG_FOCUS) {
1455 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1456 "timeSpentWaitingForApplication=%0.1fms",
1457 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 return injectionResult;
1460}
1461
1462int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001463 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001464 std::vector<InputTarget>& inputTargets,
1465 nsecs_t* nextWakeupTime,
1466 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001467 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 enum InjectionPermission {
1469 INJECTION_PERMISSION_UNKNOWN,
1470 INJECTION_PERMISSION_GRANTED,
1471 INJECTION_PERMISSION_DENIED
1472 };
1473
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 // For security reasons, we defer updating the touch state until we are sure that
1475 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001476 int32_t displayId = entry.displayId;
1477 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1479
1480 // Update the touch state as needed based on the properties of the touch event.
1481 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1482 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1483 sp<InputWindowHandle> newHoverWindowHandle;
1484
Jeff Brownf086ddb2014-02-11 14:28:48 -08001485 // Copy current touch state into mTempTouchState.
1486 // This state is always reset at the end of this function, so if we don't find state
1487 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001488 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001489 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1490 if (oldStateIndex >= 0) {
1491 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1492 mTempTouchState.copyFrom(*oldState);
1493 }
1494
1495 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001496 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001497 (mTempTouchState.deviceId != entry.deviceId || mTempTouchState.source != entry.source ||
1498 mTempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001499 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1500 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1501 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1502 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1503 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001504 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 bool wrongDevice = false;
1506 if (newGesture) {
1507 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001508 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001509 if (DEBUG_FOCUS) {
1510 ALOGD("Dropping event because a pointer for a different device is already down "
1511 "in display %" PRId32,
1512 displayId);
1513 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001514 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1516 switchedDevice = false;
1517 wrongDevice = true;
1518 goto Failed;
1519 }
1520 mTempTouchState.reset();
1521 mTempTouchState.down = down;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001522 mTempTouchState.deviceId = entry.deviceId;
1523 mTempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 mTempTouchState.displayId = displayId;
1525 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001526 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001527 if (DEBUG_FOCUS) {
1528 ALOGI("Dropping move event because a pointer for a different device is already active "
1529 "in display %" PRId32,
1530 displayId);
1531 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001532 // TODO: test multiple simultaneous input streams.
1533 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1534 switchedDevice = false;
1535 wrongDevice = true;
1536 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 }
1538
1539 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1540 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1541
Garfield Tan00f511d2019-06-12 16:55:40 -07001542 int32_t x;
1543 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001545 // Always dispatch mouse events to cursor position.
1546 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001547 x = int32_t(entry.xCursorPosition);
1548 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001549 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001550 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1551 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001552 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001553 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001554 sp<InputWindowHandle> newTouchedWindowHandle =
1555 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1556 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001557
1558 std::vector<TouchedMonitor> newGestureMonitors = isDown
1559 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1560 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001563 if (newTouchedWindowHandle != nullptr &&
1564 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001565 // New window supports splitting, but we should never split mouse events.
1566 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 } else if (isSplit) {
1568 // New window does not support splitting but we have already split events.
1569 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001570 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 }
1572
1573 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001574 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 // Try to assign the pointer to the first foreground window we find, if there is one.
1576 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001577 }
1578
1579 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1580 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001581 "(%d, %d) in display %" PRId32 ".",
1582 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001583 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1584 goto Failed;
1585 }
1586
1587 if (newTouchedWindowHandle != nullptr) {
1588 // Set target flags.
1589 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1590 if (isSplit) {
1591 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001593 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1594 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1595 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1596 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1597 }
1598
1599 // Update hover state.
1600 if (isHoverAction) {
1601 newHoverWindowHandle = newTouchedWindowHandle;
1602 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1603 newHoverWindowHandle = mLastHoverWindowHandle;
1604 }
1605
1606 // Update the temporary touch state.
1607 BitSet32 pointerIds;
1608 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001609 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001610 pointerIds.markBit(pointerId);
1611 }
1612 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 }
1614
Michael Wright3dd60e22019-03-27 22:06:44 +00001615 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 } else {
1617 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1618
1619 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001620 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001621 if (DEBUG_FOCUS) {
1622 ALOGD("Dropping event because the pointer is not down or we previously "
1623 "dropped the pointer down event in display %" PRId32,
1624 displayId);
1625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1627 goto Failed;
1628 }
1629
1630 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001631 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001632 mTempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001633 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1634 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635
1636 sp<InputWindowHandle> oldTouchedWindowHandle =
1637 mTempTouchState.getFirstForegroundWindowHandle();
1638 sp<InputWindowHandle> newTouchedWindowHandle =
1639 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001640 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1641 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001642 if (DEBUG_FOCUS) {
1643 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1644 oldTouchedWindowHandle->getName().c_str(),
1645 newTouchedWindowHandle->getName().c_str(), displayId);
1646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 // Make a slippery exit from the old window.
1648 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001649 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1650 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651
1652 // Make a slippery entrance into the new window.
1653 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1654 isSplit = true;
1655 }
1656
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001657 int32_t targetFlags =
1658 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 if (isSplit) {
1660 targetFlags |= InputTarget::FLAG_SPLIT;
1661 }
1662 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1663 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1664 }
1665
1666 BitSet32 pointerIds;
1667 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001668 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 }
1670 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1671 }
1672 }
1673 }
1674
1675 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1676 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001677 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678#if DEBUG_HOVER
1679 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001680 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681#endif
1682 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001683 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1684 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 }
1686
1687 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001688 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689#if DEBUG_HOVER
1690 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001691 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692#endif
1693 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001694 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1695 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 }
1697 }
1698
1699 // Check permission to inject into all touched foreground windows and ensure there
1700 // is at least one touched foreground window.
1701 {
1702 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001703 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1705 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001706 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1708 injectionPermission = INJECTION_PERMISSION_DENIED;
1709 goto Failed;
1710 }
1711 }
1712 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001713 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1714 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001715 if (DEBUG_FOCUS) {
1716 ALOGD("Dropping event because there is no touched foreground window in display "
1717 "%" PRId32 " or gesture monitor to receive it.",
1718 displayId);
1719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1721 goto Failed;
1722 }
1723
1724 // Permission granted to injection into all touched foreground windows.
1725 injectionPermission = INJECTION_PERMISSION_GRANTED;
1726 }
1727
1728 // Check whether windows listening for outside touches are owned by the same UID. If it is
1729 // set the policy flag that we will not reveal coordinate information to this window.
1730 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1731 sp<InputWindowHandle> foregroundWindowHandle =
1732 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001733 if (foregroundWindowHandle) {
1734 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1735 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1736 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1737 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1738 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1739 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001740 InputTarget::FLAG_ZERO_COORDS,
1741 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001742 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 }
1744 }
1745 }
1746 }
1747
1748 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001749 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001751 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001752 std::string reason =
1753 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1754 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001755 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001756 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1757 touchedWindow.windowHandle,
1758 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 goto Unresponsive;
1760 }
1761 }
1762 }
1763
1764 // If this is the first pointer going down and the touched window has a wallpaper
1765 // then also add the touched wallpaper windows so they are locked in for the duration
1766 // of the touch gesture.
1767 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1768 // engine only supports touch events. We would need to add a mechanism similar
1769 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1770 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1771 sp<InputWindowHandle> foregroundWindowHandle =
1772 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001773 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001774 const std::vector<sp<InputWindowHandle>> windowHandles =
1775 getWindowHandlesLocked(displayId);
1776 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001778 if (info->displayId == displayId &&
1779 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1780 mTempTouchState
1781 .addOrUpdateWindow(windowHandle,
1782 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1783 InputTarget::
1784 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1785 InputTarget::FLAG_DISPATCH_AS_IS,
1786 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 }
1788 }
1789 }
1790 }
1791
1792 // Success! Output targets.
1793 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1794
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001795 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001797 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 }
1799
Michael Wright3dd60e22019-03-27 22:06:44 +00001800 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1801 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001802 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001803 }
1804
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805 // Drop the outside or hover touch windows since we will not care about them
1806 // in the next iteration.
1807 mTempTouchState.filterNonAsIsTouchWindows();
1808
1809Failed:
1810 // Check injection permission once and for all.
1811 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001812 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 injectionPermission = INJECTION_PERMISSION_GRANTED;
1814 } else {
1815 injectionPermission = INJECTION_PERMISSION_DENIED;
1816 }
1817 }
1818
1819 // Update final pieces of touch state if the injector had permission.
1820 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1821 if (!wrongDevice) {
1822 if (switchedDevice) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001823 if (DEBUG_FOCUS) {
1824 ALOGD("Conflicting pointer actions: Switched to a different device.");
1825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 *outConflictingPointerActions = true;
1827 }
1828
1829 if (isHoverAction) {
1830 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001831 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001832 if (DEBUG_FOCUS) {
1833 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1834 "down.");
1835 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 *outConflictingPointerActions = true;
1837 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001838 mTempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001839 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1840 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001841 mTempTouchState.deviceId = entry.deviceId;
1842 mTempTouchState.source = entry.source;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001843 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001845 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1846 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001848 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1850 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001851 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001852 if (DEBUG_FOCUS) {
1853 ALOGD("Conflicting pointer actions: Down received while already down.");
1854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855 *outConflictingPointerActions = true;
1856 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1858 // One pointer went up.
1859 if (isSplit) {
1860 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001861 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001863 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001864 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1866 touchedWindow.pointerIds.clearBit(pointerId);
1867 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001868 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 continue;
1870 }
1871 }
1872 i += 1;
1873 }
1874 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001875 }
1876
1877 // Save changes unless the action was scroll in which case the temporary touch
1878 // state was only valid for this one action.
1879 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1880 if (mTempTouchState.displayId >= 0) {
1881 if (oldStateIndex >= 0) {
1882 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1883 } else {
1884 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1885 }
1886 } else if (oldStateIndex >= 0) {
1887 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 }
1890
1891 // Update hover state.
1892 mLastHoverWindowHandle = newHoverWindowHandle;
1893 }
1894 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001895 if (DEBUG_FOCUS) {
1896 ALOGD("Not updating touch focus because injection was denied.");
1897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 }
1899
1900Unresponsive:
1901 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1902 mTempTouchState.reset();
1903
1904 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001905 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001906 if (DEBUG_FOCUS) {
1907 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1908 "timeSpentWaitingForApplication=%0.1fms",
1909 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 return injectionResult;
1912}
1913
1914void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001915 int32_t targetFlags, BitSet32 pointerIds,
1916 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001917 std::vector<InputTarget>::iterator it =
1918 std::find_if(inputTargets.begin(), inputTargets.end(),
1919 [&windowHandle](const InputTarget& inputTarget) {
1920 return inputTarget.inputChannel->getConnectionToken() ==
1921 windowHandle->getToken();
1922 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00001923
Chavi Weingarten114b77f2020-01-15 22:35:10 +00001924 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001925
1926 if (it == inputTargets.end()) {
1927 InputTarget inputTarget;
1928 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1929 if (inputChannel == nullptr) {
1930 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1931 return;
1932 }
1933 inputTarget.inputChannel = inputChannel;
1934 inputTarget.flags = targetFlags;
1935 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
1936 inputTargets.push_back(inputTarget);
1937 it = inputTargets.end() - 1;
1938 }
1939
1940 ALOG_ASSERT(it->flags == targetFlags);
1941 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
1942
1943 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
1944 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945}
1946
Michael Wright3dd60e22019-03-27 22:06:44 +00001947void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001948 int32_t displayId, float xOffset,
1949 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001950 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1951 mGlobalMonitorsByDisplay.find(displayId);
1952
1953 if (it != mGlobalMonitorsByDisplay.end()) {
1954 const std::vector<Monitor>& monitors = it->second;
1955 for (const Monitor& monitor : monitors) {
1956 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958 }
1959}
1960
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001961void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1962 float yOffset,
1963 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001964 InputTarget target;
1965 target.inputChannel = monitor.inputChannel;
1966 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001967 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00001968 inputTargets.push_back(target);
1969}
1970
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001972 const InjectionState* injectionState) {
1973 if (injectionState &&
1974 (windowHandle == nullptr ||
1975 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1976 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001977 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001979 "owned by uid %d",
1980 injectionState->injectorPid, injectionState->injectorUid,
1981 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 } else {
1983 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001984 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 }
1986 return false;
1987 }
1988 return true;
1989}
1990
Robert Carr9cada032020-04-13 17:21:08 -07001991/**
1992 * Indicate whether one window handle should be considered as obscuring
1993 * another window handle. We only check a few preconditions. Actually
1994 * checking the bounds is left to the caller.
1995 */
1996static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
1997 const sp<InputWindowHandle>& otherHandle) {
1998 // Compare by token so cloned layers aren't counted
1999 if (haveSameToken(windowHandle, otherHandle)) {
2000 return false;
2001 }
2002 auto info = windowHandle->getInfo();
2003 auto otherInfo = otherHandle->getInfo();
2004 if (!otherInfo->visible) {
2005 return false;
2006 } else if (info->ownerPid == otherInfo->ownerPid && otherHandle->getToken() == nullptr) {
2007 // In general, if ownerPid is the same we don't want to generate occlusion
2008 // events. This line is now necessary since we are including all Surfaces
2009 // in occlusion calculation, so if we didn't check PID like this SurfaceView
2010 // would occlude their parents. On the other hand before we started including
2011 // all surfaces in occlusion calculation and had this line, we would count
2012 // windows with an input channel from the same PID as occluding, and so we
2013 // preserve this behavior with the getToken() == null check.
2014 return false;
2015 } else if (otherInfo->isTrustedOverlay()) {
2016 return false;
2017 } else if (otherInfo->displayId != info->displayId) {
2018 return false;
2019 }
2020 return true;
2021}
2022
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002023bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2024 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002026 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2027 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002028 if (windowHandle == otherHandle) {
2029 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002032 if (canBeObscuredBy(windowHandle, otherHandle) &&
2033 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 return true;
2035 }
2036 }
2037 return false;
2038}
2039
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002040bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2041 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002042 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002043 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002044 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002045 if (windowHandle == otherHandle) {
2046 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002047 }
2048
2049 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002050 if (canBeObscuredBy(windowHandle, otherHandle) &&
2051 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002052 return true;
2053 }
2054 }
2055 return false;
2056}
2057
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002058std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
2059 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002060 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07002061 // If the window is paused then keep waiting.
2062 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002063 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002064 }
2065
2066 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07002067 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002068 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002069 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002070 "registered with the input dispatcher. The window may be in the "
2071 "process of being removed.",
2072 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002073 }
2074
2075 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07002076 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002077 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002078 "The window may be in the process of being removed.",
2079 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07002080 }
2081
2082 // If the connection is backed up then keep waiting.
2083 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002084 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002085 "Outbound queue length: %zu. Wait queue length: %zu.",
2086 targetType, connection->outboundQueue.size(),
2087 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07002088 }
2089
2090 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002091 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07002092 // If the event is a key event, then we must wait for all previous events to
2093 // complete before delivering it because previous events may have the
2094 // side-effect of transferring focus to a different window and we want to
2095 // ensure that the following keys are sent to the new window.
2096 //
2097 // Suppose the user touches a button in a window then immediately presses "A".
2098 // If the button causes a pop-up window to appear then we want to ensure that
2099 // the "A" key is delivered to the new pop-up window. This is because users
2100 // often anticipate pending UI changes when typing on a keyboard.
2101 // To obtain this behavior, we must serialize key events with respect to all
2102 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002103 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002104 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002105 "finished processing all of the input events that were previously "
2106 "delivered to it. Outbound queue length: %zu. Wait queue length: "
2107 "%zu.",
2108 targetType, connection->outboundQueue.size(),
2109 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 }
Jeff Brownffb49772014-10-10 19:01:34 -07002111 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112 // Touch events can always be sent to a window immediately because the user intended
2113 // to touch whatever was visible at the time. Even if focus changes or a new
2114 // window appears moments later, the touch event was meant to be delivered to
2115 // whatever window happened to be on screen at the time.
2116 //
2117 // Generic motion events, such as trackball or joystick events are a little trickier.
2118 // Like key events, generic motion events are delivered to the focused window.
2119 // Unlike key events, generic motion events don't tend to transfer focus to other
2120 // windows and it is not important for them to be serialized. So we prefer to deliver
2121 // generic motion events as soon as possible to improve efficiency and reduce lag
2122 // through batching.
2123 //
2124 // The one case where we pause input event delivery is when the wait queue is piling
2125 // up with lots of events because the application is not responding.
2126 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002127 if (!connection->waitQueue.empty() &&
2128 currentTime >=
2129 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002130 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002131 "finished processing certain input events that were delivered to "
2132 "it over "
2133 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
2134 "%0.1fms.",
2135 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
2136 connection->waitQueue.size(),
2137 (currentTime - connection->waitQueue.front()->deliveryTime) *
2138 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 }
2140 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002141 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142}
2143
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002144std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145 const sp<InputApplicationHandle>& applicationHandle,
2146 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002147 if (applicationHandle != nullptr) {
2148 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002149 std::string label(applicationHandle->getName());
2150 label += " - ";
2151 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 return label;
2153 } else {
2154 return applicationHandle->getName();
2155 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002156 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 return windowHandle->getName();
2158 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002159 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 }
2161}
2162
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002163void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002164 if (eventEntry.type == EventEntry::Type::FOCUS) {
2165 // Focus events are passed to apps, but do not represent user activity.
2166 return;
2167 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002168 int32_t displayId = getTargetDisplayId(eventEntry);
2169 sp<InputWindowHandle> focusedWindowHandle =
2170 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2171 if (focusedWindowHandle != nullptr) {
2172 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2174#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002175 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176#endif
2177 return;
2178 }
2179 }
2180
2181 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002182 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002183 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002184 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2185 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002186 return;
2187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002189 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002190 eventType = USER_ACTIVITY_EVENT_TOUCH;
2191 }
2192 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002194 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002195 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2196 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002197 return;
2198 }
2199 eventType = USER_ACTIVITY_EVENT_BUTTON;
2200 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002202 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002203 case EventEntry::Type::CONFIGURATION_CHANGED:
2204 case EventEntry::Type::DEVICE_RESET: {
2205 LOG_ALWAYS_FATAL("%s events are not user activity",
2206 EventEntry::typeToString(eventEntry.type));
2207 break;
2208 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 }
2210
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002211 std::unique_ptr<CommandEntry> commandEntry =
2212 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002213 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002215 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216}
2217
2218void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002219 const sp<Connection>& connection,
2220 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002221 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002222 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002223 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002224 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002225 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002226 ATRACE_NAME(message.c_str());
2227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228#if DEBUG_DISPATCH_CYCLE
2229 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002230 "globalScaleFactor=%f, pointerIds=0x%x %s",
2231 connection->getInputChannelName().c_str(), inputTarget.flags,
2232 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2233 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234#endif
2235
2236 // Skip this event if the connection status is not normal.
2237 // We don't want to enqueue additional outbound events if the connection is broken.
2238 if (connection->status != Connection::STATUS_NORMAL) {
2239#if DEBUG_DISPATCH_CYCLE
2240 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002241 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242#endif
2243 return;
2244 }
2245
2246 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002247 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2248 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2249 "Entry type %s should not have FLAG_SPLIT",
2250 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002252 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002253 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002255 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 if (!splitMotionEntry) {
2257 return; // split event was dropped
2258 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002259 if (DEBUG_FOCUS) {
2260 ALOGD("channel '%s' ~ Split motion event.",
2261 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002262 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002263 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002264 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 splitMotionEntry->release();
2266 return;
2267 }
2268 }
2269
2270 // Not splitting. Enqueue dispatch entries for the event as is.
2271 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2272}
2273
2274void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002275 const sp<Connection>& connection,
2276 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002277 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002278 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002279 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002280 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002281 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002282 ATRACE_NAME(message.c_str());
2283 }
2284
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002285 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286
2287 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002288 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002290 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002291 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002292 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002293 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002294 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002296 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002298 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002299 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300
2301 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002302 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 startDispatchCycleLocked(currentTime, connection);
2304 }
2305}
2306
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002307void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2308 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002309 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002310 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002311 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002312 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2313 connection->getInputChannelName().c_str(),
2314 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002315 ATRACE_NAME(message.c_str());
2316 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002317 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 if (!(inputTargetFlags & dispatchMode)) {
2319 return;
2320 }
2321 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2322
2323 // This is a new event.
2324 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002325 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002326 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002328 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2329 // different EventEntry than what was passed in.
2330 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002332 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002333 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002334 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002335 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002336 dispatchEntry->resolvedAction = keyEntry.action;
2337 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002339 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2340 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002342 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2343 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002345 return; // skip the inconsistent event
2346 }
2347 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002350 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002351 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002352 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2353 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2354 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2355 static_cast<int32_t>(IdGenerator::Source::OTHER);
2356 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002357 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2358 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2359 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2360 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2361 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2362 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2363 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2364 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2365 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2366 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2367 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002368 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002369 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002370 }
2371 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002372 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2373 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002375 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2376 "event",
2377 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002379 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002382 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002383 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2384 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2385 }
2386 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2387 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002390 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2391 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002393 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2394 "event",
2395 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002397 return; // skip the inconsistent event
2398 }
2399
Garfield Tan1c7bc862020-01-28 13:24:04 -08002400 dispatchEntry->resolvedEventId =
2401 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2402 ? mIdGenerator.nextId()
2403 : motionEntry.id;
2404 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2405 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2406 ") to MotionEvent(id=0x%" PRIx32 ").",
2407 motionEntry.id, dispatchEntry->resolvedEventId);
2408 ATRACE_NAME(message.c_str());
2409 }
2410
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002411 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002412 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002413
2414 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002416 case EventEntry::Type::FOCUS: {
2417 break;
2418 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002419 case EventEntry::Type::CONFIGURATION_CHANGED:
2420 case EventEntry::Type::DEVICE_RESET: {
2421 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002422 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002423 break;
2424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 }
2426
2427 // Remember that we are waiting for this dispatch to complete.
2428 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002429 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 }
2431
2432 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002433 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002434 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002435}
2436
chaviwfd6d3512019-03-25 13:23:49 -07002437void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002438 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002439 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002440 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2441 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002442 return;
2443 }
2444
2445 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2446 if (inputWindowHandle == nullptr) {
2447 return;
2448 }
2449
chaviw8c9cf542019-03-25 13:02:48 -07002450 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002451 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002452
2453 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2454
2455 if (!hasFocusChanged) {
2456 return;
2457 }
2458
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002459 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2460 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002461 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002462 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463}
2464
2465void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002466 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002467 if (ATRACE_ENABLED()) {
2468 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002469 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002470 ATRACE_NAME(message.c_str());
2471 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002473 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474#endif
2475
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002476 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2477 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 dispatchEntry->deliveryTime = currentTime;
2479
2480 // Publish the event.
2481 status_t status;
2482 EventEntry* eventEntry = dispatchEntry->eventEntry;
2483 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002484 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002485 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Gang Wange9087892020-01-07 12:17:14 -05002486 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(*keyEntry);
2487 verifiedEvent.flags = dispatchEntry->resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2488 verifiedEvent.action = dispatchEntry->resolvedAction;
2489 std::array<uint8_t, 32> hmac = mHmacKeyManager.sign(verifiedEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002491 // Publish the key event.
Garfield Tan1c7bc862020-01-28 13:24:04 -08002492 status =
2493 connection->inputPublisher
2494 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2495 keyEntry->deviceId, keyEntry->source,
2496 keyEntry->displayId, std::move(hmac),
2497 dispatchEntry->resolvedAction,
2498 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2499 keyEntry->scanCode, keyEntry->metaState,
2500 keyEntry->repeatCount, keyEntry->downTime,
2501 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002502 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 }
2504
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002505 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002506 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002508 PointerCoords scaledCoords[MAX_POINTERS];
2509 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2510
chaviw82357092020-01-28 13:13:06 -08002511 // Set the X and Y offset and X and Y scale depending on the input source.
2512 float xOffset = 0.0f, yOffset = 0.0f;
2513 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002514 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2515 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2516 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002517 xScale = dispatchEntry->windowXScale;
2518 yScale = dispatchEntry->windowYScale;
2519 xOffset = dispatchEntry->xOffset * xScale;
2520 yOffset = dispatchEntry->yOffset * yScale;
2521 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002522 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2523 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002524 // Don't apply window scale here since we don't want scale to affect raw
2525 // coordinates. The scale will be sent back to the client and applied
2526 // later when requesting relative coordinates.
2527 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2528 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002529 }
2530 usingCoords = scaledCoords;
2531 }
2532 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533 // We don't want the dispatch target to know.
2534 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2535 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2536 scaledCoords[i].clear();
2537 }
2538 usingCoords = scaledCoords;
2539 }
2540 }
Gang Wange9087892020-01-07 12:17:14 -05002541 VerifiedMotionEvent verifiedEvent =
2542 verifiedMotionEventFromMotionEntry(*motionEntry);
2543 verifiedEvent.actionMasked =
2544 dispatchEntry->resolvedAction & AMOTION_EVENT_ACTION_MASK;
2545 verifiedEvent.flags = dispatchEntry->resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2546 std::array<uint8_t, 32> hmac = mHmacKeyManager.sign(verifiedEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002547
2548 // Publish the motion event.
2549 status = connection->inputPublisher
Garfield Tan1c7bc862020-01-28 13:24:04 -08002550 .publishMotionEvent(dispatchEntry->seq,
2551 dispatchEntry->resolvedEventId,
2552 motionEntry->deviceId, motionEntry->source,
2553 motionEntry->displayId, std::move(hmac),
2554 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002555 motionEntry->actionButton,
2556 dispatchEntry->resolvedFlags,
2557 motionEntry->edgeFlags, motionEntry->metaState,
2558 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002559 motionEntry->classification, xScale, yScale,
2560 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 motionEntry->yPrecision,
2562 motionEntry->xCursorPosition,
2563 motionEntry->yCursorPosition,
2564 motionEntry->downTime, motionEntry->eventTime,
2565 motionEntry->pointerCount,
2566 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002567 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002568 break;
2569 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002570 case EventEntry::Type::FOCUS: {
2571 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2572 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tan1c7bc862020-01-28 13:24:04 -08002573 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002574 focusEntry->hasFocus,
2575 mInTouchMode);
2576 break;
2577 }
2578
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002579 case EventEntry::Type::CONFIGURATION_CHANGED:
2580 case EventEntry::Type::DEVICE_RESET: {
2581 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2582 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002583 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 }
2586
2587 // Check the result.
2588 if (status) {
2589 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002590 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002592 "This is unexpected because the wait queue is empty, so the pipe "
2593 "should be empty and we shouldn't have any problems writing an "
2594 "event to it, status=%d",
2595 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2597 } else {
2598 // Pipe is full and we are waiting for the app to finish process some events
2599 // before sending more events to it.
2600#if DEBUG_DISPATCH_CYCLE
2601 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002602 "waiting for the application to catch up",
2603 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604#endif
2605 connection->inputPublisherBlocked = true;
2606 }
2607 } else {
2608 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002609 "status=%d",
2610 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002611 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2612 }
2613 return;
2614 }
2615
2616 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002617 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2618 connection->outboundQueue.end(),
2619 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002620 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002621 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002622 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 }
2624}
2625
2626void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002627 const sp<Connection>& connection, uint32_t seq,
2628 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629#if DEBUG_DISPATCH_CYCLE
2630 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002631 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632#endif
2633
2634 connection->inputPublisherBlocked = false;
2635
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002636 if (connection->status == Connection::STATUS_BROKEN ||
2637 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638 return;
2639 }
2640
2641 // Notify other system components and prepare to start the next dispatch cycle.
2642 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2643}
2644
2645void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002646 const sp<Connection>& connection,
2647 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648#if DEBUG_DISPATCH_CYCLE
2649 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002650 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651#endif
2652
2653 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002654 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002655 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002656 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002657 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658
2659 // The connection appears to be unrecoverably broken.
2660 // Ignore already broken or zombie connections.
2661 if (connection->status == Connection::STATUS_NORMAL) {
2662 connection->status = Connection::STATUS_BROKEN;
2663
2664 if (notify) {
2665 // Notify other system components.
2666 onDispatchCycleBrokenLocked(currentTime, connection);
2667 }
2668 }
2669}
2670
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002671void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2672 while (!queue.empty()) {
2673 DispatchEntry* dispatchEntry = queue.front();
2674 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002675 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676 }
2677}
2678
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002679void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002681 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 }
2683 delete dispatchEntry;
2684}
2685
2686int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2687 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2688
2689 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002690 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002692 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002694 "fd=%d, events=0x%x",
2695 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696 return 0; // remove the callback
2697 }
2698
2699 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002700 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2702 if (!(events & ALOOPER_EVENT_INPUT)) {
2703 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002704 "events=0x%x",
2705 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 return 1;
2707 }
2708
2709 nsecs_t currentTime = now();
2710 bool gotOne = false;
2711 status_t status;
2712 for (;;) {
2713 uint32_t seq;
2714 bool handled;
2715 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2716 if (status) {
2717 break;
2718 }
2719 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2720 gotOne = true;
2721 }
2722 if (gotOne) {
2723 d->runCommandsLockedInterruptible();
2724 if (status == WOULD_BLOCK) {
2725 return 1;
2726 }
2727 }
2728
2729 notify = status != DEAD_OBJECT || !connection->monitor;
2730 if (notify) {
2731 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002732 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733 }
2734 } else {
2735 // Monitor channels are never explicitly unregistered.
2736 // We do it automatically when the remote endpoint is closed so don't warn
2737 // about them.
2738 notify = !connection->monitor;
2739 if (notify) {
2740 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002741 "events=0x%x",
2742 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743 }
2744 }
2745
2746 // Unregister the channel.
2747 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2748 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002749 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750}
2751
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002752void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002754 for (const auto& pair : mConnectionsByFd) {
2755 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756 }
2757}
2758
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002759void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002760 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002761 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2762 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2763}
2764
2765void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2766 const CancelationOptions& options,
2767 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2768 for (const auto& it : monitorsByDisplay) {
2769 const std::vector<Monitor>& monitors = it.second;
2770 for (const Monitor& monitor : monitors) {
2771 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002772 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002773 }
2774}
2775
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2777 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002778 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002779 if (connection == nullptr) {
2780 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002782
2783 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784}
2785
2786void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2787 const sp<Connection>& connection, const CancelationOptions& options) {
2788 if (connection->status == Connection::STATUS_BROKEN) {
2789 return;
2790 }
2791
2792 nsecs_t currentTime = now();
2793
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002794 std::vector<EventEntry*> cancelationEvents =
2795 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002797 if (cancelationEvents.empty()) {
2798 return;
2799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002801 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2802 "with reality: %s, mode=%d.",
2803 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2804 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002806
2807 InputTarget target;
2808 sp<InputWindowHandle> windowHandle =
2809 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2810 if (windowHandle != nullptr) {
2811 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2812 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2813 windowInfo->windowXScale, windowInfo->windowYScale);
2814 target.globalScaleFactor = windowInfo->globalScaleFactor;
2815 }
2816 target.inputChannel = connection->inputChannel;
2817 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2818
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002819 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2820 EventEntry* cancelationEventEntry = cancelationEvents[i];
2821 switch (cancelationEventEntry->type) {
2822 case EventEntry::Type::KEY: {
2823 logOutboundKeyDetails("cancel - ",
2824 static_cast<const KeyEntry&>(*cancelationEventEntry));
2825 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002827 case EventEntry::Type::MOTION: {
2828 logOutboundMotionDetails("cancel - ",
2829 static_cast<const MotionEntry&>(*cancelationEventEntry));
2830 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002832 case EventEntry::Type::FOCUS: {
2833 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2834 break;
2835 }
2836 case EventEntry::Type::CONFIGURATION_CHANGED:
2837 case EventEntry::Type::DEVICE_RESET: {
2838 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2839 EventEntry::typeToString(cancelationEventEntry->type));
2840 break;
2841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 }
2843
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002844 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2845 target, InputTarget::FLAG_DISPATCH_AS_IS);
2846
2847 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002849
2850 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851}
2852
Svet Ganov5d3bc372020-01-26 23:11:07 -08002853void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2854 const sp<Connection>& connection) {
2855 if (connection->status == Connection::STATUS_BROKEN) {
2856 return;
2857 }
2858
2859 nsecs_t currentTime = now();
2860
2861 std::vector<EventEntry*> downEvents =
2862 connection->inputState.synthesizePointerDownEvents(currentTime);
2863
2864 if (downEvents.empty()) {
2865 return;
2866 }
2867
2868#if DEBUG_OUTBOUND_EVENT_DETAILS
2869 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2870 connection->getInputChannelName().c_str(), downEvents.size());
2871#endif
2872
2873 InputTarget target;
2874 sp<InputWindowHandle> windowHandle =
2875 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2876 if (windowHandle != nullptr) {
2877 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2878 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2879 windowInfo->windowXScale, windowInfo->windowYScale);
2880 target.globalScaleFactor = windowInfo->globalScaleFactor;
2881 }
2882 target.inputChannel = connection->inputChannel;
2883 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2884
2885 for (EventEntry* downEventEntry : downEvents) {
2886 switch (downEventEntry->type) {
2887 case EventEntry::Type::MOTION: {
2888 logOutboundMotionDetails("down - ",
2889 static_cast<const MotionEntry&>(*downEventEntry));
2890 break;
2891 }
2892
2893 case EventEntry::Type::KEY:
2894 case EventEntry::Type::FOCUS:
2895 case EventEntry::Type::CONFIGURATION_CHANGED:
2896 case EventEntry::Type::DEVICE_RESET: {
2897 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2898 EventEntry::typeToString(downEventEntry->type));
2899 break;
2900 }
2901 }
2902
2903 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2904 target, InputTarget::FLAG_DISPATCH_AS_IS);
2905
2906 downEventEntry->release();
2907 }
2908
2909 startDispatchCycleLocked(currentTime, connection);
2910}
2911
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002912MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002913 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914 ALOG_ASSERT(pointerIds.value != 0);
2915
2916 uint32_t splitPointerIndexMap[MAX_POINTERS];
2917 PointerProperties splitPointerProperties[MAX_POINTERS];
2918 PointerCoords splitPointerCoords[MAX_POINTERS];
2919
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002920 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921 uint32_t splitPointerCount = 0;
2922
2923 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002924 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002926 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927 uint32_t pointerId = uint32_t(pointerProperties.id);
2928 if (pointerIds.hasBit(pointerId)) {
2929 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2930 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2931 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002932 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 splitPointerCount += 1;
2934 }
2935 }
2936
2937 if (splitPointerCount != pointerIds.count()) {
2938 // This is bad. We are missing some of the pointers that we expected to deliver.
2939 // Most likely this indicates that we received an ACTION_MOVE events that has
2940 // different pointer ids than we expected based on the previous ACTION_DOWN
2941 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2942 // in this way.
2943 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002944 "we expected there to be %d pointers. This probably means we received "
2945 "a broken sequence of pointer ids from the input device.",
2946 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002947 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948 }
2949
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002950 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002952 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2953 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2955 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002956 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957 uint32_t pointerId = uint32_t(pointerProperties.id);
2958 if (pointerIds.hasBit(pointerId)) {
2959 if (pointerIds.count() == 1) {
2960 // The first/last pointer went down/up.
2961 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002962 ? AMOTION_EVENT_ACTION_DOWN
2963 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002964 } else {
2965 // A secondary pointer went down/up.
2966 uint32_t splitPointerIndex = 0;
2967 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2968 splitPointerIndex += 1;
2969 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002970 action = maskedAction |
2971 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 }
2973 } else {
2974 // An unrelated pointer changed.
2975 action = AMOTION_EVENT_ACTION_MOVE;
2976 }
2977 }
2978
Garfield Tan1c7bc862020-01-28 13:24:04 -08002979 int32_t newId = mIdGenerator.nextId();
2980 if (ATRACE_ENABLED()) {
2981 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
2982 ") to MotionEvent(id=0x%" PRIx32 ").",
2983 originalMotionEntry.id, newId);
2984 ATRACE_NAME(message.c_str());
2985 }
Garfield Tan00f511d2019-06-12 16:55:40 -07002986 MotionEntry* splitMotionEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002987 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
2988 originalMotionEntry.source, originalMotionEntry.displayId,
2989 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002990 originalMotionEntry.actionButton, originalMotionEntry.flags,
2991 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2992 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2993 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2994 originalMotionEntry.xCursorPosition,
2995 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002996 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002998 if (originalMotionEntry.injectionState) {
2999 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000 splitMotionEntry->injectionState->refCount += 1;
3001 }
3002
3003 return splitMotionEntry;
3004}
3005
3006void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3007#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003008 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009#endif
3010
3011 bool needWake;
3012 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003013 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014
Prabir Pradhan42611e02018-11-27 14:04:02 -08003015 ConfigurationChangedEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003016 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 needWake = enqueueInboundEventLocked(newEntry);
3018 } // release lock
3019
3020 if (needWake) {
3021 mLooper->wake();
3022 }
3023}
3024
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003025/**
3026 * If one of the meta shortcuts is detected, process them here:
3027 * Meta + Backspace -> generate BACK
3028 * Meta + Enter -> generate HOME
3029 * This will potentially overwrite keyCode and metaState.
3030 */
3031void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003032 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003033 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3034 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3035 if (keyCode == AKEYCODE_DEL) {
3036 newKeyCode = AKEYCODE_BACK;
3037 } else if (keyCode == AKEYCODE_ENTER) {
3038 newKeyCode = AKEYCODE_HOME;
3039 }
3040 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003041 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003042 struct KeyReplacement replacement = {keyCode, deviceId};
3043 mReplacedKeys.add(replacement, newKeyCode);
3044 keyCode = newKeyCode;
3045 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3046 }
3047 } else if (action == AKEY_EVENT_ACTION_UP) {
3048 // In order to maintain a consistent stream of up and down events, check to see if the key
3049 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3050 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003051 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003052 struct KeyReplacement replacement = {keyCode, deviceId};
3053 ssize_t index = mReplacedKeys.indexOfKey(replacement);
3054 if (index >= 0) {
3055 keyCode = mReplacedKeys.valueAt(index);
3056 mReplacedKeys.removeItemsAt(index);
3057 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3058 }
3059 }
3060}
3061
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3063#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003064 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3065 "policyFlags=0x%x, action=0x%x, "
3066 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3067 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3068 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3069 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070#endif
3071 if (!validateKeyEvent(args->action)) {
3072 return;
3073 }
3074
3075 uint32_t policyFlags = args->policyFlags;
3076 int32_t flags = args->flags;
3077 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003078 // InputDispatcher tracks and generates key repeats on behalf of
3079 // whatever notifies it, so repeatCount should always be set to 0
3080 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3082 policyFlags |= POLICY_FLAG_VIRTUAL;
3083 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085 if (policyFlags & POLICY_FLAG_FUNCTION) {
3086 metaState |= AMETA_FUNCTION_ON;
3087 }
3088
3089 policyFlags |= POLICY_FLAG_TRUSTED;
3090
Michael Wright78f24442014-08-06 15:55:28 -07003091 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003092 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003093
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003095 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08003096 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3097 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098
Michael Wright2b3c3302018-03-02 17:19:13 +00003099 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003101 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3102 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003103 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003104 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106 bool needWake;
3107 { // acquire lock
3108 mLock.lock();
3109
3110 if (shouldSendKeyToInputFilterLocked(args)) {
3111 mLock.unlock();
3112
3113 policyFlags |= POLICY_FLAG_FILTERED;
3114 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3115 return; // event was consumed by the filter
3116 }
3117
3118 mLock.lock();
3119 }
3120
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121 KeyEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003122 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003123 args->displayId, policyFlags, args->action, flags, keyCode,
3124 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125
3126 needWake = enqueueInboundEventLocked(newEntry);
3127 mLock.unlock();
3128 } // release lock
3129
3130 if (needWake) {
3131 mLooper->wake();
3132 }
3133}
3134
3135bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3136 return mInputFilterEnabled;
3137}
3138
3139void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3140#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003141 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3142 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003143 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3144 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003145 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003146 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3147 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3148 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3149 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150 for (uint32_t i = 0; i < args->pointerCount; i++) {
3151 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003152 "x=%f, y=%f, pressure=%f, size=%f, "
3153 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3154 "orientation=%f",
3155 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3156 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3157 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3158 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3159 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3160 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3161 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3162 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3163 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3164 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 }
3166#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003167 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3168 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 return;
3170 }
3171
3172 uint32_t policyFlags = args->policyFlags;
3173 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003174
3175 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003176 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003177 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3178 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003179 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181
3182 bool needWake;
3183 { // acquire lock
3184 mLock.lock();
3185
3186 if (shouldSendMotionToInputFilterLocked(args)) {
3187 mLock.unlock();
3188
3189 MotionEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003190 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3191 args->action, args->actionButton, args->flags, args->edgeFlags,
3192 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3193 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3194 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3195 args->downTime, args->eventTime, args->pointerCount,
3196 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197
3198 policyFlags |= POLICY_FLAG_FILTERED;
3199 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3200 return; // event was consumed by the filter
3201 }
3202
3203 mLock.lock();
3204 }
3205
3206 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003207 MotionEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003208 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003209 args->displayId, policyFlags, args->action, args->actionButton,
3210 args->flags, args->metaState, args->buttonState,
3211 args->classification, args->edgeFlags, args->xPrecision,
3212 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3213 args->downTime, args->pointerCount, args->pointerProperties,
3214 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215
3216 needWake = enqueueInboundEventLocked(newEntry);
3217 mLock.unlock();
3218 } // release lock
3219
3220 if (needWake) {
3221 mLooper->wake();
3222 }
3223}
3224
3225bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003226 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227}
3228
3229void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3230#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003231 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003232 "switchMask=0x%08x",
3233 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234#endif
3235
3236 uint32_t policyFlags = args->policyFlags;
3237 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003238 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239}
3240
3241void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3242#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3244 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245#endif
3246
3247 bool needWake;
3248 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003249 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250
Prabir Pradhan42611e02018-11-27 14:04:02 -08003251 DeviceResetEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003252 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 needWake = enqueueInboundEventLocked(newEntry);
3254 } // release lock
3255
3256 if (needWake) {
3257 mLooper->wake();
3258 }
3259}
3260
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003261int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3262 int32_t injectorUid, int32_t syncMode,
3263 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264#if DEBUG_INBOUND_EVENT_DETAILS
3265 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003266 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
3267 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268#endif
3269
3270 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
3271
3272 policyFlags |= POLICY_FLAG_INJECTED;
3273 if (hasInjectionPermission(injectorPid, injectorUid)) {
3274 policyFlags |= POLICY_FLAG_TRUSTED;
3275 }
3276
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003277 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003279 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003280 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3281 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003282 if (!validateKeyEvent(action)) {
3283 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003286 int32_t flags = incomingKey.getFlags();
3287 int32_t keyCode = incomingKey.getKeyCode();
3288 int32_t metaState = incomingKey.getMetaState();
3289 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003290 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003291 KeyEvent keyEvent;
Garfield Tanfbe732e2020-01-24 11:26:14 -08003292 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003293 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3294 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3295 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003297 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3298 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003299 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003300
3301 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3302 android::base::Timer t;
3303 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3304 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3305 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3306 std::to_string(t.duration().count()).c_str());
3307 }
3308 }
3309
3310 mLock.lock();
3311 KeyEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003312 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3313 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3314 incomingKey.getDisplayId(), policyFlags, action, flags,
3315 incomingKey.getKeyCode(), incomingKey.getScanCode(),
3316 incomingKey.getMetaState(), incomingKey.getRepeatCount(),
3317 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 injectedEntries.push(injectedEntry);
3319 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 }
3321
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 case AINPUT_EVENT_TYPE_MOTION: {
3323 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3324 int32_t action = motionEvent->getAction();
3325 size_t pointerCount = motionEvent->getPointerCount();
3326 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3327 int32_t actionButton = motionEvent->getActionButton();
3328 int32_t displayId = motionEvent->getDisplayId();
3329 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3330 return INPUT_EVENT_INJECTION_FAILED;
3331 }
3332
3333 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3334 nsecs_t eventTime = motionEvent->getEventTime();
3335 android::base::Timer t;
3336 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3337 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3338 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3339 std::to_string(t.duration().count()).c_str());
3340 }
3341 }
3342
3343 mLock.lock();
3344 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3345 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3346 MotionEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003347 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3348 motionEvent->getSource(), motionEvent->getDisplayId(),
3349 policyFlags, action, actionButton, motionEvent->getFlags(),
3350 motionEvent->getMetaState(), motionEvent->getButtonState(),
3351 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3352 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003353 motionEvent->getRawXCursorPosition(),
3354 motionEvent->getRawYCursorPosition(),
3355 motionEvent->getDownTime(), uint32_t(pointerCount),
3356 pointerProperties, samplePointerCoords,
3357 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003358 injectedEntries.push(injectedEntry);
3359 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3360 sampleEventTimes += 1;
3361 samplePointerCoords += pointerCount;
3362 MotionEntry* nextInjectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003363 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003364 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003365 motionEvent->getDisplayId(), policyFlags, action,
3366 actionButton, motionEvent->getFlags(),
3367 motionEvent->getMetaState(), motionEvent->getButtonState(),
3368 motionEvent->getClassification(),
3369 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3370 motionEvent->getYPrecision(),
3371 motionEvent->getRawXCursorPosition(),
3372 motionEvent->getRawYCursorPosition(),
3373 motionEvent->getDownTime(), uint32_t(pointerCount),
3374 pointerProperties, samplePointerCoords,
3375 motionEvent->getXOffset(), motionEvent->getYOffset());
3376 injectedEntries.push(nextInjectedEntry);
3377 }
3378 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003381 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003382 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003383 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 }
3385
3386 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3387 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3388 injectionState->injectionIsAsync = true;
3389 }
3390
3391 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003392 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393
3394 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003395 while (!injectedEntries.empty()) {
3396 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3397 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 }
3399
3400 mLock.unlock();
3401
3402 if (needWake) {
3403 mLooper->wake();
3404 }
3405
3406 int32_t injectionResult;
3407 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003408 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409
3410 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3411 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3412 } else {
3413 for (;;) {
3414 injectionResult = injectionState->injectionResult;
3415 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3416 break;
3417 }
3418
3419 nsecs_t remainingTimeout = endTime - now();
3420 if (remainingTimeout <= 0) {
3421#if DEBUG_INJECTION
3422 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003423 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424#endif
3425 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3426 break;
3427 }
3428
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003429 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 }
3431
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003432 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3433 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434 while (injectionState->pendingForegroundDispatches != 0) {
3435#if DEBUG_INJECTION
3436 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003437 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438#endif
3439 nsecs_t remainingTimeout = endTime - now();
3440 if (remainingTimeout <= 0) {
3441#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003442 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3443 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444#endif
3445 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3446 break;
3447 }
3448
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003449 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450 }
3451 }
3452 }
3453
3454 injectionState->release();
3455 } // release lock
3456
3457#if DEBUG_INJECTION
3458 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003459 "injectorPid=%d, injectorUid=%d",
3460 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461#endif
3462
3463 return injectionResult;
3464}
3465
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003466std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003467 std::array<uint8_t, 32> calculatedHmac;
3468 std::unique_ptr<VerifiedInputEvent> result;
3469 switch (event.getType()) {
3470 case AINPUT_EVENT_TYPE_KEY: {
3471 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3472 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3473 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3474 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3475 break;
3476 }
3477 case AINPUT_EVENT_TYPE_MOTION: {
3478 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3479 VerifiedMotionEvent verifiedMotionEvent =
3480 verifiedMotionEventFromMotionEvent(motionEvent);
3481 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3482 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3483 break;
3484 }
3485 default: {
3486 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3487 return nullptr;
3488 }
3489 }
3490 if (calculatedHmac == INVALID_HMAC) {
3491 return nullptr;
3492 }
3493 if (calculatedHmac != event.getHmac()) {
3494 return nullptr;
3495 }
3496 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003497}
3498
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003500 return injectorUid == 0 ||
3501 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502}
3503
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003504void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 InjectionState* injectionState = entry->injectionState;
3506 if (injectionState) {
3507#if DEBUG_INJECTION
3508 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003509 "injectorPid=%d, injectorUid=%d",
3510 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511#endif
3512
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003513 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514 // Log the outcome since the injector did not wait for the injection result.
3515 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003516 case INPUT_EVENT_INJECTION_SUCCEEDED:
3517 ALOGV("Asynchronous input event injection succeeded.");
3518 break;
3519 case INPUT_EVENT_INJECTION_FAILED:
3520 ALOGW("Asynchronous input event injection failed.");
3521 break;
3522 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3523 ALOGW("Asynchronous input event injection permission denied.");
3524 break;
3525 case INPUT_EVENT_INJECTION_TIMED_OUT:
3526 ALOGW("Asynchronous input event injection timed out.");
3527 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 }
3529 }
3530
3531 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003532 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 }
3534}
3535
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003536void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 InjectionState* injectionState = entry->injectionState;
3538 if (injectionState) {
3539 injectionState->pendingForegroundDispatches += 1;
3540 }
3541}
3542
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003543void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544 InjectionState* injectionState = entry->injectionState;
3545 if (injectionState) {
3546 injectionState->pendingForegroundDispatches -= 1;
3547
3548 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003549 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550 }
3551 }
3552}
3553
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003554std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3555 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003556 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003557}
3558
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003560 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003561 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003562 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3563 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003564 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003565 return windowHandle;
3566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 }
3568 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003569 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570}
3571
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003572bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003573 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003574 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3575 for (const sp<InputWindowHandle>& handle : windowHandles) {
3576 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003577 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003578 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003579 ", but it should belong to display %" PRId32,
3580 windowHandle->getName().c_str(), it.first,
3581 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003582 }
3583 return true;
3584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585 }
3586 }
3587 return false;
3588}
3589
Robert Carr5c8a0262018-10-03 16:30:44 -07003590sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3591 size_t count = mInputChannelsByToken.count(token);
3592 if (count == 0) {
3593 return nullptr;
3594 }
3595 return mInputChannelsByToken.at(token);
3596}
3597
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003598void InputDispatcher::updateWindowHandlesForDisplayLocked(
3599 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3600 if (inputWindowHandles.empty()) {
3601 // Remove all handles on a display if there are no windows left.
3602 mWindowHandlesByDisplay.erase(displayId);
3603 return;
3604 }
3605
3606 // Since we compare the pointer of input window handles across window updates, we need
3607 // to make sure the handle object for the same window stays unchanged across updates.
3608 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003609 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003610 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003611 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003612 }
3613
3614 std::vector<sp<InputWindowHandle>> newHandles;
3615 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3616 if (!handle->updateInfo()) {
3617 // handle no longer valid
3618 continue;
3619 }
3620
3621 const InputWindowInfo* info = handle->getInfo();
3622 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3623 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3624 const bool noInputChannel =
3625 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3626 const bool canReceiveInput =
3627 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3628 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3629 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003630 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003631 handle->getName().c_str());
3632 }
3633 continue;
3634 }
3635
3636 if (info->displayId != displayId) {
3637 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3638 handle->getName().c_str(), displayId, info->displayId);
3639 continue;
3640 }
3641
chaviwaf87b3e2019-10-01 16:59:28 -07003642 if (oldHandlesById.find(handle->getId()) != oldHandlesById.end()) {
3643 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003644 oldHandle->updateFrom(handle);
3645 newHandles.push_back(oldHandle);
3646 } else {
3647 newHandles.push_back(handle);
3648 }
3649 }
3650
3651 // Insert or replace
3652 mWindowHandlesByDisplay[displayId] = newHandles;
3653}
3654
Arthur Hung72d8dc32020-03-28 00:48:39 +00003655void InputDispatcher::setInputWindows(
3656 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3657 { // acquire lock
3658 std::scoped_lock _l(mLock);
3659 for (auto const& i : handlesPerDisplay) {
3660 setInputWindowsLocked(i.second, i.first);
3661 }
3662 }
3663 // Wake up poll loop since it may need to make new input dispatching choices.
3664 mLooper->wake();
3665}
3666
Arthur Hungb92218b2018-08-14 12:00:21 +08003667/**
3668 * Called from InputManagerService, update window handle list by displayId that can receive input.
3669 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3670 * If set an empty list, remove all handles from the specific display.
3671 * For focused handle, check if need to change and send a cancel event to previous one.
3672 * For removed handle, check if need to send a cancel event if already in touch.
3673 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003674void InputDispatcher::setInputWindowsLocked(
3675 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003676 if (DEBUG_FOCUS) {
3677 std::string windowList;
3678 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3679 windowList += iwh->getName() + " ";
3680 }
3681 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683
Arthur Hung72d8dc32020-03-28 00:48:39 +00003684 // Copy old handles for release if they are no longer present.
3685 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686
Arthur Hung72d8dc32020-03-28 00:48:39 +00003687 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003688
Arthur Hung72d8dc32020-03-28 00:48:39 +00003689 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3690 bool foundHoveredWindow = false;
3691 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3692 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3693 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3694 windowHandle->getInfo()->visible) {
3695 newFocusedWindowHandle = windowHandle;
3696 }
3697 if (windowHandle == mLastHoverWindowHandle) {
3698 foundHoveredWindow = true;
3699 }
3700 }
3701
3702 if (!foundHoveredWindow) {
3703 mLastHoverWindowHandle = nullptr;
3704 }
3705
3706 sp<InputWindowHandle> oldFocusedWindowHandle =
3707 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3708
3709 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3710 if (oldFocusedWindowHandle != nullptr) {
3711 if (DEBUG_FOCUS) {
3712 ALOGD("Focus left window: %s in display %" PRId32,
3713 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003714 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003715 sp<InputChannel> focusedInputChannel =
3716 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3717 if (focusedInputChannel != nullptr) {
3718 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3719 "focus left window");
3720 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3721 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003722 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003723 mFocusedWindowHandlesByDisplay.erase(displayId);
3724 }
3725 if (newFocusedWindowHandle != nullptr) {
3726 if (DEBUG_FOCUS) {
3727 ALOGD("Focus entered window: %s in display %" PRId32,
3728 newFocusedWindowHandle->getName().c_str(), displayId);
3729 }
3730 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3731 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 }
3733
Arthur Hung72d8dc32020-03-28 00:48:39 +00003734 if (mFocusedDisplayId == displayId) {
3735 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738
Arthur Hung72d8dc32020-03-28 00:48:39 +00003739 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3740 if (stateIndex >= 0) {
3741 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
3742 for (size_t i = 0; i < state.windows.size();) {
3743 TouchedWindow& touchedWindow = state.windows[i];
3744 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003745 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003746 ALOGD("Touched window was removed: %s in display %" PRId32,
3747 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003748 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003749 sp<InputChannel> touchedInputChannel =
3750 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3751 if (touchedInputChannel != nullptr) {
3752 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3753 "touched window was removed");
3754 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003756 state.windows.erase(state.windows.begin() + i);
3757 } else {
3758 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 }
3760 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003761 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003762
Arthur Hung72d8dc32020-03-28 00:48:39 +00003763 // Release information for windows that are no longer present.
3764 // This ensures that unused input channels are released promptly.
3765 // Otherwise, they might stick around until the window handle is destroyed
3766 // which might not happen until the next GC.
3767 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3768 if (!hasWindowHandleLocked(oldWindowHandle)) {
3769 if (DEBUG_FOCUS) {
3770 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003771 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003772 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003773 }
chaviw291d88a2019-02-14 10:33:58 -08003774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775}
3776
3777void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003778 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003779 if (DEBUG_FOCUS) {
3780 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3781 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003784 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785
Tiger Huang721e26f2018-07-24 22:26:19 +08003786 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3787 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003788 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003789 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3790 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003793 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003795 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003797 oldFocusedApplicationHandle.clear();
3798 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 } // release lock
3801
3802 // Wake up poll loop since it may need to make new input dispatching choices.
3803 mLooper->wake();
3804}
3805
Tiger Huang721e26f2018-07-24 22:26:19 +08003806/**
3807 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3808 * the display not specified.
3809 *
3810 * We track any unreleased events for each window. If a window loses the ability to receive the
3811 * released event, we will send a cancel event to it. So when the focused display is changed, we
3812 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3813 * display. The display-specified events won't be affected.
3814 */
3815void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003816 if (DEBUG_FOCUS) {
3817 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3818 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003819 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003820 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003821
3822 if (mFocusedDisplayId != displayId) {
3823 sp<InputWindowHandle> oldFocusedWindowHandle =
3824 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3825 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003826 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003827 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003828 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003829 CancelationOptions
3830 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3831 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003832 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003833 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3834 }
3835 }
3836 mFocusedDisplayId = displayId;
3837
3838 // Sanity check
3839 sp<InputWindowHandle> newFocusedWindowHandle =
3840 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003841 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003842
Tiger Huang721e26f2018-07-24 22:26:19 +08003843 if (newFocusedWindowHandle == nullptr) {
3844 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3845 if (!mFocusedWindowHandlesByDisplay.empty()) {
3846 ALOGE("But another display has a focused window:");
3847 for (auto& it : mFocusedWindowHandlesByDisplay) {
3848 const int32_t displayId = it.first;
3849 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003850 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3851 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003852 }
3853 }
3854 }
3855 }
3856
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003857 if (DEBUG_FOCUS) {
3858 logDispatchStateLocked();
3859 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003860 } // release lock
3861
3862 // Wake up poll loop since it may need to make new input dispatching choices.
3863 mLooper->wake();
3864}
3865
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003867 if (DEBUG_FOCUS) {
3868 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870
3871 bool changed;
3872 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003873 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874
3875 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3876 if (mDispatchFrozen && !frozen) {
3877 resetANRTimeoutsLocked();
3878 }
3879
3880 if (mDispatchEnabled && !enabled) {
3881 resetAndDropEverythingLocked("dispatcher is being disabled");
3882 }
3883
3884 mDispatchEnabled = enabled;
3885 mDispatchFrozen = frozen;
3886 changed = true;
3887 } else {
3888 changed = false;
3889 }
3890
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003891 if (DEBUG_FOCUS) {
3892 logDispatchStateLocked();
3893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894 } // release lock
3895
3896 if (changed) {
3897 // Wake up poll loop since it may need to make new input dispatching choices.
3898 mLooper->wake();
3899 }
3900}
3901
3902void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003903 if (DEBUG_FOCUS) {
3904 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3905 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906
3907 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003908 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909
3910 if (mInputFilterEnabled == enabled) {
3911 return;
3912 }
3913
3914 mInputFilterEnabled = enabled;
3915 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3916 } // release lock
3917
3918 // Wake up poll loop since there might be work to do to drop everything.
3919 mLooper->wake();
3920}
3921
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003922void InputDispatcher::setInTouchMode(bool inTouchMode) {
3923 std::scoped_lock lock(mLock);
3924 mInTouchMode = inTouchMode;
3925}
3926
chaviwfbe5d9c2018-12-26 12:23:37 -08003927bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3928 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003929 if (DEBUG_FOCUS) {
3930 ALOGD("Trivial transfer to same window.");
3931 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003932 return true;
3933 }
3934
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003936 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937
chaviwfbe5d9c2018-12-26 12:23:37 -08003938 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3939 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003940 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003941 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942 return false;
3943 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003944 if (DEBUG_FOCUS) {
3945 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3946 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003949 if (DEBUG_FOCUS) {
3950 ALOGD("Cannot transfer focus because windows are on different displays.");
3951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 return false;
3953 }
3954
3955 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003956 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3957 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3958 for (size_t i = 0; i < state.windows.size(); i++) {
3959 const TouchedWindow& touchedWindow = state.windows[i];
3960 if (touchedWindow.windowHandle == fromWindowHandle) {
3961 int32_t oldTargetFlags = touchedWindow.targetFlags;
3962 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003964 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003966 int32_t newTargetFlags = oldTargetFlags &
3967 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3968 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003969 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970
Jeff Brownf086ddb2014-02-11 14:28:48 -08003971 found = true;
3972 goto Found;
3973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 }
3975 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003976 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003978 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003979 if (DEBUG_FOCUS) {
3980 ALOGD("Focus transfer failed because from window did not have focus.");
3981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982 return false;
3983 }
3984
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003985 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3986 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003987 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003988 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003989 CancelationOptions
3990 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3991 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003993 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 }
3995
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003996 if (DEBUG_FOCUS) {
3997 logDispatchStateLocked();
3998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999 } // release lock
4000
4001 // Wake up poll loop since it may need to make new input dispatching choices.
4002 mLooper->wake();
4003 return true;
4004}
4005
4006void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004007 if (DEBUG_FOCUS) {
4008 ALOGD("Resetting and dropping all events (%s).", reason);
4009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010
4011 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4012 synthesizeCancelationEventsForAllConnectionsLocked(options);
4013
4014 resetKeyRepeatLocked();
4015 releasePendingEventLocked();
4016 drainInboundQueueLocked();
4017 resetANRTimeoutsLocked();
4018
Jeff Brownf086ddb2014-02-11 14:28:48 -08004019 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004021 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022}
4023
4024void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004025 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026 dumpDispatchStateLocked(dump);
4027
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004028 std::istringstream stream(dump);
4029 std::string line;
4030
4031 while (std::getline(stream, line, '\n')) {
4032 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033 }
4034}
4035
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004036void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004037 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4038 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4039 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004040 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041
Tiger Huang721e26f2018-07-24 22:26:19 +08004042 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4043 dump += StringPrintf(INDENT "FocusedApplications:\n");
4044 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4045 const int32_t displayId = it.first;
4046 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004047 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4048 ", name='%s', dispatchingTimeout=%0.3fms\n",
4049 displayId, applicationHandle->getName().c_str(),
4050 applicationHandle->getDispatchingTimeout(
4051 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
4052 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08004053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004055 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004057
4058 if (!mFocusedWindowHandlesByDisplay.empty()) {
4059 dump += StringPrintf(INDENT "FocusedWindows:\n");
4060 for (auto& it : mFocusedWindowHandlesByDisplay) {
4061 const int32_t displayId = it.first;
4062 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004063 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4064 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004065 }
4066 } else {
4067 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069
Jeff Brownf086ddb2014-02-11 14:28:48 -08004070 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004071 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08004072 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
4073 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004074 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004075 state.displayId, toString(state.down), toString(state.split),
4076 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004077 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004078 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004079 for (size_t i = 0; i < state.windows.size(); i++) {
4080 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004081 dump += StringPrintf(INDENT4
4082 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4083 i, touchedWindow.windowHandle->getName().c_str(),
4084 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004085 }
4086 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004087 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004088 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004089 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004090 dump += INDENT3 "Portal windows:\n";
4091 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004092 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004093 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4094 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004095 }
4096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 }
4098 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004099 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 }
4101
Arthur Hungb92218b2018-08-14 12:00:21 +08004102 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004103 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004104 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004105 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004106 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004107 dump += INDENT2 "Windows:\n";
4108 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004109 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004110 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111
Arthur Hungb92218b2018-08-14 12:00:21 +08004112 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004113 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004114 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4115 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004116 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004117 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004118 i, windowInfo->name.c_str(), windowInfo->displayId,
4119 windowInfo->portalToDisplayId,
4120 toString(windowInfo->paused),
4121 toString(windowInfo->hasFocus),
4122 toString(windowInfo->hasWallpaper),
4123 toString(windowInfo->visible),
4124 toString(windowInfo->canReceiveKeys),
4125 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004126 windowInfo->layoutParamsType, windowInfo->frameLeft,
4127 windowInfo->frameTop, windowInfo->frameRight,
4128 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4129 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004130 dumpRegion(dump, windowInfo->touchableRegion);
4131 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
4132 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004133 windowInfo->ownerPid, windowInfo->ownerUid,
4134 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08004135 }
4136 } else {
4137 dump += INDENT2 "Windows: <none>\n";
4138 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 }
4140 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004141 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 }
4143
Michael Wright3dd60e22019-03-27 22:06:44 +00004144 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004145 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004146 const std::vector<Monitor>& monitors = it.second;
4147 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4148 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004149 }
4150 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004151 const std::vector<Monitor>& monitors = it.second;
4152 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4153 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004156 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 }
4158
4159 nsecs_t currentTime = now();
4160
4161 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004162 if (!mRecentQueue.empty()) {
4163 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4164 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004165 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 }
4169 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004170 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 }
4172
4173 // Dump event currently being dispatched.
4174 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004175 dump += INDENT "PendingEvent:\n";
4176 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004178 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004179 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004181 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 }
4183
4184 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004185 if (!mInboundQueue.empty()) {
4186 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4187 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004188 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004190 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 }
4192 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004193 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 }
4195
Michael Wright78f24442014-08-06 15:55:28 -07004196 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004197 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07004198 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
4199 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
4200 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
4202 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004203 }
4204 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004205 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004206 }
4207
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004208 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004209 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004210 for (const auto& pair : mConnectionsByFd) {
4211 const sp<Connection>& connection = pair.second;
4212 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
4213 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
4214 pair.first, connection->getInputChannelName().c_str(),
4215 connection->getWindowName().c_str(), connection->getStatusLabel(),
4216 toString(connection->monitor),
4217 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004219 if (!connection->outboundQueue.empty()) {
4220 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4221 connection->outboundQueue.size());
4222 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 dump.append(INDENT4);
4224 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004225 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004226 entry->targetFlags, entry->resolvedAction,
4227 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 }
4229 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004230 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 }
4232
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004233 if (!connection->waitQueue.empty()) {
4234 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4235 connection->waitQueue.size());
4236 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004237 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004239 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004240 "age=%0.1fms, wait=%0.1fms\n",
4241 entry->targetFlags, entry->resolvedAction,
4242 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
4243 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244 }
4245 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004246 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 }
4248 }
4249 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004250 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 }
4252
4253 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004254 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004255 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004257 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 }
4259
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004260 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004262 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004263 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264}
4265
Michael Wright3dd60e22019-03-27 22:06:44 +00004266void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4267 const size_t numMonitors = monitors.size();
4268 for (size_t i = 0; i < numMonitors; i++) {
4269 const Monitor& monitor = monitors[i];
4270 const sp<InputChannel>& channel = monitor.inputChannel;
4271 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4272 dump += "\n";
4273 }
4274}
4275
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004276status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004278 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279#endif
4280
4281 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004282 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004283 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004284 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004286 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 return BAD_VALUE;
4288 }
4289
Garfield Tan1c7bc862020-01-28 13:24:04 -08004290 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291
4292 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004293 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004294 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4297 } // release lock
4298
4299 // Wake the looper because some connections have changed.
4300 mLooper->wake();
4301 return OK;
4302}
4303
Michael Wright3dd60e22019-03-27 22:06:44 +00004304status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004305 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004306 { // acquire lock
4307 std::scoped_lock _l(mLock);
4308
4309 if (displayId < 0) {
4310 ALOGW("Attempted to register input monitor without a specified display.");
4311 return BAD_VALUE;
4312 }
4313
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004314 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004315 ALOGW("Attempted to register input monitor without an identifying token.");
4316 return BAD_VALUE;
4317 }
4318
Garfield Tan1c7bc862020-01-28 13:24:04 -08004319 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004320
4321 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004322 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004323 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004324
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004325 auto& monitorsByDisplay =
4326 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004327 monitorsByDisplay[displayId].emplace_back(inputChannel);
4328
4329 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004330 }
4331 // Wake the looper because some connections have changed.
4332 mLooper->wake();
4333 return OK;
4334}
4335
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4337#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004338 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339#endif
4340
4341 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004342 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343
4344 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4345 if (status) {
4346 return status;
4347 }
4348 } // release lock
4349
4350 // Wake the poll loop because removing the connection may have changed the current
4351 // synchronization state.
4352 mLooper->wake();
4353 return OK;
4354}
4355
4356status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004357 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004358 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004359 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004361 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362 return BAD_VALUE;
4363 }
4364
John Recke0710582019-09-26 13:46:12 -07004365 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004366 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004367 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004368
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 if (connection->monitor) {
4370 removeMonitorChannelLocked(inputChannel);
4371 }
4372
4373 mLooper->removeFd(inputChannel->getFd());
4374
4375 nsecs_t currentTime = now();
4376 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4377
4378 connection->status = Connection::STATUS_ZOMBIE;
4379 return OK;
4380}
4381
4382void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004383 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4384 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4385}
4386
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004387void InputDispatcher::removeMonitorChannelLocked(
4388 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004389 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004390 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004391 std::vector<Monitor>& monitors = it->second;
4392 const size_t numMonitors = monitors.size();
4393 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004394 if (monitors[i].inputChannel == inputChannel) {
4395 monitors.erase(monitors.begin() + i);
4396 break;
4397 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004398 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004399 if (monitors.empty()) {
4400 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004401 } else {
4402 ++it;
4403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 }
4405}
4406
Michael Wright3dd60e22019-03-27 22:06:44 +00004407status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4408 { // acquire lock
4409 std::scoped_lock _l(mLock);
4410 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4411
4412 if (!foundDisplayId) {
4413 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4414 return BAD_VALUE;
4415 }
4416 int32_t displayId = foundDisplayId.value();
4417
4418 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4419 if (stateIndex < 0) {
4420 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4421 return BAD_VALUE;
4422 }
4423
4424 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4425 std::optional<int32_t> foundDeviceId;
4426 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004427 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004428 foundDeviceId = state.deviceId;
4429 }
4430 }
4431 if (!foundDeviceId || !state.down) {
4432 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004433 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004434 return BAD_VALUE;
4435 }
4436 int32_t deviceId = foundDeviceId.value();
4437
4438 // Send cancel events to all the input channels we're stealing from.
4439 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004440 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004441 options.deviceId = deviceId;
4442 options.displayId = displayId;
4443 for (const TouchedWindow& window : state.windows) {
4444 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004445 if (channel != nullptr) {
4446 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4447 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004448 }
4449 // Then clear the current touch state so we stop dispatching to them as well.
4450 state.filterNonMonitors();
4451 }
4452 return OK;
4453}
4454
Michael Wright3dd60e22019-03-27 22:06:44 +00004455std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4456 const sp<IBinder>& token) {
4457 for (const auto& it : mGestureMonitorsByDisplay) {
4458 const std::vector<Monitor>& monitors = it.second;
4459 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004460 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004461 return it.first;
4462 }
4463 }
4464 }
4465 return std::nullopt;
4466}
4467
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004468sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4469 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004470 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004471 }
4472
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004473 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004474 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004475 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004476 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477 }
4478 }
Robert Carr4e670e52018-08-15 13:26:12 -07004479
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004480 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481}
4482
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004483void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4484 const sp<Connection>& connection, uint32_t seq,
4485 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004486 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4487 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488 commandEntry->connection = connection;
4489 commandEntry->eventTime = currentTime;
4490 commandEntry->seq = seq;
4491 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004492 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493}
4494
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004495void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4496 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004498 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004500 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4501 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004503 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504}
4505
chaviw0c06c6e2019-01-09 13:27:07 -08004506void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004507 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004508 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4509 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004510 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4511 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004512 commandEntry->oldToken = oldToken;
4513 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004514 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004515}
4516
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004517void InputDispatcher::onANRLocked(nsecs_t currentTime,
4518 const sp<InputApplicationHandle>& applicationHandle,
4519 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4520 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4522 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4523 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004524 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4525 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4526 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527
4528 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004529 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530 struct tm tm;
4531 localtime_r(&t, &tm);
4532 char timestr[64];
4533 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4534 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004535 mLastANRState += INDENT "ANR:\n";
4536 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004537 mLastANRState +=
4538 StringPrintf(INDENT2 "Window: %s\n",
4539 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004540 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4541 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4542 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 dumpDispatchStateLocked(mLastANRState);
4544
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004545 std::unique_ptr<CommandEntry> commandEntry =
4546 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004548 commandEntry->inputChannel =
4549 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004551 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552}
4553
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004554void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555 mLock.unlock();
4556
4557 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4558
4559 mLock.lock();
4560}
4561
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004562void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 sp<Connection> connection = commandEntry->connection;
4564
4565 if (connection->status != Connection::STATUS_ZOMBIE) {
4566 mLock.unlock();
4567
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004568 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569
4570 mLock.lock();
4571 }
4572}
4573
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004574void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004575 sp<IBinder> oldToken = commandEntry->oldToken;
4576 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004577 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004578 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004579 mLock.lock();
4580}
4581
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004582void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004583 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004584 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585 mLock.unlock();
4586
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004587 nsecs_t newTimeout =
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004588 mPolicy->notifyANR(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589
4590 mLock.lock();
4591
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004592 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593}
4594
4595void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4596 CommandEntry* commandEntry) {
4597 KeyEntry* entry = commandEntry->keyEntry;
4598
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004599 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600
4601 mLock.unlock();
4602
Michael Wright2b3c3302018-03-02 17:19:13 +00004603 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004604 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004605 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004606 : nullptr;
4607 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004608 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4609 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004610 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612
4613 mLock.lock();
4614
4615 if (delay < 0) {
4616 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4617 } else if (!delay) {
4618 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4619 } else {
4620 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4621 entry->interceptKeyWakeupTime = now() + delay;
4622 }
4623 entry->release();
4624}
4625
chaviwfd6d3512019-03-25 13:23:49 -07004626void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4627 mLock.unlock();
4628 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4629 mLock.lock();
4630}
4631
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004632void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004634 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004636 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637
4638 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004639 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004640 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004641 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004642 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004643 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004644
4645 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4646 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4647 std::string msg =
4648 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4649 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4650 dispatchEntry->eventEntry->appendDescription(msg);
4651 ALOGI("%s", msg.c_str());
4652 }
4653
4654 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004655 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004656 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4657 restartEvent =
4658 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004659 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004660 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4661 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4662 handled);
4663 } else {
4664 restartEvent = false;
4665 }
4666
4667 // Dequeue the event and start the next cycle.
4668 // Note that because the lock might have been released, it is possible that the
4669 // contents of the wait queue to have been drained, so we need to double-check
4670 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004671 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4672 if (dispatchEntryIt != connection->waitQueue.end()) {
4673 dispatchEntry = *dispatchEntryIt;
4674 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004675 traceWaitQueueLength(connection);
4676 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004677 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004678 traceOutboundQueueLength(connection);
4679 } else {
4680 releaseDispatchEntry(dispatchEntry);
4681 }
4682 }
4683
4684 // Start the next dispatch cycle for this connection.
4685 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686}
4687
4688bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004689 DispatchEntry* dispatchEntry,
4690 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004691 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004692 if (!handled) {
4693 // Report the key as unhandled, since the fallback was not handled.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004694 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004695 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004696 return false;
4697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004699 // Get the fallback key state.
4700 // Clear it out after dispatching the UP.
4701 int32_t originalKeyCode = keyEntry->keyCode;
4702 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4703 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4704 connection->inputState.removeFallbackKey(originalKeyCode);
4705 }
4706
4707 if (handled || !dispatchEntry->hasForegroundTarget()) {
4708 // If the application handles the original key for which we previously
4709 // generated a fallback or if the window is not a foreground window,
4710 // then cancel the associated fallback key, if any.
4711 if (fallbackKeyCode != -1) {
4712 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004714 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004715 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4716 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4717 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004719 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004720 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721
4722 mLock.unlock();
4723
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004724 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004725 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726
4727 mLock.lock();
4728
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004729 // Cancel the fallback key.
4730 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004732 "application handled the original non-fallback key "
4733 "or is no longer a foreground target, "
4734 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735 options.keyCode = fallbackKeyCode;
4736 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004738 connection->inputState.removeFallbackKey(originalKeyCode);
4739 }
4740 } else {
4741 // If the application did not handle a non-fallback key, first check
4742 // that we are in a good state to perform unhandled key event processing
4743 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004744 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004745 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004747 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004748 "since this is not an initial down. "
4749 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4750 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004752 return false;
4753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004755 // Dispatch the unhandled key to the policy.
4756#if DEBUG_OUTBOUND_EVENT_DETAILS
4757 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004758 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4759 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004760#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004761 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004762
4763 mLock.unlock();
4764
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004765 bool fallback =
4766 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4767 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004768
4769 mLock.lock();
4770
4771 if (connection->status != Connection::STATUS_NORMAL) {
4772 connection->inputState.removeFallbackKey(originalKeyCode);
4773 return false;
4774 }
4775
4776 // Latch the fallback keycode for this key on an initial down.
4777 // The fallback keycode cannot change at any other point in the lifecycle.
4778 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004779 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004780 fallbackKeyCode = event.getKeyCode();
4781 } else {
4782 fallbackKeyCode = AKEYCODE_UNKNOWN;
4783 }
4784 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4785 }
4786
4787 ALOG_ASSERT(fallbackKeyCode != -1);
4788
4789 // Cancel the fallback key if the policy decides not to send it anymore.
4790 // We will continue to dispatch the key to the policy but we will no
4791 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004792 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4793 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004794#if DEBUG_OUTBOUND_EVENT_DETAILS
4795 if (fallback) {
4796 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004797 "as a fallback for %d, but on the DOWN it had requested "
4798 "to send %d instead. Fallback canceled.",
4799 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004800 } else {
4801 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004802 "but on the DOWN it had requested to send %d. "
4803 "Fallback canceled.",
4804 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004805 }
4806#endif
4807
4808 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4809 "canceling fallback, policy no longer desires it");
4810 options.keyCode = fallbackKeyCode;
4811 synthesizeCancelationEventsForConnectionLocked(connection, options);
4812
4813 fallback = false;
4814 fallbackKeyCode = AKEYCODE_UNKNOWN;
4815 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004816 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004817 }
4818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819
4820#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004821 {
4822 std::string msg;
4823 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4824 connection->inputState.getFallbackKeys();
4825 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004826 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004828 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004829 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004830 }
4831#endif
4832
4833 if (fallback) {
4834 // Restart the dispatch cycle using the fallback key.
4835 keyEntry->eventTime = event.getEventTime();
4836 keyEntry->deviceId = event.getDeviceId();
4837 keyEntry->source = event.getSource();
4838 keyEntry->displayId = event.getDisplayId();
4839 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4840 keyEntry->keyCode = fallbackKeyCode;
4841 keyEntry->scanCode = event.getScanCode();
4842 keyEntry->metaState = event.getMetaState();
4843 keyEntry->repeatCount = event.getRepeatCount();
4844 keyEntry->downTime = event.getDownTime();
4845 keyEntry->syntheticRepeat = false;
4846
4847#if DEBUG_OUTBOUND_EVENT_DETAILS
4848 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004849 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4850 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004851#endif
4852 return true; // restart the event
4853 } else {
4854#if DEBUG_OUTBOUND_EVENT_DETAILS
4855 ALOGD("Unhandled key event: No fallback key.");
4856#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004857
4858 // Report the key as unhandled, since there is no fallback key.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004859 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 }
4861 }
4862 return false;
4863}
4864
4865bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004866 DispatchEntry* dispatchEntry,
4867 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 return false;
4869}
4870
4871void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4872 mLock.unlock();
4873
4874 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4875
4876 mLock.lock();
4877}
4878
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004879KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4880 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004881 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08004882 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
4883 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004884 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885}
4886
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004887void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004888 int32_t injectionResult,
4889 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 // TODO Write some statistics about how long we spend waiting.
4891}
4892
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004893/**
4894 * Report the touch event latency to the statsd server.
4895 * Input events are reported for statistics if:
4896 * - This is a touchscreen event
4897 * - InputFilter is not enabled
4898 * - Event is not injected or synthesized
4899 *
4900 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4901 * from getting aggregated with the "old" data.
4902 */
4903void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4904 REQUIRES(mLock) {
4905 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4906 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4907 if (!reportForStatistics) {
4908 return;
4909 }
4910
4911 if (mTouchStatistics.shouldReport()) {
4912 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4913 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4914 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4915 mTouchStatistics.reset();
4916 }
4917 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4918 mTouchStatistics.addValue(latencyMicros);
4919}
4920
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921void InputDispatcher::traceInboundQueueLengthLocked() {
4922 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004923 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 }
4925}
4926
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004927void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 if (ATRACE_ENABLED()) {
4929 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004930 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004931 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932 }
4933}
4934
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004935void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936 if (ATRACE_ENABLED()) {
4937 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004938 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004939 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940 }
4941}
4942
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004943void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004944 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004946 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947 dumpDispatchStateLocked(dump);
4948
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004949 if (!mLastANRState.empty()) {
4950 dump += "\nInput Dispatcher State at time of last ANR:\n";
4951 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952 }
4953}
4954
4955void InputDispatcher::monitor() {
4956 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004957 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004959 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960}
4961
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004962/**
4963 * Wake up the dispatcher and wait until it processes all events and commands.
4964 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4965 * this method can be safely called from any thread, as long as you've ensured that
4966 * the work you are interested in completing has already been queued.
4967 */
4968bool InputDispatcher::waitForIdle() {
4969 /**
4970 * Timeout should represent the longest possible time that a device might spend processing
4971 * events and commands.
4972 */
4973 constexpr std::chrono::duration TIMEOUT = 100ms;
4974 std::unique_lock lock(mLock);
4975 mLooper->wake();
4976 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4977 return result == std::cv_status::no_timeout;
4978}
4979
Garfield Tane84e6f92019-08-29 17:28:41 -07004980} // namespace android::inputdispatcher