blob: bcfc7acdf971c9b2705310a41ef0b8b3649a4291 [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 }
Gang Wang342c9272020-01-13 13:15:04 -0500355 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700356 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500357}
358
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700359std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500360 // SHA256 always generates 32-bytes result
361 std::array<uint8_t, 32> hash;
362 unsigned int hashLen = 0;
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700363 uint8_t* result =
364 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500365 if (result == nullptr) {
366 ALOGE("Could not sign the data using HMAC");
367 return INVALID_HMAC;
368 }
369
370 if (hashLen != hash.size()) {
371 ALOGE("HMAC-SHA256 has unexpected length");
372 return INVALID_HMAC;
373 }
374
375 return hash;
376}
377
Michael Wrightd02c5b62014-02-10 15:10:22 -0800378// --- InputDispatcher ---
379
Garfield Tan00f511d2019-06-12 16:55:40 -0700380InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
381 : mPolicy(policy),
382 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700383 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tan1c7bc862020-01-28 13:24:04 -0800384 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700385 mAppSwitchSawKeyDown(false),
386 mAppSwitchDueTime(LONG_LONG_MAX),
387 mNextUnblockedEvent(nullptr),
388 mDispatchEnabled(false),
389 mDispatchFrozen(false),
390 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800391 // mInTouchMode will be initialized by the WindowManager to the default device config.
392 // To avoid leaking stack in case that call never comes, and for tests,
393 // initialize it here anyways.
394 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700395 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
396 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800397 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800398 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800399
Yi Kong9b14ac62018-07-17 13:48:38 -0700400 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800401
402 policy->getDispatcherConfiguration(&mConfig);
403}
404
405InputDispatcher::~InputDispatcher() {
406 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800407 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800408
409 resetKeyRepeatLocked();
410 releasePendingEventLocked();
411 drainInboundQueueLocked();
412 }
413
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700414 while (!mConnectionsByFd.empty()) {
415 sp<Connection> connection = mConnectionsByFd.begin()->second;
416 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417 }
418}
419
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700420status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700421 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700422 return ALREADY_EXISTS;
423 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700424 mThread = std::make_unique<InputThread>(
425 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
426 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700427}
428
429status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700430 if (mThread && mThread->isCallingThread()) {
431 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700432 return INVALID_OPERATION;
433 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700434 mThread.reset();
435 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700436}
437
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438void InputDispatcher::dispatchOnce() {
439 nsecs_t nextWakeupTime = LONG_LONG_MAX;
440 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800441 std::scoped_lock _l(mLock);
442 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800443
444 // Run a dispatch loop if there are no pending commands.
445 // The dispatch loop might enqueue commands to run afterwards.
446 if (!haveCommandsLocked()) {
447 dispatchOnceInnerLocked(&nextWakeupTime);
448 }
449
450 // Run all pending commands if there are any.
451 // If any commands were run then force the next poll to wake up immediately.
452 if (runCommandsLockedInterruptible()) {
453 nextWakeupTime = LONG_LONG_MIN;
454 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800455
456 // We are about to enter an infinitely long sleep, because we have no commands or
457 // pending or queued events
458 if (nextWakeupTime == LONG_LONG_MAX) {
459 mDispatcherEnteredIdle.notify_all();
460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461 } // release lock
462
463 // Wait for callback or timeout or wake. (make sure we round up, not down)
464 nsecs_t currentTime = now();
465 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
466 mLooper->pollOnce(timeoutMillis);
467}
468
469void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
470 nsecs_t currentTime = now();
471
Jeff Browndc5992e2014-04-11 01:27:26 -0700472 // Reset the key repeat timer whenever normal dispatch is suspended while the
473 // device is in a non-interactive state. This is to ensure that we abort a key
474 // repeat if the device is just coming out of sleep.
475 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800476 resetKeyRepeatLocked();
477 }
478
479 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
480 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100481 if (DEBUG_FOCUS) {
482 ALOGD("Dispatch frozen. Waiting some more.");
483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800484 return;
485 }
486
487 // Optimize latency of app switches.
488 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
489 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
490 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
491 if (mAppSwitchDueTime < *nextWakeupTime) {
492 *nextWakeupTime = mAppSwitchDueTime;
493 }
494
495 // Ready to start a new event.
496 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700497 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700498 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499 if (isAppSwitchDue) {
500 // The inbound queue is empty so the app switch key we were waiting
501 // for will never arrive. Stop waiting for it.
502 resetPendingAppSwitchLocked(false);
503 isAppSwitchDue = false;
504 }
505
506 // Synthesize a key repeat if appropriate.
507 if (mKeyRepeatState.lastKeyEntry) {
508 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
509 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
510 } else {
511 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
512 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
513 }
514 }
515 }
516
517 // Nothing to do if there is no pending event.
518 if (!mPendingEvent) {
519 return;
520 }
521 } else {
522 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700523 mPendingEvent = mInboundQueue.front();
524 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525 traceInboundQueueLengthLocked();
526 }
527
528 // Poke user activity for this event.
529 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700530 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531 }
532
533 // Get ready to dispatch the event.
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700534 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535 }
536
537 // Now we have an event to dispatch.
538 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700539 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700541 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800542 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700543 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700545 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800546 }
547
548 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700549 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 }
551
552 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700553 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700554 ConfigurationChangedEntry* typedEntry =
555 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
556 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700557 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700558 break;
559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700561 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700562 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
563 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700564 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700565 break;
566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100568 case EventEntry::Type::FOCUS: {
569 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
570 dispatchFocusLocked(currentTime, typedEntry);
571 done = true;
572 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
573 break;
574 }
575
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700576 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700577 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
578 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700579 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700580 resetPendingAppSwitchLocked(true);
581 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700582 } else if (dropReason == DropReason::NOT_DROPPED) {
583 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700584 }
585 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700586 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700587 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700588 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700589 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
590 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700591 }
592 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
593 break;
594 }
595
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700596 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700597 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700598 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
599 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700601 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700602 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700603 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700604 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
605 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700606 }
607 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
608 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610 }
611
612 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700613 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700614 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800615 }
Michael Wright3a981722015-06-10 15:26:13 +0100616 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617
618 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700619 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800620 }
621}
622
623bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700624 bool needWake = mInboundQueue.empty();
625 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 traceInboundQueueLengthLocked();
627
628 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700629 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700630 // Optimize app switch latency.
631 // If the application takes too long to catch up then we drop all events preceding
632 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700633 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700634 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700635 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700636 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700637 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700638 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700640 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800641#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700642 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700643 mAppSwitchSawKeyDown = false;
644 needWake = true;
645 }
646 }
647 }
648 break;
649 }
650
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700651 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700652 // Optimize case where the current application is unresponsive and the user
653 // decides to touch a window in a different application.
654 // If the application takes too long to catch up then we drop all events preceding
655 // the touch into the other window.
656 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
657 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
658 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
659 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
660 mInputTargetWaitApplicationToken != nullptr) {
661 int32_t displayId = motionEntry->displayId;
662 int32_t x =
663 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
664 int32_t y =
665 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
666 sp<InputWindowHandle> touchedWindowHandle =
667 findTouchedWindowAtLocked(displayId, x, y);
668 if (touchedWindowHandle != nullptr &&
669 touchedWindowHandle->getApplicationToken() !=
670 mInputTargetWaitApplicationToken) {
671 // User touched a different application than the one we are waiting on.
672 // Flag the event, and start pruning the input queue.
673 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 needWake = true;
675 }
676 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700677 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700679 case EventEntry::Type::CONFIGURATION_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100680 case EventEntry::Type::DEVICE_RESET:
681 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700682 // nothing to do
683 break;
684 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685 }
686
687 return needWake;
688}
689
690void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
691 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700692 mRecentQueue.push_back(entry);
693 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
694 mRecentQueue.front()->release();
695 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696 }
697}
698
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700699sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
700 int32_t y, bool addOutsideTargets,
701 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800703 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
704 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 const InputWindowInfo* windowInfo = windowHandle->getInfo();
706 if (windowInfo->displayId == displayId) {
707 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708
709 if (windowInfo->visible) {
710 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700711 bool isTouchModal = (flags &
712 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
713 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800715 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700716 if (portalToDisplayId != ADISPLAY_ID_NONE &&
717 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800718 if (addPortalWindows) {
719 // For the monitoring channels of the display.
720 mTempTouchState.addPortalWindow(windowHandle);
721 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700722 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
723 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725 // Found window.
726 return windowHandle;
727 }
728 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800729
730 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700731 mTempTouchState.addOrUpdateWindow(windowHandle,
732 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
733 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800734 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736 }
737 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700738 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739}
740
Garfield Tane84e6f92019-08-29 17:28:41 -0700741std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000742 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
743 std::vector<TouchedMonitor> touchedMonitors;
744
745 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
746 addGestureMonitors(monitors, touchedMonitors);
747 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
748 const InputWindowInfo* windowInfo = portalWindow->getInfo();
749 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700750 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
751 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000752 }
753 return touchedMonitors;
754}
755
756void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700757 std::vector<TouchedMonitor>& outTouchedMonitors,
758 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000759 if (monitors.empty()) {
760 return;
761 }
762 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
763 for (const Monitor& monitor : monitors) {
764 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
765 }
766}
767
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700768void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800769 const char* reason;
770 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700771 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700773 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700775 reason = "inbound event was dropped because the policy consumed it";
776 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700777 case DropReason::DISABLED:
778 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700779 ALOGI("Dropped event because input dispatch is disabled.");
780 }
781 reason = "inbound event was dropped because input dispatch is disabled";
782 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700783 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700784 ALOGI("Dropped event because of pending overdue app switch.");
785 reason = "inbound event was dropped because of pending overdue app switch";
786 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700787 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700788 ALOGI("Dropped event because the current application is not responding and the user "
789 "has started interacting with a different application.");
790 reason = "inbound event was dropped because the current application is not responding "
791 "and the user has started interacting with a different application";
792 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700793 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700794 ALOGI("Dropped event because it is stale.");
795 reason = "inbound event was dropped because it is stale";
796 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700797 case DropReason::NOT_DROPPED: {
798 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700799 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
802
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700803 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700804 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
806 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700807 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700809 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700810 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
811 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
813 synthesizeCancelationEventsForAllConnectionsLocked(options);
814 } else {
815 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
816 synthesizeCancelationEventsForAllConnectionsLocked(options);
817 }
818 break;
819 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100820 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700821 case EventEntry::Type::CONFIGURATION_CHANGED:
822 case EventEntry::Type::DEVICE_RESET: {
823 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
824 break;
825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826 }
827}
828
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800829static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700830 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
831 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800832}
833
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700834bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
835 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
836 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
837 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838}
839
840bool InputDispatcher::isAppSwitchPendingLocked() {
841 return mAppSwitchDueTime != LONG_LONG_MAX;
842}
843
844void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
845 mAppSwitchDueTime = LONG_LONG_MAX;
846
847#if DEBUG_APP_SWITCH
848 if (handled) {
849 ALOGD("App switch has arrived.");
850 } else {
851 ALOGD("App switch was abandoned.");
852 }
853#endif
854}
855
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700857 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858}
859
860bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700861 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 return false;
863 }
864
865 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700866 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700867 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700869 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870
871 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700872 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 return true;
874}
875
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700876void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
877 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878}
879
880void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700881 while (!mInboundQueue.empty()) {
882 EventEntry* entry = mInboundQueue.front();
883 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 releaseInboundEventLocked(entry);
885 }
886 traceInboundQueueLengthLocked();
887}
888
889void InputDispatcher::releasePendingEventLocked() {
890 if (mPendingEvent) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700891 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700893 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 }
895}
896
897void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
898 InjectionState* injectionState = entry->injectionState;
899 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
900#if DEBUG_DISPATCH_CYCLE
901 ALOGD("Injected inbound event was dropped.");
902#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800903 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
905 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700906 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 }
908 addRecentEventLocked(entry);
909 entry->release();
910}
911
912void InputDispatcher::resetKeyRepeatLocked() {
913 if (mKeyRepeatState.lastKeyEntry) {
914 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700915 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916 }
917}
918
Garfield Tane84e6f92019-08-29 17:28:41 -0700919KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
921
922 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700923 uint32_t policyFlags = entry->policyFlags &
924 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 if (entry->refCount == 1) {
926 entry->recycle();
Garfield Tan1c7bc862020-01-28 13:24:04 -0800927 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 entry->eventTime = currentTime;
929 entry->policyFlags = policyFlags;
930 entry->repeatCount += 1;
931 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700932 KeyEntry* newEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -0800933 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800934 entry->displayId, policyFlags, entry->action, entry->flags,
935 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700936 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937
938 mKeyRepeatState.lastKeyEntry = newEntry;
939 entry->release();
940
941 entry = newEntry;
942 }
943 entry->syntheticRepeat = true;
944
945 // Increment reference count since we keep a reference to the event in
946 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
947 entry->refCount += 1;
948
949 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
950 return entry;
951}
952
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700953bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
954 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700956 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957#endif
958
959 // Reset key repeating in case a keyboard device was added or removed or something.
960 resetKeyRepeatLocked();
961
962 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700963 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
964 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700966 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 return true;
968}
969
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700970bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700972 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700973 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974#endif
975
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700976 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 options.deviceId = entry->deviceId;
978 synthesizeCancelationEventsForAllConnectionsLocked(options);
979 return true;
980}
981
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100982void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
983 FocusEntry* focusEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -0800984 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100985 enqueueInboundEventLocked(focusEntry);
986}
987
988void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
989 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
990 if (channel == nullptr) {
991 return; // Window has gone away
992 }
993 InputTarget target;
994 target.inputChannel = channel;
995 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
996 entry->dispatchInProgress = true;
997
998 dispatchEventLocked(currentTime, entry, {target});
999}
1000
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001002 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001004 if (!entry->dispatchInProgress) {
1005 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1006 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1007 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1008 if (mKeyRepeatState.lastKeyEntry &&
1009 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 // We have seen two identical key downs in a row which indicates that the device
1011 // driver is automatically generating key repeats itself. We take note of the
1012 // repeat here, but we disable our own next key repeat timer since it is clear that
1013 // we will not need to synthesize key repeats ourselves.
1014 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1015 resetKeyRepeatLocked();
1016 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1017 } else {
1018 // Not a repeat. Save key down state in case we do see a repeat later.
1019 resetKeyRepeatLocked();
1020 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1021 }
1022 mKeyRepeatState.lastKeyEntry = entry;
1023 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001024 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 resetKeyRepeatLocked();
1026 }
1027
1028 if (entry->repeatCount == 1) {
1029 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1030 } else {
1031 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1032 }
1033
1034 entry->dispatchInProgress = true;
1035
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001036 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 }
1038
1039 // Handle case where the policy asked us to try again later last time.
1040 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1041 if (currentTime < entry->interceptKeyWakeupTime) {
1042 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1043 *nextWakeupTime = entry->interceptKeyWakeupTime;
1044 }
1045 return false; // wait until next wakeup
1046 }
1047 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1048 entry->interceptKeyWakeupTime = 0;
1049 }
1050
1051 // Give the policy a chance to intercept the key.
1052 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1053 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001054 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001055 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001056 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001057 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001058 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001059 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 }
1061 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001062 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 entry->refCount += 1;
1064 return false; // wait for the command to run
1065 } else {
1066 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1067 }
1068 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001069 if (*dropReason == DropReason::NOT_DROPPED) {
1070 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 }
1072 }
1073
1074 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001075 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001076 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001077 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001079 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 return true;
1081 }
1082
1083 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001084 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001086 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1088 return false;
1089 }
1090
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001091 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1093 return true;
1094 }
1095
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001096 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001097 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001098
1099 // Dispatch the key.
1100 dispatchEventLocked(currentTime, entry, inputTargets);
1101 return true;
1102}
1103
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001104void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001106 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001107 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1108 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001109 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1110 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1111 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112#endif
1113}
1114
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001115bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1116 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001117 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001119 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 entry->dispatchInProgress = true;
1121
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001122 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 }
1124
1125 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001126 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001127 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001128 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 return true;
1131 }
1132
1133 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1134
1135 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001136 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137
1138 bool conflictingPointerActions = false;
1139 int32_t injectionResult;
1140 if (isPointerEvent) {
1141 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001142 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001143 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001144 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145 } else {
1146 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001147 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001148 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 }
1150 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1151 return false;
1152 }
1153
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001154 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001155 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1156 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1157 return true;
1158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001160 CancelationOptions::Mode mode(isPointerEvent
1161 ? CancelationOptions::CANCEL_POINTER_EVENTS
1162 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1163 CancelationOptions options(mode, "input event injection failed");
1164 synthesizeCancelationEventsForMonitorsLocked(options);
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 Vishniakoub1a16272020-05-06 16:09:19 -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
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001350void InputDispatcher::resetAnrTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001351 if (DEBUG_FOCUS) {
1352 ALOGD("Resetting ANR timeouts.");
1353 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354
1355 // Reset input target wait timeout.
1356 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001357 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358}
1359
Tiger Huang721e26f2018-07-24 22:26:19 +08001360/**
1361 * Get the display id that the given event should go to. If this event specifies a valid display id,
1362 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1363 * Focused display is the display that the user most recently interacted with.
1364 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001365int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001366 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001367 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001368 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001369 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1370 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001371 break;
1372 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001373 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001374 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1375 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001376 break;
1377 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001378 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001379 case EventEntry::Type::CONFIGURATION_CHANGED:
1380 case EventEntry::Type::DEVICE_RESET: {
1381 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001382 return ADISPLAY_ID_NONE;
1383 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001384 }
1385 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1386}
1387
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001389 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001390 std::vector<InputTarget>& inputTargets,
1391 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001392 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393
Tiger Huang721e26f2018-07-24 22:26:19 +08001394 int32_t displayId = getTargetDisplayId(entry);
1395 sp<InputWindowHandle> focusedWindowHandle =
1396 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1397 sp<InputApplicationHandle> focusedApplicationHandle =
1398 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1399
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 // If there is no currently focused window and no focused application
1401 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001402 if (focusedWindowHandle == nullptr) {
1403 if (focusedApplicationHandle != nullptr) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001404 return handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1405 nullptr, nextWakeupTime,
1406 "Waiting because no window has focus but there is "
1407 "a focused application that may eventually add a "
1408 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001409 }
1410
Arthur Hung3b413f22018-10-26 18:05:34 +08001411 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001412 "%" PRId32 ".",
1413 displayId);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001414 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 }
1416
1417 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001418 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001419 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420 }
1421
Jeff Brownffb49772014-10-10 19:01:34 -07001422 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001423 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001424 if (!reason.empty()) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001425 return handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1426 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 }
1428
1429 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001430 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001431 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1432 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433
1434 // Done.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001435 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436}
1437
1438int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001439 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001440 std::vector<InputTarget>& inputTargets,
1441 nsecs_t* nextWakeupTime,
1442 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001443 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 enum InjectionPermission {
1445 INJECTION_PERMISSION_UNKNOWN,
1446 INJECTION_PERMISSION_GRANTED,
1447 INJECTION_PERMISSION_DENIED
1448 };
1449
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450 // For security reasons, we defer updating the touch state until we are sure that
1451 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001452 int32_t displayId = entry.displayId;
1453 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1455
1456 // Update the touch state as needed based on the properties of the touch event.
1457 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1458 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1459 sp<InputWindowHandle> newHoverWindowHandle;
1460
Jeff Brownf086ddb2014-02-11 14:28:48 -08001461 // Copy current touch state into mTempTouchState.
1462 // This state is always reset at the end of this function, so if we don't find state
1463 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001464 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001465 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1466 if (oldStateIndex >= 0) {
1467 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1468 mTempTouchState.copyFrom(*oldState);
1469 }
1470
1471 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001472 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001473 (mTempTouchState.deviceId != entry.deviceId || mTempTouchState.source != entry.source ||
1474 mTempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001475 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1476 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1477 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1478 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1479 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001480 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481 bool wrongDevice = false;
1482 if (newGesture) {
1483 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001484 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001485 if (DEBUG_FOCUS) {
1486 ALOGD("Dropping event because a pointer for a different device is already down "
1487 "in display %" PRId32,
1488 displayId);
1489 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001490 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1492 switchedDevice = false;
1493 wrongDevice = true;
1494 goto Failed;
1495 }
1496 mTempTouchState.reset();
1497 mTempTouchState.down = down;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001498 mTempTouchState.deviceId = entry.deviceId;
1499 mTempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 mTempTouchState.displayId = displayId;
1501 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001502 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001503 if (DEBUG_FOCUS) {
1504 ALOGI("Dropping move event because a pointer for a different device is already active "
1505 "in display %" PRId32,
1506 displayId);
1507 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001508 // TODO: test multiple simultaneous input streams.
1509 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1510 switchedDevice = false;
1511 wrongDevice = true;
1512 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 }
1514
1515 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1516 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1517
Garfield Tan00f511d2019-06-12 16:55:40 -07001518 int32_t x;
1519 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001521 // Always dispatch mouse events to cursor position.
1522 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001523 x = int32_t(entry.xCursorPosition);
1524 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001525 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001526 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1527 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001528 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001529 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001530 sp<InputWindowHandle> newTouchedWindowHandle =
1531 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1532 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001533
1534 std::vector<TouchedMonitor> newGestureMonitors = isDown
1535 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1536 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001539 if (newTouchedWindowHandle != nullptr &&
1540 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001541 // New window supports splitting, but we should never split mouse events.
1542 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 } else if (isSplit) {
1544 // New window does not support splitting but we have already split events.
1545 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001546 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 }
1548
1549 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001550 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 // Try to assign the pointer to the first foreground window we find, if there is one.
1552 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001553 }
1554
1555 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1556 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001557 "(%d, %d) in display %" PRId32 ".",
1558 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001559 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1560 goto Failed;
1561 }
1562
1563 if (newTouchedWindowHandle != nullptr) {
1564 // Set target flags.
1565 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1566 if (isSplit) {
1567 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001569 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1570 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1571 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1572 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1573 }
1574
1575 // Update hover state.
1576 if (isHoverAction) {
1577 newHoverWindowHandle = newTouchedWindowHandle;
1578 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1579 newHoverWindowHandle = mLastHoverWindowHandle;
1580 }
1581
1582 // Update the temporary touch state.
1583 BitSet32 pointerIds;
1584 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001585 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001586 pointerIds.markBit(pointerId);
1587 }
1588 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589 }
1590
Michael Wright3dd60e22019-03-27 22:06:44 +00001591 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 } else {
1593 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1594
1595 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001596 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001597 if (DEBUG_FOCUS) {
1598 ALOGD("Dropping event because the pointer is not down or we previously "
1599 "dropped the pointer down event in display %" PRId32,
1600 displayId);
1601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1603 goto Failed;
1604 }
1605
1606 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001607 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001608 mTempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001609 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1610 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611
1612 sp<InputWindowHandle> oldTouchedWindowHandle =
1613 mTempTouchState.getFirstForegroundWindowHandle();
1614 sp<InputWindowHandle> newTouchedWindowHandle =
1615 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001616 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1617 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001618 if (DEBUG_FOCUS) {
1619 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1620 oldTouchedWindowHandle->getName().c_str(),
1621 newTouchedWindowHandle->getName().c_str(), displayId);
1622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 // Make a slippery exit from the old window.
1624 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001625 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1626 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627
1628 // Make a slippery entrance into the new window.
1629 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1630 isSplit = true;
1631 }
1632
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001633 int32_t targetFlags =
1634 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 if (isSplit) {
1636 targetFlags |= InputTarget::FLAG_SPLIT;
1637 }
1638 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1639 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1640 }
1641
1642 BitSet32 pointerIds;
1643 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001644 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 }
1646 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1647 }
1648 }
1649 }
1650
1651 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1652 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001653 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654#if DEBUG_HOVER
1655 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001656 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657#endif
1658 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001659 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1660 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 }
1662
1663 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001664 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665#if DEBUG_HOVER
1666 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001667 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668#endif
1669 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001670 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1671 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 }
1673 }
1674
1675 // Check permission to inject into all touched foreground windows and ensure there
1676 // is at least one touched foreground window.
1677 {
1678 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001679 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1681 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001682 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1684 injectionPermission = INJECTION_PERMISSION_DENIED;
1685 goto Failed;
1686 }
1687 }
1688 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001689 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1690 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001691 if (DEBUG_FOCUS) {
1692 ALOGD("Dropping event because there is no touched foreground window in display "
1693 "%" PRId32 " or gesture monitor to receive it.",
1694 displayId);
1695 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1697 goto Failed;
1698 }
1699
1700 // Permission granted to injection into all touched foreground windows.
1701 injectionPermission = INJECTION_PERMISSION_GRANTED;
1702 }
1703
1704 // Check whether windows listening for outside touches are owned by the same UID. If it is
1705 // set the policy flag that we will not reveal coordinate information to this window.
1706 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1707 sp<InputWindowHandle> foregroundWindowHandle =
1708 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001709 if (foregroundWindowHandle) {
1710 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1711 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1712 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1713 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1714 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1715 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001716 InputTarget::FLAG_ZERO_COORDS,
1717 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 }
1720 }
1721 }
1722 }
1723
1724 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001725 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001727 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001728 std::string reason =
1729 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1730 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001731 if (!reason.empty()) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001732 return handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1733 touchedWindow.windowHandle, nextWakeupTime,
1734 reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735 }
1736 }
1737 }
1738
1739 // If this is the first pointer going down and the touched window has a wallpaper
1740 // then also add the touched wallpaper windows so they are locked in for the duration
1741 // of the touch gesture.
1742 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1743 // engine only supports touch events. We would need to add a mechanism similar
1744 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1745 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1746 sp<InputWindowHandle> foregroundWindowHandle =
1747 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001748 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001749 const std::vector<sp<InputWindowHandle>> windowHandles =
1750 getWindowHandlesLocked(displayId);
1751 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001753 if (info->displayId == displayId &&
1754 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1755 mTempTouchState
1756 .addOrUpdateWindow(windowHandle,
1757 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1758 InputTarget::
1759 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1760 InputTarget::FLAG_DISPATCH_AS_IS,
1761 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 }
1763 }
1764 }
1765 }
1766
1767 // Success! Output targets.
1768 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1769
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001770 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001772 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 }
1774
Michael Wright3dd60e22019-03-27 22:06:44 +00001775 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1776 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001777 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001778 }
1779
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 // Drop the outside or hover touch windows since we will not care about them
1781 // in the next iteration.
1782 mTempTouchState.filterNonAsIsTouchWindows();
1783
1784Failed:
1785 // Check injection permission once and for all.
1786 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001787 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 injectionPermission = INJECTION_PERMISSION_GRANTED;
1789 } else {
1790 injectionPermission = INJECTION_PERMISSION_DENIED;
1791 }
1792 }
1793
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001794 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1795 return injectionResult;
1796 }
1797
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001799 if (!wrongDevice) {
1800 if (switchedDevice) {
1801 if (DEBUG_FOCUS) {
1802 ALOGD("Conflicting pointer actions: Switched to a different device.");
1803 }
1804 *outConflictingPointerActions = true;
1805 }
1806
1807 if (isHoverAction) {
1808 // Started hovering, therefore no longer down.
1809 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001810 if (DEBUG_FOCUS) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001811 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1812 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 *outConflictingPointerActions = true;
1815 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001816 mTempTouchState.reset();
1817 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1818 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1819 mTempTouchState.deviceId = entry.deviceId;
1820 mTempTouchState.source = entry.source;
1821 mTempTouchState.displayId = displayId;
1822 }
1823 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1824 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1825 // All pointers up or canceled.
1826 mTempTouchState.reset();
1827 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1828 // First pointer went down.
1829 if (oldState && oldState->down) {
1830 if (DEBUG_FOCUS) {
1831 ALOGD("Conflicting pointer actions: Down received while already down.");
1832 }
1833 *outConflictingPointerActions = true;
1834 }
1835 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1836 // One pointer went up.
1837 if (isSplit) {
1838 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1839 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001841 for (size_t i = 0; i < mTempTouchState.windows.size();) {
1842 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1843 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1844 touchedWindow.pointerIds.clearBit(pointerId);
1845 if (touchedWindow.pointerIds.isEmpty()) {
1846 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
1847 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001850 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001852 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001853 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001854
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001855 // Save changes unless the action was scroll in which case the temporary touch
1856 // state was only valid for this one action.
1857 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1858 if (mTempTouchState.displayId >= 0) {
1859 if (oldStateIndex >= 0) {
1860 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1861 } else {
1862 mTouchStatesByDisplay.add(displayId, mTempTouchState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001863 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001864 } else if (oldStateIndex >= 0) {
1865 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001869 // Update hover state.
1870 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 }
1872
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 return injectionResult;
1874}
1875
1876void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001877 int32_t targetFlags, BitSet32 pointerIds,
1878 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001879 std::vector<InputTarget>::iterator it =
1880 std::find_if(inputTargets.begin(), inputTargets.end(),
1881 [&windowHandle](const InputTarget& inputTarget) {
1882 return inputTarget.inputChannel->getConnectionToken() ==
1883 windowHandle->getToken();
1884 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00001885
Chavi Weingarten114b77f2020-01-15 22:35:10 +00001886 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001887
1888 if (it == inputTargets.end()) {
1889 InputTarget inputTarget;
1890 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1891 if (inputChannel == nullptr) {
1892 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1893 return;
1894 }
1895 inputTarget.inputChannel = inputChannel;
1896 inputTarget.flags = targetFlags;
1897 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
1898 inputTargets.push_back(inputTarget);
1899 it = inputTargets.end() - 1;
1900 }
1901
1902 ALOG_ASSERT(it->flags == targetFlags);
1903 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
1904
1905 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
1906 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907}
1908
Michael Wright3dd60e22019-03-27 22:06:44 +00001909void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001910 int32_t displayId, float xOffset,
1911 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001912 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1913 mGlobalMonitorsByDisplay.find(displayId);
1914
1915 if (it != mGlobalMonitorsByDisplay.end()) {
1916 const std::vector<Monitor>& monitors = it->second;
1917 for (const Monitor& monitor : monitors) {
1918 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920 }
1921}
1922
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001923void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1924 float yOffset,
1925 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001926 InputTarget target;
1927 target.inputChannel = monitor.inputChannel;
1928 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001929 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00001930 inputTargets.push_back(target);
1931}
1932
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001934 const InjectionState* injectionState) {
1935 if (injectionState &&
1936 (windowHandle == nullptr ||
1937 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1938 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001939 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001941 "owned by uid %d",
1942 injectionState->injectorPid, injectionState->injectorUid,
1943 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 } else {
1945 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001946 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947 }
1948 return false;
1949 }
1950 return true;
1951}
1952
Robert Carr9cada032020-04-13 17:21:08 -07001953/**
1954 * Indicate whether one window handle should be considered as obscuring
1955 * another window handle. We only check a few preconditions. Actually
1956 * checking the bounds is left to the caller.
1957 */
1958static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
1959 const sp<InputWindowHandle>& otherHandle) {
1960 // Compare by token so cloned layers aren't counted
1961 if (haveSameToken(windowHandle, otherHandle)) {
1962 return false;
1963 }
1964 auto info = windowHandle->getInfo();
1965 auto otherInfo = otherHandle->getInfo();
1966 if (!otherInfo->visible) {
1967 return false;
1968 } else if (info->ownerPid == otherInfo->ownerPid && otherHandle->getToken() == nullptr) {
1969 // In general, if ownerPid is the same we don't want to generate occlusion
1970 // events. This line is now necessary since we are including all Surfaces
1971 // in occlusion calculation, so if we didn't check PID like this SurfaceView
1972 // would occlude their parents. On the other hand before we started including
1973 // all surfaces in occlusion calculation and had this line, we would count
1974 // windows with an input channel from the same PID as occluding, and so we
1975 // preserve this behavior with the getToken() == null check.
1976 return false;
1977 } else if (otherInfo->isTrustedOverlay()) {
1978 return false;
1979 } else if (otherInfo->displayId != info->displayId) {
1980 return false;
1981 }
1982 return true;
1983}
1984
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001985bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1986 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001988 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1989 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07001990 if (windowHandle == otherHandle) {
1991 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07001994 if (canBeObscuredBy(windowHandle, otherHandle) &&
1995 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996 return true;
1997 }
1998 }
1999 return false;
2000}
2001
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002002bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2003 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002004 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002005 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002006 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002007 if (windowHandle == otherHandle) {
2008 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002009 }
2010
2011 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002012 if (canBeObscuredBy(windowHandle, otherHandle) &&
2013 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002014 return true;
2015 }
2016 }
2017 return false;
2018}
2019
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002020std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
2021 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002022 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07002023 // If the window is paused then keep waiting.
2024 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002025 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002026 }
2027
2028 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07002029 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002030 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002031 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002032 "registered with the input dispatcher. The window may be in the "
2033 "process of being removed.",
2034 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002035 }
2036
2037 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07002038 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002039 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002040 "The window may be in the process of being removed.",
2041 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07002042 }
2043
2044 // If the connection is backed up then keep waiting.
2045 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002046 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002047 "Outbound queue length: %zu. Wait queue length: %zu.",
2048 targetType, connection->outboundQueue.size(),
2049 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07002050 }
2051
2052 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002053 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07002054 // If the event is a key event, then we must wait for all previous events to
2055 // complete before delivering it because previous events may have the
2056 // side-effect of transferring focus to a different window and we want to
2057 // ensure that the following keys are sent to the new window.
2058 //
2059 // Suppose the user touches a button in a window then immediately presses "A".
2060 // If the button causes a pop-up window to appear then we want to ensure that
2061 // the "A" key is delivered to the new pop-up window. This is because users
2062 // often anticipate pending UI changes when typing on a keyboard.
2063 // To obtain this behavior, we must serialize key events with respect to all
2064 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002065 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002066 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002067 "finished processing all of the input events that were previously "
2068 "delivered to it. Outbound queue length: %zu. Wait queue length: "
2069 "%zu.",
2070 targetType, connection->outboundQueue.size(),
2071 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 }
Jeff Brownffb49772014-10-10 19:01:34 -07002073 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074 // Touch events can always be sent to a window immediately because the user intended
2075 // to touch whatever was visible at the time. Even if focus changes or a new
2076 // window appears moments later, the touch event was meant to be delivered to
2077 // whatever window happened to be on screen at the time.
2078 //
2079 // Generic motion events, such as trackball or joystick events are a little trickier.
2080 // Like key events, generic motion events are delivered to the focused window.
2081 // Unlike key events, generic motion events don't tend to transfer focus to other
2082 // windows and it is not important for them to be serialized. So we prefer to deliver
2083 // generic motion events as soon as possible to improve efficiency and reduce lag
2084 // through batching.
2085 //
2086 // The one case where we pause input event delivery is when the wait queue is piling
2087 // up with lots of events because the application is not responding.
2088 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002089 if (!connection->waitQueue.empty() &&
2090 currentTime >=
2091 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002092 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002093 "finished processing certain input events that were delivered to "
2094 "it over "
2095 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
2096 "%0.1fms.",
2097 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
2098 connection->waitQueue.size(),
2099 (currentTime - connection->waitQueue.front()->deliveryTime) *
2100 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 }
2102 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002103 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104}
2105
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002106std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 const sp<InputApplicationHandle>& applicationHandle,
2108 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002109 if (applicationHandle != nullptr) {
2110 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002111 std::string label(applicationHandle->getName());
2112 label += " - ";
2113 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 return label;
2115 } else {
2116 return applicationHandle->getName();
2117 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002118 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119 return windowHandle->getName();
2120 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002121 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122 }
2123}
2124
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002125void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002126 if (eventEntry.type == EventEntry::Type::FOCUS) {
2127 // Focus events are passed to apps, but do not represent user activity.
2128 return;
2129 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002130 int32_t displayId = getTargetDisplayId(eventEntry);
2131 sp<InputWindowHandle> focusedWindowHandle =
2132 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2133 if (focusedWindowHandle != nullptr) {
2134 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2136#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002137 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138#endif
2139 return;
2140 }
2141 }
2142
2143 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002144 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002145 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002146 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2147 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002148 return;
2149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002151 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002152 eventType = USER_ACTIVITY_EVENT_TOUCH;
2153 }
2154 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002156 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002157 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2158 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002159 return;
2160 }
2161 eventType = USER_ACTIVITY_EVENT_BUTTON;
2162 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002164 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002165 case EventEntry::Type::CONFIGURATION_CHANGED:
2166 case EventEntry::Type::DEVICE_RESET: {
2167 LOG_ALWAYS_FATAL("%s events are not user activity",
2168 EventEntry::typeToString(eventEntry.type));
2169 break;
2170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171 }
2172
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002173 std::unique_ptr<CommandEntry> commandEntry =
2174 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002175 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002177 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178}
2179
2180void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002181 const sp<Connection>& connection,
2182 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002183 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002184 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002185 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002186 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002187 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002188 ATRACE_NAME(message.c_str());
2189 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190#if DEBUG_DISPATCH_CYCLE
2191 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002192 "globalScaleFactor=%f, pointerIds=0x%x %s",
2193 connection->getInputChannelName().c_str(), inputTarget.flags,
2194 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2195 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196#endif
2197
2198 // Skip this event if the connection status is not normal.
2199 // We don't want to enqueue additional outbound events if the connection is broken.
2200 if (connection->status != Connection::STATUS_NORMAL) {
2201#if DEBUG_DISPATCH_CYCLE
2202 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002203 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204#endif
2205 return;
2206 }
2207
2208 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002209 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2210 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2211 "Entry type %s should not have FLAG_SPLIT",
2212 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002214 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002215 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002216 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002217 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218 if (!splitMotionEntry) {
2219 return; // split event was dropped
2220 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002221 if (DEBUG_FOCUS) {
2222 ALOGD("channel '%s' ~ Split motion event.",
2223 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002224 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002225 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002226 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 splitMotionEntry->release();
2228 return;
2229 }
2230 }
2231
2232 // Not splitting. Enqueue dispatch entries for the event as is.
2233 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2234}
2235
2236void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002237 const sp<Connection>& connection,
2238 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002239 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002240 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002241 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002242 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002243 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002244 ATRACE_NAME(message.c_str());
2245 }
2246
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002247 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248
2249 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002250 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002251 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002252 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002253 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002254 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002255 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002256 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002257 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002258 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002259 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002260 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002261 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262
2263 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002264 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 startDispatchCycleLocked(currentTime, connection);
2266 }
2267}
2268
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002269void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2270 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002271 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002272 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002273 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002274 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2275 connection->getInputChannelName().c_str(),
2276 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002277 ATRACE_NAME(message.c_str());
2278 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002279 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 if (!(inputTargetFlags & dispatchMode)) {
2281 return;
2282 }
2283 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2284
2285 // This is a new event.
2286 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002287 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002288 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002290 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2291 // different EventEntry than what was passed in.
2292 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002294 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002295 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002296 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002297 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002298 dispatchEntry->resolvedAction = keyEntry.action;
2299 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002301 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2302 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002304 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2305 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002307 return; // skip the inconsistent event
2308 }
2309 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002312 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002313 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002314 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2315 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2316 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2317 static_cast<int32_t>(IdGenerator::Source::OTHER);
2318 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002319 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2320 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2321 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2322 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2323 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2324 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2325 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2326 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2327 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2328 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2329 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002330 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002331 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002332 }
2333 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002334 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2335 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002337 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2338 "event",
2339 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002341 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002344 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002345 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2346 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2347 }
2348 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2349 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002352 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2353 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002355 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2356 "event",
2357 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002359 return; // skip the inconsistent event
2360 }
2361
Garfield Tan1c7bc862020-01-28 13:24:04 -08002362 dispatchEntry->resolvedEventId =
2363 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2364 ? mIdGenerator.nextId()
2365 : motionEntry.id;
2366 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2367 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2368 ") to MotionEvent(id=0x%" PRIx32 ").",
2369 motionEntry.id, dispatchEntry->resolvedEventId);
2370 ATRACE_NAME(message.c_str());
2371 }
2372
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002373 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002374 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002375
2376 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002378 case EventEntry::Type::FOCUS: {
2379 break;
2380 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002381 case EventEntry::Type::CONFIGURATION_CHANGED:
2382 case EventEntry::Type::DEVICE_RESET: {
2383 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002384 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002385 break;
2386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387 }
2388
2389 // Remember that we are waiting for this dispatch to complete.
2390 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002391 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 }
2393
2394 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002395 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002396 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002397}
2398
chaviwfd6d3512019-03-25 13:23:49 -07002399void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002400 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002401 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002402 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2403 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002404 return;
2405 }
2406
2407 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2408 if (inputWindowHandle == nullptr) {
2409 return;
2410 }
2411
chaviw8c9cf542019-03-25 13:02:48 -07002412 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002413 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002414
2415 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2416
2417 if (!hasFocusChanged) {
2418 return;
2419 }
2420
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002421 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2422 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002423 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002424 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425}
2426
2427void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002428 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002429 if (ATRACE_ENABLED()) {
2430 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002431 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002432 ATRACE_NAME(message.c_str());
2433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002435 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436#endif
2437
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002438 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2439 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 dispatchEntry->deliveryTime = currentTime;
2441
2442 // Publish the event.
2443 status_t status;
2444 EventEntry* eventEntry = dispatchEntry->eventEntry;
2445 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002446 case EventEntry::Type::KEY: {
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002447 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2448 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002450 // Publish the key event.
Garfield Tan1c7bc862020-01-28 13:24:04 -08002451 status =
2452 connection->inputPublisher
2453 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2454 keyEntry->deviceId, keyEntry->source,
2455 keyEntry->displayId, std::move(hmac),
2456 dispatchEntry->resolvedAction,
2457 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2458 keyEntry->scanCode, keyEntry->metaState,
2459 keyEntry->repeatCount, keyEntry->downTime,
2460 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002461 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 }
2463
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002464 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002465 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002467 PointerCoords scaledCoords[MAX_POINTERS];
2468 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2469
chaviw82357092020-01-28 13:13:06 -08002470 // Set the X and Y offset and X and Y scale depending on the input source.
2471 float xOffset = 0.0f, yOffset = 0.0f;
2472 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002473 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2474 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2475 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002476 xScale = dispatchEntry->windowXScale;
2477 yScale = dispatchEntry->windowYScale;
2478 xOffset = dispatchEntry->xOffset * xScale;
2479 yOffset = dispatchEntry->yOffset * yScale;
2480 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002481 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2482 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002483 // Don't apply window scale here since we don't want scale to affect raw
2484 // coordinates. The scale will be sent back to the client and applied
2485 // later when requesting relative coordinates.
2486 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2487 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002488 }
2489 usingCoords = scaledCoords;
2490 }
2491 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002492 // We don't want the dispatch target to know.
2493 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2494 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2495 scaledCoords[i].clear();
2496 }
2497 usingCoords = scaledCoords;
2498 }
2499 }
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002500
2501 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002502
2503 // Publish the motion event.
2504 status = connection->inputPublisher
Garfield Tan1c7bc862020-01-28 13:24:04 -08002505 .publishMotionEvent(dispatchEntry->seq,
2506 dispatchEntry->resolvedEventId,
2507 motionEntry->deviceId, motionEntry->source,
2508 motionEntry->displayId, std::move(hmac),
2509 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002510 motionEntry->actionButton,
2511 dispatchEntry->resolvedFlags,
2512 motionEntry->edgeFlags, motionEntry->metaState,
2513 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002514 motionEntry->classification, xScale, yScale,
2515 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002516 motionEntry->yPrecision,
2517 motionEntry->xCursorPosition,
2518 motionEntry->yCursorPosition,
2519 motionEntry->downTime, motionEntry->eventTime,
2520 motionEntry->pointerCount,
2521 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002522 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002523 break;
2524 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002525 case EventEntry::Type::FOCUS: {
2526 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2527 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tan1c7bc862020-01-28 13:24:04 -08002528 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002529 focusEntry->hasFocus,
2530 mInTouchMode);
2531 break;
2532 }
2533
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002534 case EventEntry::Type::CONFIGURATION_CHANGED:
2535 case EventEntry::Type::DEVICE_RESET: {
2536 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2537 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002538 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 }
2541
2542 // Check the result.
2543 if (status) {
2544 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002545 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002547 "This is unexpected because the wait queue is empty, so the pipe "
2548 "should be empty and we shouldn't have any problems writing an "
2549 "event to it, status=%d",
2550 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2552 } else {
2553 // Pipe is full and we are waiting for the app to finish process some events
2554 // before sending more events to it.
2555#if DEBUG_DISPATCH_CYCLE
2556 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002557 "waiting for the application to catch up",
2558 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559#endif
2560 connection->inputPublisherBlocked = true;
2561 }
2562 } else {
2563 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002564 "status=%d",
2565 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2567 }
2568 return;
2569 }
2570
2571 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002572 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2573 connection->outboundQueue.end(),
2574 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002575 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002576 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002577 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578 }
2579}
2580
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002581const std::array<uint8_t, 32> InputDispatcher::getSignature(
2582 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2583 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2584 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2585 // Only sign events up and down events as the purely move events
2586 // are tied to their up/down counterparts so signing would be redundant.
2587 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2588 verifiedEvent.actionMasked = actionMasked;
2589 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2590 return mHmacKeyManager.sign(verifiedEvent);
2591 }
2592 return INVALID_HMAC;
2593}
2594
2595const std::array<uint8_t, 32> InputDispatcher::getSignature(
2596 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2597 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2598 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2599 verifiedEvent.action = dispatchEntry.resolvedAction;
2600 return mHmacKeyManager.sign(verifiedEvent);
2601}
2602
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002604 const sp<Connection>& connection, uint32_t seq,
2605 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606#if DEBUG_DISPATCH_CYCLE
2607 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002608 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609#endif
2610
2611 connection->inputPublisherBlocked = false;
2612
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002613 if (connection->status == Connection::STATUS_BROKEN ||
2614 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 return;
2616 }
2617
2618 // Notify other system components and prepare to start the next dispatch cycle.
2619 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2620}
2621
2622void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002623 const sp<Connection>& connection,
2624 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625#if DEBUG_DISPATCH_CYCLE
2626 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002627 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628#endif
2629
2630 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002631 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002632 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002633 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002634 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002635
2636 // The connection appears to be unrecoverably broken.
2637 // Ignore already broken or zombie connections.
2638 if (connection->status == Connection::STATUS_NORMAL) {
2639 connection->status = Connection::STATUS_BROKEN;
2640
2641 if (notify) {
2642 // Notify other system components.
2643 onDispatchCycleBrokenLocked(currentTime, connection);
2644 }
2645 }
2646}
2647
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002648void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2649 while (!queue.empty()) {
2650 DispatchEntry* dispatchEntry = queue.front();
2651 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002652 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 }
2654}
2655
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002656void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002658 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 }
2660 delete dispatchEntry;
2661}
2662
2663int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2664 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2665
2666 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002667 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002669 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002671 "fd=%d, events=0x%x",
2672 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673 return 0; // remove the callback
2674 }
2675
2676 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002677 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2679 if (!(events & ALOOPER_EVENT_INPUT)) {
2680 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002681 "events=0x%x",
2682 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683 return 1;
2684 }
2685
2686 nsecs_t currentTime = now();
2687 bool gotOne = false;
2688 status_t status;
2689 for (;;) {
2690 uint32_t seq;
2691 bool handled;
2692 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2693 if (status) {
2694 break;
2695 }
2696 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2697 gotOne = true;
2698 }
2699 if (gotOne) {
2700 d->runCommandsLockedInterruptible();
2701 if (status == WOULD_BLOCK) {
2702 return 1;
2703 }
2704 }
2705
2706 notify = status != DEAD_OBJECT || !connection->monitor;
2707 if (notify) {
2708 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002709 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 }
2711 } else {
2712 // Monitor channels are never explicitly unregistered.
2713 // We do it automatically when the remote endpoint is closed so don't warn
2714 // about them.
2715 notify = !connection->monitor;
2716 if (notify) {
2717 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002718 "events=0x%x",
2719 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720 }
2721 }
2722
2723 // Unregister the channel.
2724 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2725 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002726 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727}
2728
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002729void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002731 for (const auto& pair : mConnectionsByFd) {
2732 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733 }
2734}
2735
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002736void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002737 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002738 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2739 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2740}
2741
2742void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2743 const CancelationOptions& options,
2744 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2745 for (const auto& it : monitorsByDisplay) {
2746 const std::vector<Monitor>& monitors = it.second;
2747 for (const Monitor& monitor : monitors) {
2748 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002749 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002750 }
2751}
2752
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2754 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002755 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002756 if (connection == nullptr) {
2757 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002759
2760 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761}
2762
2763void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2764 const sp<Connection>& connection, const CancelationOptions& options) {
2765 if (connection->status == Connection::STATUS_BROKEN) {
2766 return;
2767 }
2768
2769 nsecs_t currentTime = now();
2770
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002771 std::vector<EventEntry*> cancelationEvents =
2772 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002774 if (cancelationEvents.empty()) {
2775 return;
2776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002778 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2779 "with reality: %s, mode=%d.",
2780 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2781 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002783
2784 InputTarget target;
2785 sp<InputWindowHandle> windowHandle =
2786 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2787 if (windowHandle != nullptr) {
2788 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2789 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2790 windowInfo->windowXScale, windowInfo->windowYScale);
2791 target.globalScaleFactor = windowInfo->globalScaleFactor;
2792 }
2793 target.inputChannel = connection->inputChannel;
2794 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2795
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002796 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2797 EventEntry* cancelationEventEntry = cancelationEvents[i];
2798 switch (cancelationEventEntry->type) {
2799 case EventEntry::Type::KEY: {
2800 logOutboundKeyDetails("cancel - ",
2801 static_cast<const KeyEntry&>(*cancelationEventEntry));
2802 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002804 case EventEntry::Type::MOTION: {
2805 logOutboundMotionDetails("cancel - ",
2806 static_cast<const MotionEntry&>(*cancelationEventEntry));
2807 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002809 case EventEntry::Type::FOCUS: {
2810 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2811 break;
2812 }
2813 case EventEntry::Type::CONFIGURATION_CHANGED:
2814 case EventEntry::Type::DEVICE_RESET: {
2815 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2816 EventEntry::typeToString(cancelationEventEntry->type));
2817 break;
2818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819 }
2820
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002821 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2822 target, InputTarget::FLAG_DISPATCH_AS_IS);
2823
2824 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002826
2827 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828}
2829
Svet Ganov5d3bc372020-01-26 23:11:07 -08002830void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2831 const sp<Connection>& connection) {
2832 if (connection->status == Connection::STATUS_BROKEN) {
2833 return;
2834 }
2835
2836 nsecs_t currentTime = now();
2837
2838 std::vector<EventEntry*> downEvents =
2839 connection->inputState.synthesizePointerDownEvents(currentTime);
2840
2841 if (downEvents.empty()) {
2842 return;
2843 }
2844
2845#if DEBUG_OUTBOUND_EVENT_DETAILS
2846 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2847 connection->getInputChannelName().c_str(), downEvents.size());
2848#endif
2849
2850 InputTarget target;
2851 sp<InputWindowHandle> windowHandle =
2852 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2853 if (windowHandle != nullptr) {
2854 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2855 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2856 windowInfo->windowXScale, windowInfo->windowYScale);
2857 target.globalScaleFactor = windowInfo->globalScaleFactor;
2858 }
2859 target.inputChannel = connection->inputChannel;
2860 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2861
2862 for (EventEntry* downEventEntry : downEvents) {
2863 switch (downEventEntry->type) {
2864 case EventEntry::Type::MOTION: {
2865 logOutboundMotionDetails("down - ",
2866 static_cast<const MotionEntry&>(*downEventEntry));
2867 break;
2868 }
2869
2870 case EventEntry::Type::KEY:
2871 case EventEntry::Type::FOCUS:
2872 case EventEntry::Type::CONFIGURATION_CHANGED:
2873 case EventEntry::Type::DEVICE_RESET: {
2874 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2875 EventEntry::typeToString(downEventEntry->type));
2876 break;
2877 }
2878 }
2879
2880 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2881 target, InputTarget::FLAG_DISPATCH_AS_IS);
2882
2883 downEventEntry->release();
2884 }
2885
2886 startDispatchCycleLocked(currentTime, connection);
2887}
2888
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002889MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002890 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891 ALOG_ASSERT(pointerIds.value != 0);
2892
2893 uint32_t splitPointerIndexMap[MAX_POINTERS];
2894 PointerProperties splitPointerProperties[MAX_POINTERS];
2895 PointerCoords splitPointerCoords[MAX_POINTERS];
2896
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002897 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898 uint32_t splitPointerCount = 0;
2899
2900 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002903 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904 uint32_t pointerId = uint32_t(pointerProperties.id);
2905 if (pointerIds.hasBit(pointerId)) {
2906 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2907 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2908 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002909 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910 splitPointerCount += 1;
2911 }
2912 }
2913
2914 if (splitPointerCount != pointerIds.count()) {
2915 // This is bad. We are missing some of the pointers that we expected to deliver.
2916 // Most likely this indicates that we received an ACTION_MOVE events that has
2917 // different pointer ids than we expected based on the previous ACTION_DOWN
2918 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2919 // in this way.
2920 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002921 "we expected there to be %d pointers. This probably means we received "
2922 "a broken sequence of pointer ids from the input device.",
2923 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002924 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 }
2926
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002927 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2930 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2932 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002933 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934 uint32_t pointerId = uint32_t(pointerProperties.id);
2935 if (pointerIds.hasBit(pointerId)) {
2936 if (pointerIds.count() == 1) {
2937 // The first/last pointer went down/up.
2938 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002939 ? AMOTION_EVENT_ACTION_DOWN
2940 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941 } else {
2942 // A secondary pointer went down/up.
2943 uint32_t splitPointerIndex = 0;
2944 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2945 splitPointerIndex += 1;
2946 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002947 action = maskedAction |
2948 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949 }
2950 } else {
2951 // An unrelated pointer changed.
2952 action = AMOTION_EVENT_ACTION_MOVE;
2953 }
2954 }
2955
Garfield Tan1c7bc862020-01-28 13:24:04 -08002956 int32_t newId = mIdGenerator.nextId();
2957 if (ATRACE_ENABLED()) {
2958 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
2959 ") to MotionEvent(id=0x%" PRIx32 ").",
2960 originalMotionEntry.id, newId);
2961 ATRACE_NAME(message.c_str());
2962 }
Garfield Tan00f511d2019-06-12 16:55:40 -07002963 MotionEntry* splitMotionEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002964 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
2965 originalMotionEntry.source, originalMotionEntry.displayId,
2966 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002967 originalMotionEntry.actionButton, originalMotionEntry.flags,
2968 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2969 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2970 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2971 originalMotionEntry.xCursorPosition,
2972 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002973 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002975 if (originalMotionEntry.injectionState) {
2976 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002977 splitMotionEntry->injectionState->refCount += 1;
2978 }
2979
2980 return splitMotionEntry;
2981}
2982
2983void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2984#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002985 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986#endif
2987
2988 bool needWake;
2989 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002990 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002991
Prabir Pradhan42611e02018-11-27 14:04:02 -08002992 ConfigurationChangedEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002993 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994 needWake = enqueueInboundEventLocked(newEntry);
2995 } // release lock
2996
2997 if (needWake) {
2998 mLooper->wake();
2999 }
3000}
3001
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003002/**
3003 * If one of the meta shortcuts is detected, process them here:
3004 * Meta + Backspace -> generate BACK
3005 * Meta + Enter -> generate HOME
3006 * This will potentially overwrite keyCode and metaState.
3007 */
3008void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003009 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003010 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3011 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3012 if (keyCode == AKEYCODE_DEL) {
3013 newKeyCode = AKEYCODE_BACK;
3014 } else if (keyCode == AKEYCODE_ENTER) {
3015 newKeyCode = AKEYCODE_HOME;
3016 }
3017 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003018 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003019 struct KeyReplacement replacement = {keyCode, deviceId};
3020 mReplacedKeys.add(replacement, newKeyCode);
3021 keyCode = newKeyCode;
3022 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3023 }
3024 } else if (action == AKEY_EVENT_ACTION_UP) {
3025 // In order to maintain a consistent stream of up and down events, check to see if the key
3026 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3027 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003028 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003029 struct KeyReplacement replacement = {keyCode, deviceId};
3030 ssize_t index = mReplacedKeys.indexOfKey(replacement);
3031 if (index >= 0) {
3032 keyCode = mReplacedKeys.valueAt(index);
3033 mReplacedKeys.removeItemsAt(index);
3034 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3035 }
3036 }
3037}
3038
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3040#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003041 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3042 "policyFlags=0x%x, action=0x%x, "
3043 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3044 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3045 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3046 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047#endif
3048 if (!validateKeyEvent(args->action)) {
3049 return;
3050 }
3051
3052 uint32_t policyFlags = args->policyFlags;
3053 int32_t flags = args->flags;
3054 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003055 // InputDispatcher tracks and generates key repeats on behalf of
3056 // whatever notifies it, so repeatCount should always be set to 0
3057 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3059 policyFlags |= POLICY_FLAG_VIRTUAL;
3060 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062 if (policyFlags & POLICY_FLAG_FUNCTION) {
3063 metaState |= AMETA_FUNCTION_ON;
3064 }
3065
3066 policyFlags |= POLICY_FLAG_TRUSTED;
3067
Michael Wright78f24442014-08-06 15:55:28 -07003068 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003069 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003070
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003072 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08003073 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3074 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003075
Michael Wright2b3c3302018-03-02 17:19:13 +00003076 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003078 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3079 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003080 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083 bool needWake;
3084 { // acquire lock
3085 mLock.lock();
3086
3087 if (shouldSendKeyToInputFilterLocked(args)) {
3088 mLock.unlock();
3089
3090 policyFlags |= POLICY_FLAG_FILTERED;
3091 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3092 return; // event was consumed by the filter
3093 }
3094
3095 mLock.lock();
3096 }
3097
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003098 KeyEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003099 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 args->displayId, policyFlags, args->action, flags, keyCode,
3101 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102
3103 needWake = enqueueInboundEventLocked(newEntry);
3104 mLock.unlock();
3105 } // release lock
3106
3107 if (needWake) {
3108 mLooper->wake();
3109 }
3110}
3111
3112bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3113 return mInputFilterEnabled;
3114}
3115
3116void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3117#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003118 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3119 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003120 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3121 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003122 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003123 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3124 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3125 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3126 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127 for (uint32_t i = 0; i < args->pointerCount; i++) {
3128 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003129 "x=%f, y=%f, pressure=%f, size=%f, "
3130 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3131 "orientation=%f",
3132 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3133 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3134 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3135 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3136 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3137 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3138 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3139 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3140 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3141 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 }
3143#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003144 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3145 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 return;
3147 }
3148
3149 uint32_t policyFlags = args->policyFlags;
3150 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003151
3152 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003153 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003154 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3155 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003156 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158
3159 bool needWake;
3160 { // acquire lock
3161 mLock.lock();
3162
3163 if (shouldSendMotionToInputFilterLocked(args)) {
3164 mLock.unlock();
3165
3166 MotionEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003167 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3168 args->action, args->actionButton, args->flags, args->edgeFlags,
3169 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3170 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3171 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3172 args->downTime, args->eventTime, args->pointerCount,
3173 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174
3175 policyFlags |= POLICY_FLAG_FILTERED;
3176 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3177 return; // event was consumed by the filter
3178 }
3179
3180 mLock.lock();
3181 }
3182
3183 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003184 MotionEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003185 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003186 args->displayId, policyFlags, args->action, args->actionButton,
3187 args->flags, args->metaState, args->buttonState,
3188 args->classification, args->edgeFlags, args->xPrecision,
3189 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3190 args->downTime, args->pointerCount, args->pointerProperties,
3191 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192
3193 needWake = enqueueInboundEventLocked(newEntry);
3194 mLock.unlock();
3195 } // release lock
3196
3197 if (needWake) {
3198 mLooper->wake();
3199 }
3200}
3201
3202bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003203 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204}
3205
3206void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3207#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003208 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 "switchMask=0x%08x",
3210 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211#endif
3212
3213 uint32_t policyFlags = args->policyFlags;
3214 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003215 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216}
3217
3218void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3219#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003220 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3221 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222#endif
3223
3224 bool needWake;
3225 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003226 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227
Prabir Pradhan42611e02018-11-27 14:04:02 -08003228 DeviceResetEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003229 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 needWake = enqueueInboundEventLocked(newEntry);
3231 } // release lock
3232
3233 if (needWake) {
3234 mLooper->wake();
3235 }
3236}
3237
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003238int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3239 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003240 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241#if DEBUG_INBOUND_EVENT_DETAILS
3242 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003243 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3244 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245#endif
3246
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003247 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248
3249 policyFlags |= POLICY_FLAG_INJECTED;
3250 if (hasInjectionPermission(injectorPid, injectorUid)) {
3251 policyFlags |= POLICY_FLAG_TRUSTED;
3252 }
3253
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003254 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003256 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003257 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3258 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003259 if (!validateKeyEvent(action)) {
3260 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003263 int32_t flags = incomingKey.getFlags();
3264 int32_t keyCode = incomingKey.getKeyCode();
3265 int32_t metaState = incomingKey.getMetaState();
3266 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003267 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003268 KeyEvent keyEvent;
Garfield Tanfbe732e2020-01-24 11:26:14 -08003269 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003270 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3271 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3272 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003274 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3275 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003276 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003277
3278 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3279 android::base::Timer t;
3280 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3281 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3282 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3283 std::to_string(t.duration().count()).c_str());
3284 }
3285 }
3286
3287 mLock.lock();
3288 KeyEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003289 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3290 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003291 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3292 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tanfbe732e2020-01-24 11:26:14 -08003293 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003294 injectedEntries.push(injectedEntry);
3295 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 }
3297
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298 case AINPUT_EVENT_TYPE_MOTION: {
3299 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3300 int32_t action = motionEvent->getAction();
3301 size_t pointerCount = motionEvent->getPointerCount();
3302 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3303 int32_t actionButton = motionEvent->getActionButton();
3304 int32_t displayId = motionEvent->getDisplayId();
3305 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3306 return INPUT_EVENT_INJECTION_FAILED;
3307 }
3308
3309 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3310 nsecs_t eventTime = motionEvent->getEventTime();
3311 android::base::Timer t;
3312 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3313 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3314 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3315 std::to_string(t.duration().count()).c_str());
3316 }
3317 }
3318
3319 mLock.lock();
3320 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3321 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3322 MotionEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003323 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3324 motionEvent->getSource(), motionEvent->getDisplayId(),
3325 policyFlags, action, actionButton, motionEvent->getFlags(),
3326 motionEvent->getMetaState(), motionEvent->getButtonState(),
3327 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3328 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003329 motionEvent->getRawXCursorPosition(),
3330 motionEvent->getRawYCursorPosition(),
3331 motionEvent->getDownTime(), uint32_t(pointerCount),
3332 pointerProperties, samplePointerCoords,
3333 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 injectedEntries.push(injectedEntry);
3335 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3336 sampleEventTimes += 1;
3337 samplePointerCoords += pointerCount;
3338 MotionEntry* nextInjectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003339 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003340 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 motionEvent->getDisplayId(), policyFlags, action,
3342 actionButton, motionEvent->getFlags(),
3343 motionEvent->getMetaState(), motionEvent->getButtonState(),
3344 motionEvent->getClassification(),
3345 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3346 motionEvent->getYPrecision(),
3347 motionEvent->getRawXCursorPosition(),
3348 motionEvent->getRawYCursorPosition(),
3349 motionEvent->getDownTime(), uint32_t(pointerCount),
3350 pointerProperties, samplePointerCoords,
3351 motionEvent->getXOffset(), motionEvent->getYOffset());
3352 injectedEntries.push(nextInjectedEntry);
3353 }
3354 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003357 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003358 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003359 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360 }
3361
3362 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3363 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3364 injectionState->injectionIsAsync = true;
3365 }
3366
3367 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003368 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369
3370 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003371 while (!injectedEntries.empty()) {
3372 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3373 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 }
3375
3376 mLock.unlock();
3377
3378 if (needWake) {
3379 mLooper->wake();
3380 }
3381
3382 int32_t injectionResult;
3383 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003384 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385
3386 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3387 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3388 } else {
3389 for (;;) {
3390 injectionResult = injectionState->injectionResult;
3391 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3392 break;
3393 }
3394
3395 nsecs_t remainingTimeout = endTime - now();
3396 if (remainingTimeout <= 0) {
3397#if DEBUG_INJECTION
3398 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003399 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400#endif
3401 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3402 break;
3403 }
3404
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003405 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 }
3407
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003408 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3409 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 while (injectionState->pendingForegroundDispatches != 0) {
3411#if DEBUG_INJECTION
3412 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003413 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414#endif
3415 nsecs_t remainingTimeout = endTime - now();
3416 if (remainingTimeout <= 0) {
3417#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003418 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3419 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420#endif
3421 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3422 break;
3423 }
3424
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003425 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 }
3427 }
3428 }
3429
3430 injectionState->release();
3431 } // release lock
3432
3433#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003434 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003435 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436#endif
3437
3438 return injectionResult;
3439}
3440
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003441std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003442 std::array<uint8_t, 32> calculatedHmac;
3443 std::unique_ptr<VerifiedInputEvent> result;
3444 switch (event.getType()) {
3445 case AINPUT_EVENT_TYPE_KEY: {
3446 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3447 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3448 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3449 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3450 break;
3451 }
3452 case AINPUT_EVENT_TYPE_MOTION: {
3453 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3454 VerifiedMotionEvent verifiedMotionEvent =
3455 verifiedMotionEventFromMotionEvent(motionEvent);
3456 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3457 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3458 break;
3459 }
3460 default: {
3461 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3462 return nullptr;
3463 }
3464 }
3465 if (calculatedHmac == INVALID_HMAC) {
3466 return nullptr;
3467 }
3468 if (calculatedHmac != event.getHmac()) {
3469 return nullptr;
3470 }
3471 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003472}
3473
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003475 return injectorUid == 0 ||
3476 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477}
3478
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003479void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480 InjectionState* injectionState = entry->injectionState;
3481 if (injectionState) {
3482#if DEBUG_INJECTION
3483 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003484 "injectorPid=%d, injectorUid=%d",
3485 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486#endif
3487
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003488 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489 // Log the outcome since the injector did not wait for the injection result.
3490 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003491 case INPUT_EVENT_INJECTION_SUCCEEDED:
3492 ALOGV("Asynchronous input event injection succeeded.");
3493 break;
3494 case INPUT_EVENT_INJECTION_FAILED:
3495 ALOGW("Asynchronous input event injection failed.");
3496 break;
3497 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3498 ALOGW("Asynchronous input event injection permission denied.");
3499 break;
3500 case INPUT_EVENT_INJECTION_TIMED_OUT:
3501 ALOGW("Asynchronous input event injection timed out.");
3502 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503 }
3504 }
3505
3506 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003507 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 }
3509}
3510
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003511void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 InjectionState* injectionState = entry->injectionState;
3513 if (injectionState) {
3514 injectionState->pendingForegroundDispatches += 1;
3515 }
3516}
3517
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003518void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519 InjectionState* injectionState = entry->injectionState;
3520 if (injectionState) {
3521 injectionState->pendingForegroundDispatches -= 1;
3522
3523 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003524 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525 }
3526 }
3527}
3528
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003529std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3530 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003531 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003532}
3533
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003535 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003536 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003537 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3538 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003539 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003540 return windowHandle;
3541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 }
3543 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003544 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545}
3546
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003547bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003548 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003549 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3550 for (const sp<InputWindowHandle>& handle : windowHandles) {
3551 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003552 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003553 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003554 ", but it should belong to display %" PRId32,
3555 windowHandle->getName().c_str(), it.first,
3556 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003557 }
3558 return true;
3559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 }
3561 }
3562 return false;
3563}
3564
Robert Carr5c8a0262018-10-03 16:30:44 -07003565sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3566 size_t count = mInputChannelsByToken.count(token);
3567 if (count == 0) {
3568 return nullptr;
3569 }
3570 return mInputChannelsByToken.at(token);
3571}
3572
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003573void InputDispatcher::updateWindowHandlesForDisplayLocked(
3574 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3575 if (inputWindowHandles.empty()) {
3576 // Remove all handles on a display if there are no windows left.
3577 mWindowHandlesByDisplay.erase(displayId);
3578 return;
3579 }
3580
3581 // Since we compare the pointer of input window handles across window updates, we need
3582 // to make sure the handle object for the same window stays unchanged across updates.
3583 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003584 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003585 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003586 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003587 }
3588
3589 std::vector<sp<InputWindowHandle>> newHandles;
3590 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3591 if (!handle->updateInfo()) {
3592 // handle no longer valid
3593 continue;
3594 }
3595
3596 const InputWindowInfo* info = handle->getInfo();
3597 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3598 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3599 const bool noInputChannel =
3600 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3601 const bool canReceiveInput =
3602 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3603 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3604 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003605 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003606 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003607 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003608 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003609 }
3610
3611 if (info->displayId != displayId) {
3612 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3613 handle->getName().c_str(), displayId, info->displayId);
3614 continue;
3615 }
3616
chaviwaf87b3e2019-10-01 16:59:28 -07003617 if (oldHandlesById.find(handle->getId()) != oldHandlesById.end()) {
3618 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003619 oldHandle->updateFrom(handle);
3620 newHandles.push_back(oldHandle);
3621 } else {
3622 newHandles.push_back(handle);
3623 }
3624 }
3625
3626 // Insert or replace
3627 mWindowHandlesByDisplay[displayId] = newHandles;
3628}
3629
Arthur Hung72d8dc32020-03-28 00:48:39 +00003630void InputDispatcher::setInputWindows(
3631 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3632 { // acquire lock
3633 std::scoped_lock _l(mLock);
3634 for (auto const& i : handlesPerDisplay) {
3635 setInputWindowsLocked(i.second, i.first);
3636 }
3637 }
3638 // Wake up poll loop since it may need to make new input dispatching choices.
3639 mLooper->wake();
3640}
3641
Arthur Hungb92218b2018-08-14 12:00:21 +08003642/**
3643 * Called from InputManagerService, update window handle list by displayId that can receive input.
3644 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3645 * If set an empty list, remove all handles from the specific display.
3646 * For focused handle, check if need to change and send a cancel event to previous one.
3647 * For removed handle, check if need to send a cancel event if already in touch.
3648 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003649void InputDispatcher::setInputWindowsLocked(
3650 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003651 if (DEBUG_FOCUS) {
3652 std::string windowList;
3653 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3654 windowList += iwh->getName() + " ";
3655 }
3656 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658
Arthur Hung72d8dc32020-03-28 00:48:39 +00003659 // Copy old handles for release if they are no longer present.
3660 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661
Arthur Hung72d8dc32020-03-28 00:48:39 +00003662 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003663
Arthur Hung72d8dc32020-03-28 00:48:39 +00003664 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3665 bool foundHoveredWindow = false;
3666 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3667 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3668 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3669 windowHandle->getInfo()->visible) {
3670 newFocusedWindowHandle = windowHandle;
3671 }
3672 if (windowHandle == mLastHoverWindowHandle) {
3673 foundHoveredWindow = true;
3674 }
3675 }
3676
3677 if (!foundHoveredWindow) {
3678 mLastHoverWindowHandle = nullptr;
3679 }
3680
3681 sp<InputWindowHandle> oldFocusedWindowHandle =
3682 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3683
3684 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3685 if (oldFocusedWindowHandle != nullptr) {
3686 if (DEBUG_FOCUS) {
3687 ALOGD("Focus left window: %s in display %" PRId32,
3688 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003689 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003690 sp<InputChannel> focusedInputChannel =
3691 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3692 if (focusedInputChannel != nullptr) {
3693 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3694 "focus left window");
3695 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3696 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003697 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003698 mFocusedWindowHandlesByDisplay.erase(displayId);
3699 }
3700 if (newFocusedWindowHandle != nullptr) {
3701 if (DEBUG_FOCUS) {
3702 ALOGD("Focus entered window: %s in display %" PRId32,
3703 newFocusedWindowHandle->getName().c_str(), displayId);
3704 }
3705 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3706 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 }
3708
Arthur Hung72d8dc32020-03-28 00:48:39 +00003709 if (mFocusedDisplayId == displayId) {
3710 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713
Arthur Hung72d8dc32020-03-28 00:48:39 +00003714 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3715 if (stateIndex >= 0) {
3716 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
3717 for (size_t i = 0; i < state.windows.size();) {
3718 TouchedWindow& touchedWindow = state.windows[i];
3719 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003720 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003721 ALOGD("Touched window was removed: %s in display %" PRId32,
3722 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003723 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003724 sp<InputChannel> touchedInputChannel =
3725 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3726 if (touchedInputChannel != nullptr) {
3727 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3728 "touched window was removed");
3729 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003731 state.windows.erase(state.windows.begin() + i);
3732 } else {
3733 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 }
3735 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003736 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003737
Arthur Hung72d8dc32020-03-28 00:48:39 +00003738 // Release information for windows that are no longer present.
3739 // This ensures that unused input channels are released promptly.
3740 // Otherwise, they might stick around until the window handle is destroyed
3741 // which might not happen until the next GC.
3742 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3743 if (!hasWindowHandleLocked(oldWindowHandle)) {
3744 if (DEBUG_FOCUS) {
3745 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003746 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003747 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003748 }
chaviw291d88a2019-02-14 10:33:58 -08003749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750}
3751
3752void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003753 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003754 if (DEBUG_FOCUS) {
3755 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3756 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003759 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760
Tiger Huang721e26f2018-07-24 22:26:19 +08003761 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3762 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003763 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003764 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3765 if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003766 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003768 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003770 } else if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003771 resetAnrTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003772 oldFocusedApplicationHandle.clear();
3773 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775 } // release lock
3776
3777 // Wake up poll loop since it may need to make new input dispatching choices.
3778 mLooper->wake();
3779}
3780
Tiger Huang721e26f2018-07-24 22:26:19 +08003781/**
3782 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3783 * the display not specified.
3784 *
3785 * We track any unreleased events for each window. If a window loses the ability to receive the
3786 * released event, we will send a cancel event to it. So when the focused display is changed, we
3787 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3788 * display. The display-specified events won't be affected.
3789 */
3790void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003791 if (DEBUG_FOCUS) {
3792 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3793 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003794 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003795 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003796
3797 if (mFocusedDisplayId != displayId) {
3798 sp<InputWindowHandle> oldFocusedWindowHandle =
3799 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3800 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003801 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003802 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003803 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003804 CancelationOptions
3805 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3806 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003807 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003808 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3809 }
3810 }
3811 mFocusedDisplayId = displayId;
3812
3813 // Sanity check
3814 sp<InputWindowHandle> newFocusedWindowHandle =
3815 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003816 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003817
Tiger Huang721e26f2018-07-24 22:26:19 +08003818 if (newFocusedWindowHandle == nullptr) {
3819 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3820 if (!mFocusedWindowHandlesByDisplay.empty()) {
3821 ALOGE("But another display has a focused window:");
3822 for (auto& it : mFocusedWindowHandlesByDisplay) {
3823 const int32_t displayId = it.first;
3824 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003825 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3826 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003827 }
3828 }
3829 }
3830 }
3831
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003832 if (DEBUG_FOCUS) {
3833 logDispatchStateLocked();
3834 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003835 } // release lock
3836
3837 // Wake up poll loop since it may need to make new input dispatching choices.
3838 mLooper->wake();
3839}
3840
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003842 if (DEBUG_FOCUS) {
3843 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003845
3846 bool changed;
3847 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003848 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849
3850 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3851 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003852 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853 }
3854
3855 if (mDispatchEnabled && !enabled) {
3856 resetAndDropEverythingLocked("dispatcher is being disabled");
3857 }
3858
3859 mDispatchEnabled = enabled;
3860 mDispatchFrozen = frozen;
3861 changed = true;
3862 } else {
3863 changed = false;
3864 }
3865
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003866 if (DEBUG_FOCUS) {
3867 logDispatchStateLocked();
3868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 } // release lock
3870
3871 if (changed) {
3872 // Wake up poll loop since it may need to make new input dispatching choices.
3873 mLooper->wake();
3874 }
3875}
3876
3877void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003878 if (DEBUG_FOCUS) {
3879 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881
3882 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003883 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884
3885 if (mInputFilterEnabled == enabled) {
3886 return;
3887 }
3888
3889 mInputFilterEnabled = enabled;
3890 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3891 } // release lock
3892
3893 // Wake up poll loop since there might be work to do to drop everything.
3894 mLooper->wake();
3895}
3896
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003897void InputDispatcher::setInTouchMode(bool inTouchMode) {
3898 std::scoped_lock lock(mLock);
3899 mInTouchMode = inTouchMode;
3900}
3901
chaviwfbe5d9c2018-12-26 12:23:37 -08003902bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3903 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003904 if (DEBUG_FOCUS) {
3905 ALOGD("Trivial transfer to same window.");
3906 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003907 return true;
3908 }
3909
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003911 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912
chaviwfbe5d9c2018-12-26 12:23:37 -08003913 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3914 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003915 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003916 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 return false;
3918 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003919 if (DEBUG_FOCUS) {
3920 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3921 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003924 if (DEBUG_FOCUS) {
3925 ALOGD("Cannot transfer focus because windows are on different displays.");
3926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 return false;
3928 }
3929
3930 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003931 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3932 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3933 for (size_t i = 0; i < state.windows.size(); i++) {
3934 const TouchedWindow& touchedWindow = state.windows[i];
3935 if (touchedWindow.windowHandle == fromWindowHandle) {
3936 int32_t oldTargetFlags = touchedWindow.targetFlags;
3937 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003939 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003941 int32_t newTargetFlags = oldTargetFlags &
3942 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3943 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003944 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945
Jeff Brownf086ddb2014-02-11 14:28:48 -08003946 found = true;
3947 goto Found;
3948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 }
3950 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003951 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003953 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003954 if (DEBUG_FOCUS) {
3955 ALOGD("Focus transfer failed because from window did not have focus.");
3956 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 return false;
3958 }
3959
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003960 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3961 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003962 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003963 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003964 CancelationOptions
3965 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3966 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003968 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 }
3970
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003971 if (DEBUG_FOCUS) {
3972 logDispatchStateLocked();
3973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 } // release lock
3975
3976 // Wake up poll loop since it may need to make new input dispatching choices.
3977 mLooper->wake();
3978 return true;
3979}
3980
3981void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003982 if (DEBUG_FOCUS) {
3983 ALOGD("Resetting and dropping all events (%s).", reason);
3984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985
3986 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3987 synthesizeCancelationEventsForAllConnectionsLocked(options);
3988
3989 resetKeyRepeatLocked();
3990 releasePendingEventLocked();
3991 drainInboundQueueLocked();
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003992 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993
Jeff Brownf086ddb2014-02-11 14:28:48 -08003994 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003996 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997}
3998
3999void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004000 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001 dumpDispatchStateLocked(dump);
4002
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004003 std::istringstream stream(dump);
4004 std::string line;
4005
4006 while (std::getline(stream, line, '\n')) {
4007 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008 }
4009}
4010
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004011void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004012 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4013 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4014 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004015 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016
Tiger Huang721e26f2018-07-24 22:26:19 +08004017 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4018 dump += StringPrintf(INDENT "FocusedApplications:\n");
4019 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4020 const int32_t displayId = it.first;
4021 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004022 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4023 ", name='%s', dispatchingTimeout=%0.3fms\n",
4024 displayId, applicationHandle->getName().c_str(),
4025 applicationHandle->getDispatchingTimeout(
4026 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
4027 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08004028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004030 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004032
4033 if (!mFocusedWindowHandlesByDisplay.empty()) {
4034 dump += StringPrintf(INDENT "FocusedWindows:\n");
4035 for (auto& it : mFocusedWindowHandlesByDisplay) {
4036 const int32_t displayId = it.first;
4037 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004038 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4039 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004040 }
4041 } else {
4042 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044
Jeff Brownf086ddb2014-02-11 14:28:48 -08004045 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004046 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08004047 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
4048 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004049 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004050 state.displayId, toString(state.down), toString(state.split),
4051 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004052 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004053 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004054 for (size_t i = 0; i < state.windows.size(); i++) {
4055 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004056 dump += StringPrintf(INDENT4
4057 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4058 i, touchedWindow.windowHandle->getName().c_str(),
4059 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004060 }
4061 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004062 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004063 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004064 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004065 dump += INDENT3 "Portal windows:\n";
4066 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004067 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004068 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4069 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004070 }
4071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 }
4073 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004074 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 }
4076
Arthur Hungb92218b2018-08-14 12:00:21 +08004077 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004078 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004079 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004080 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004081 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004082 dump += INDENT2 "Windows:\n";
4083 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004084 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004085 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086
Arthur Hungb92218b2018-08-14 12:00:21 +08004087 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004088 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004089 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4090 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004091 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004092 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004093 i, windowInfo->name.c_str(), windowInfo->displayId,
4094 windowInfo->portalToDisplayId,
4095 toString(windowInfo->paused),
4096 toString(windowInfo->hasFocus),
4097 toString(windowInfo->hasWallpaper),
4098 toString(windowInfo->visible),
4099 toString(windowInfo->canReceiveKeys),
4100 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004101 windowInfo->layoutParamsType, windowInfo->frameLeft,
4102 windowInfo->frameTop, windowInfo->frameRight,
4103 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4104 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004105 dumpRegion(dump, windowInfo->touchableRegion);
4106 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
4107 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004108 windowInfo->ownerPid, windowInfo->ownerUid,
4109 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08004110 }
4111 } else {
4112 dump += INDENT2 "Windows: <none>\n";
4113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 }
4115 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004116 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 }
4118
Michael Wright3dd60e22019-03-27 22:06:44 +00004119 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004120 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004121 const std::vector<Monitor>& monitors = it.second;
4122 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4123 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004124 }
4125 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004126 const std::vector<Monitor>& monitors = it.second;
4127 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4128 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004131 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 }
4133
4134 nsecs_t currentTime = now();
4135
4136 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004137 if (!mRecentQueue.empty()) {
4138 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4139 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004140 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004142 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143 }
4144 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004145 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 }
4147
4148 // Dump event currently being dispatched.
4149 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004150 dump += INDENT "PendingEvent:\n";
4151 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004153 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004154 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004156 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 }
4158
4159 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004160 if (!mInboundQueue.empty()) {
4161 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4162 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004163 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004165 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 }
4167 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004168 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 }
4170
Michael Wright78f24442014-08-06 15:55:28 -07004171 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004172 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07004173 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
4174 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
4175 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004176 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
4177 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004178 }
4179 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004180 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004181 }
4182
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004183 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004184 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004185 for (const auto& pair : mConnectionsByFd) {
4186 const sp<Connection>& connection = pair.second;
4187 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
4188 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
4189 pair.first, connection->getInputChannelName().c_str(),
4190 connection->getWindowName().c_str(), connection->getStatusLabel(),
4191 toString(connection->monitor),
4192 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004194 if (!connection->outboundQueue.empty()) {
4195 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4196 connection->outboundQueue.size());
4197 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 dump.append(INDENT4);
4199 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004200 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 entry->targetFlags, entry->resolvedAction,
4202 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 }
4204 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004205 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 }
4207
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004208 if (!connection->waitQueue.empty()) {
4209 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4210 connection->waitQueue.size());
4211 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004212 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004214 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004215 "age=%0.1fms, wait=%0.1fms\n",
4216 entry->targetFlags, entry->resolvedAction,
4217 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
4218 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 }
4220 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004221 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 }
4223 }
4224 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004225 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 }
4227
4228 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004229 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004230 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004232 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 }
4234
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004235 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004236 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004237 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004238 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239}
4240
Michael Wright3dd60e22019-03-27 22:06:44 +00004241void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4242 const size_t numMonitors = monitors.size();
4243 for (size_t i = 0; i < numMonitors; i++) {
4244 const Monitor& monitor = monitors[i];
4245 const sp<InputChannel>& channel = monitor.inputChannel;
4246 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4247 dump += "\n";
4248 }
4249}
4250
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004251status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004253 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254#endif
4255
4256 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004257 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004258 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004259 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 return BAD_VALUE;
4263 }
4264
Garfield Tan1c7bc862020-01-28 13:24:04 -08004265 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266
4267 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004268 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004269 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4272 } // release lock
4273
4274 // Wake the looper because some connections have changed.
4275 mLooper->wake();
4276 return OK;
4277}
4278
Michael Wright3dd60e22019-03-27 22:06:44 +00004279status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004280 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004281 { // acquire lock
4282 std::scoped_lock _l(mLock);
4283
4284 if (displayId < 0) {
4285 ALOGW("Attempted to register input monitor without a specified display.");
4286 return BAD_VALUE;
4287 }
4288
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004289 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004290 ALOGW("Attempted to register input monitor without an identifying token.");
4291 return BAD_VALUE;
4292 }
4293
Garfield Tan1c7bc862020-01-28 13:24:04 -08004294 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004295
4296 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004297 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004298 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004299
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 auto& monitorsByDisplay =
4301 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004302 monitorsByDisplay[displayId].emplace_back(inputChannel);
4303
4304 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004305 }
4306 // Wake the looper because some connections have changed.
4307 mLooper->wake();
4308 return OK;
4309}
4310
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4312#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004313 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314#endif
4315
4316 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004317 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318
4319 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4320 if (status) {
4321 return status;
4322 }
4323 } // release lock
4324
4325 // Wake the poll loop because removing the connection may have changed the current
4326 // synchronization state.
4327 mLooper->wake();
4328 return OK;
4329}
4330
4331status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004332 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004333 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004334 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004336 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337 return BAD_VALUE;
4338 }
4339
John Recke0710582019-09-26 13:46:12 -07004340 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004341 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004342 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004343
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344 if (connection->monitor) {
4345 removeMonitorChannelLocked(inputChannel);
4346 }
4347
4348 mLooper->removeFd(inputChannel->getFd());
4349
4350 nsecs_t currentTime = now();
4351 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4352
4353 connection->status = Connection::STATUS_ZOMBIE;
4354 return OK;
4355}
4356
4357void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004358 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4359 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4360}
4361
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004362void InputDispatcher::removeMonitorChannelLocked(
4363 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004364 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004365 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004366 std::vector<Monitor>& monitors = it->second;
4367 const size_t numMonitors = monitors.size();
4368 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004369 if (monitors[i].inputChannel == inputChannel) {
4370 monitors.erase(monitors.begin() + i);
4371 break;
4372 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004373 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004374 if (monitors.empty()) {
4375 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004376 } else {
4377 ++it;
4378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379 }
4380}
4381
Michael Wright3dd60e22019-03-27 22:06:44 +00004382status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4383 { // acquire lock
4384 std::scoped_lock _l(mLock);
4385 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4386
4387 if (!foundDisplayId) {
4388 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4389 return BAD_VALUE;
4390 }
4391 int32_t displayId = foundDisplayId.value();
4392
4393 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4394 if (stateIndex < 0) {
4395 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4396 return BAD_VALUE;
4397 }
4398
4399 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4400 std::optional<int32_t> foundDeviceId;
4401 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004402 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004403 foundDeviceId = state.deviceId;
4404 }
4405 }
4406 if (!foundDeviceId || !state.down) {
4407 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004408 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004409 return BAD_VALUE;
4410 }
4411 int32_t deviceId = foundDeviceId.value();
4412
4413 // Send cancel events to all the input channels we're stealing from.
4414 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004415 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004416 options.deviceId = deviceId;
4417 options.displayId = displayId;
4418 for (const TouchedWindow& window : state.windows) {
4419 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004420 if (channel != nullptr) {
4421 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4422 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004423 }
4424 // Then clear the current touch state so we stop dispatching to them as well.
4425 state.filterNonMonitors();
4426 }
4427 return OK;
4428}
4429
Michael Wright3dd60e22019-03-27 22:06:44 +00004430std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4431 const sp<IBinder>& token) {
4432 for (const auto& it : mGestureMonitorsByDisplay) {
4433 const std::vector<Monitor>& monitors = it.second;
4434 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004435 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004436 return it.first;
4437 }
4438 }
4439 }
4440 return std::nullopt;
4441}
4442
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004443sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4444 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004445 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004446 }
4447
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004448 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004449 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004450 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004451 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452 }
4453 }
Robert Carr4e670e52018-08-15 13:26:12 -07004454
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004455 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456}
4457
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004458void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4459 const sp<Connection>& connection, uint32_t seq,
4460 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004461 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4462 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 commandEntry->connection = connection;
4464 commandEntry->eventTime = currentTime;
4465 commandEntry->seq = seq;
4466 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004467 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468}
4469
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004470void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4471 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004473 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004475 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4476 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004478 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479}
4480
chaviw0c06c6e2019-01-09 13:27:07 -08004481void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004482 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004483 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4484 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004485 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4486 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004487 commandEntry->oldToken = oldToken;
4488 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004489 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004490}
4491
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004492void InputDispatcher::onAnrLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004493 const sp<InputApplicationHandle>& applicationHandle,
4494 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4495 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4497 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4498 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004499 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4500 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4501 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502
4503 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004504 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 struct tm tm;
4506 localtime_r(&t, &tm);
4507 char timestr[64];
4508 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004509 mLastAnrState.clear();
4510 mLastAnrState += INDENT "ANR:\n";
4511 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
4512 mLastAnrState +=
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004513 StringPrintf(INDENT2 "Window: %s\n",
4514 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004515 mLastAnrState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4516 mLastAnrState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4517 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason);
4518 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004520 std::unique_ptr<CommandEntry> commandEntry =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004521 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004523 commandEntry->inputChannel =
4524 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004526 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527}
4528
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004529void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530 mLock.unlock();
4531
4532 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4533
4534 mLock.lock();
4535}
4536
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004537void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 sp<Connection> connection = commandEntry->connection;
4539
4540 if (connection->status != Connection::STATUS_ZOMBIE) {
4541 mLock.unlock();
4542
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004543 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544
4545 mLock.lock();
4546 }
4547}
4548
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004549void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004550 sp<IBinder> oldToken = commandEntry->oldToken;
4551 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004552 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004553 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004554 mLock.lock();
4555}
4556
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004557void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004558 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004559 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560 mLock.unlock();
4561
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004562 nsecs_t newTimeout =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004563 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564
4565 mLock.lock();
4566
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004567 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568}
4569
4570void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4571 CommandEntry* commandEntry) {
4572 KeyEntry* entry = commandEntry->keyEntry;
4573
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004574 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575
4576 mLock.unlock();
4577
Michael Wright2b3c3302018-03-02 17:19:13 +00004578 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004579 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004580 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004581 : nullptr;
4582 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004583 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4584 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004585 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587
4588 mLock.lock();
4589
4590 if (delay < 0) {
4591 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4592 } else if (!delay) {
4593 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4594 } else {
4595 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4596 entry->interceptKeyWakeupTime = now() + delay;
4597 }
4598 entry->release();
4599}
4600
chaviwfd6d3512019-03-25 13:23:49 -07004601void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4602 mLock.unlock();
4603 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4604 mLock.lock();
4605}
4606
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004607void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004609 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004611 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612
4613 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004614 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004615 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004616 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004618 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004619
4620 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4621 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4622 std::string msg =
4623 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4624 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4625 dispatchEntry->eventEntry->appendDescription(msg);
4626 ALOGI("%s", msg.c_str());
4627 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004628 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004629
4630 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004631 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004632 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4633 restartEvent =
4634 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004635 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004636 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4637 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4638 handled);
4639 } else {
4640 restartEvent = false;
4641 }
4642
4643 // Dequeue the event and start the next cycle.
4644 // Note that because the lock might have been released, it is possible that the
4645 // contents of the wait queue to have been drained, so we need to double-check
4646 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004647 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4648 if (dispatchEntryIt != connection->waitQueue.end()) {
4649 dispatchEntry = *dispatchEntryIt;
4650 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004651 traceWaitQueueLength(connection);
4652 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004653 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004654 traceOutboundQueueLength(connection);
4655 } else {
4656 releaseDispatchEntry(dispatchEntry);
4657 }
4658 }
4659
4660 // Start the next dispatch cycle for this connection.
4661 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662}
4663
4664bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004665 DispatchEntry* dispatchEntry,
4666 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004667 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004668 if (!handled) {
4669 // Report the key as unhandled, since the fallback was not handled.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004670 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004671 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004672 return false;
4673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004675 // Get the fallback key state.
4676 // Clear it out after dispatching the UP.
4677 int32_t originalKeyCode = keyEntry->keyCode;
4678 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4679 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4680 connection->inputState.removeFallbackKey(originalKeyCode);
4681 }
4682
4683 if (handled || !dispatchEntry->hasForegroundTarget()) {
4684 // If the application handles the original key for which we previously
4685 // generated a fallback or if the window is not a foreground window,
4686 // then cancel the associated fallback key, if any.
4687 if (fallbackKeyCode != -1) {
4688 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004690 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004691 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4692 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4693 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004695 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004696 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697
4698 mLock.unlock();
4699
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004700 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004701 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702
4703 mLock.lock();
4704
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004705 // Cancel the fallback key.
4706 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004708 "application handled the original non-fallback key "
4709 "or is no longer a foreground target, "
4710 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 options.keyCode = fallbackKeyCode;
4712 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004714 connection->inputState.removeFallbackKey(originalKeyCode);
4715 }
4716 } else {
4717 // If the application did not handle a non-fallback key, first check
4718 // that we are in a good state to perform unhandled key event processing
4719 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004720 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004721 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004723 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004724 "since this is not an initial down. "
4725 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4726 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004728 return false;
4729 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004731 // Dispatch the unhandled key to the policy.
4732#if DEBUG_OUTBOUND_EVENT_DETAILS
4733 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004734 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4735 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004736#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004737 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004738
4739 mLock.unlock();
4740
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004741 bool fallback =
4742 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4743 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004744
4745 mLock.lock();
4746
4747 if (connection->status != Connection::STATUS_NORMAL) {
4748 connection->inputState.removeFallbackKey(originalKeyCode);
4749 return false;
4750 }
4751
4752 // Latch the fallback keycode for this key on an initial down.
4753 // The fallback keycode cannot change at any other point in the lifecycle.
4754 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004756 fallbackKeyCode = event.getKeyCode();
4757 } else {
4758 fallbackKeyCode = AKEYCODE_UNKNOWN;
4759 }
4760 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4761 }
4762
4763 ALOG_ASSERT(fallbackKeyCode != -1);
4764
4765 // Cancel the fallback key if the policy decides not to send it anymore.
4766 // We will continue to dispatch the key to the policy but we will no
4767 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004768 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4769 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004770#if DEBUG_OUTBOUND_EVENT_DETAILS
4771 if (fallback) {
4772 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004773 "as a fallback for %d, but on the DOWN it had requested "
4774 "to send %d instead. Fallback canceled.",
4775 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004776 } else {
4777 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004778 "but on the DOWN it had requested to send %d. "
4779 "Fallback canceled.",
4780 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004781 }
4782#endif
4783
4784 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4785 "canceling fallback, policy no longer desires it");
4786 options.keyCode = fallbackKeyCode;
4787 synthesizeCancelationEventsForConnectionLocked(connection, options);
4788
4789 fallback = false;
4790 fallbackKeyCode = AKEYCODE_UNKNOWN;
4791 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004792 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004793 }
4794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795
4796#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004797 {
4798 std::string msg;
4799 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4800 connection->inputState.getFallbackKeys();
4801 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004802 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004804 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004805 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004806 }
4807#endif
4808
4809 if (fallback) {
4810 // Restart the dispatch cycle using the fallback key.
4811 keyEntry->eventTime = event.getEventTime();
4812 keyEntry->deviceId = event.getDeviceId();
4813 keyEntry->source = event.getSource();
4814 keyEntry->displayId = event.getDisplayId();
4815 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4816 keyEntry->keyCode = fallbackKeyCode;
4817 keyEntry->scanCode = event.getScanCode();
4818 keyEntry->metaState = event.getMetaState();
4819 keyEntry->repeatCount = event.getRepeatCount();
4820 keyEntry->downTime = event.getDownTime();
4821 keyEntry->syntheticRepeat = false;
4822
4823#if DEBUG_OUTBOUND_EVENT_DETAILS
4824 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004825 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4826 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004827#endif
4828 return true; // restart the event
4829 } else {
4830#if DEBUG_OUTBOUND_EVENT_DETAILS
4831 ALOGD("Unhandled key event: No fallback key.");
4832#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004833
4834 // Report the key as unhandled, since there is no fallback key.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004835 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836 }
4837 }
4838 return false;
4839}
4840
4841bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004842 DispatchEntry* dispatchEntry,
4843 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844 return false;
4845}
4846
4847void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4848 mLock.unlock();
4849
4850 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4851
4852 mLock.lock();
4853}
4854
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004855KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4856 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004857 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08004858 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
4859 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004860 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861}
4862
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004863void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
4864 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 // TODO Write some statistics about how long we spend waiting.
4866}
4867
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004868/**
4869 * Report the touch event latency to the statsd server.
4870 * Input events are reported for statistics if:
4871 * - This is a touchscreen event
4872 * - InputFilter is not enabled
4873 * - Event is not injected or synthesized
4874 *
4875 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4876 * from getting aggregated with the "old" data.
4877 */
4878void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4879 REQUIRES(mLock) {
4880 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4881 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4882 if (!reportForStatistics) {
4883 return;
4884 }
4885
4886 if (mTouchStatistics.shouldReport()) {
4887 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4888 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4889 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4890 mTouchStatistics.reset();
4891 }
4892 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4893 mTouchStatistics.addValue(latencyMicros);
4894}
4895
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896void InputDispatcher::traceInboundQueueLengthLocked() {
4897 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004898 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899 }
4900}
4901
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004902void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903 if (ATRACE_ENABLED()) {
4904 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004905 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004906 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907 }
4908}
4909
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004910void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911 if (ATRACE_ENABLED()) {
4912 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004913 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004914 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915 }
4916}
4917
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004918void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004919 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004921 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 dumpDispatchStateLocked(dump);
4923
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004924 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004925 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004926 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927 }
4928}
4929
4930void InputDispatcher::monitor() {
4931 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004932 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004934 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935}
4936
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004937/**
4938 * Wake up the dispatcher and wait until it processes all events and commands.
4939 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4940 * this method can be safely called from any thread, as long as you've ensured that
4941 * the work you are interested in completing has already been queued.
4942 */
4943bool InputDispatcher::waitForIdle() {
4944 /**
4945 * Timeout should represent the longest possible time that a device might spend processing
4946 * events and commands.
4947 */
4948 constexpr std::chrono::duration TIMEOUT = 100ms;
4949 std::unique_lock lock(mLock);
4950 mLooper->wake();
4951 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4952 return result == std::cv_status::no_timeout;
4953}
4954
Garfield Tane84e6f92019-08-29 17:28:41 -07004955} // namespace android::inputdispatcher