blob: e6e3347ae98d4af24413ce84be7d885407443374 [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.
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -070081constexpr std::chrono::nanoseconds DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5s;
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
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700623/**
624 * Return true if the events preceding this incoming motion event should be dropped
625 * Return false otherwise (the default behaviour)
626 */
627bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
628 bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
629 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
630 if (isPointerDownEvent &&
631 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
632 mInputTargetWaitApplicationToken != nullptr) {
633 int32_t displayId = motionEntry.displayId;
634 int32_t x = static_cast<int32_t>(
635 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
636 int32_t y = static_cast<int32_t>(
637 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
638 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
639 if (touchedWindowHandle != nullptr &&
640 touchedWindowHandle->getApplicationToken() != mInputTargetWaitApplicationToken) {
641 // User touched a different application than the one we are waiting on.
642 // Flag the event, and start pruning the input queue.
643 ALOGI("Pruning input queue because user touched a different application");
644 return true;
645 }
646 }
647 return false;
648}
649
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700651 bool needWake = mInboundQueue.empty();
652 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653 traceInboundQueueLengthLocked();
654
655 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700656 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700657 // Optimize app switch latency.
658 // If the application takes too long to catch up then we drop all events preceding
659 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700660 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700661 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700662 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700663 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700664 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700665 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700667 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700669 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700670 mAppSwitchSawKeyDown = false;
671 needWake = true;
672 }
673 }
674 }
675 break;
676 }
677
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700678 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700679 // Optimize case where the current application is unresponsive and the user
680 // decides to touch a window in a different application.
681 // If the application takes too long to catch up then we drop all events preceding
682 // the touch into the other window.
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700683 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
684 mNextUnblockedEvent = entry;
685 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700687 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100689 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700690 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
691 break;
692 }
693 case EventEntry::Type::CONFIGURATION_CHANGED:
694 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700695 // nothing to do
696 break;
697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
699
700 return needWake;
701}
702
703void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
704 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700705 mRecentQueue.push_back(entry);
706 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
707 mRecentQueue.front()->release();
708 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800709 }
710}
711
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700712sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
713 int32_t y, bool addOutsideTargets,
714 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800716 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
717 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 const InputWindowInfo* windowInfo = windowHandle->getInfo();
719 if (windowInfo->displayId == displayId) {
720 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800721
722 if (windowInfo->visible) {
723 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700724 bool isTouchModal = (flags &
725 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
726 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800728 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700729 if (portalToDisplayId != ADISPLAY_ID_NONE &&
730 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800731 if (addPortalWindows) {
732 // For the monitoring channels of the display.
733 mTempTouchState.addPortalWindow(windowHandle);
734 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700735 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
736 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 // Found window.
739 return windowHandle;
740 }
741 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800742
743 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700744 mTempTouchState.addOrUpdateWindow(windowHandle,
745 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
746 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749 }
750 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700751 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752}
753
Garfield Tane84e6f92019-08-29 17:28:41 -0700754std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000755 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
756 std::vector<TouchedMonitor> touchedMonitors;
757
758 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
759 addGestureMonitors(monitors, touchedMonitors);
760 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
761 const InputWindowInfo* windowInfo = portalWindow->getInfo();
762 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700763 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
764 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000765 }
766 return touchedMonitors;
767}
768
769void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700770 std::vector<TouchedMonitor>& outTouchedMonitors,
771 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000772 if (monitors.empty()) {
773 return;
774 }
775 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
776 for (const Monitor& monitor : monitors) {
777 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
778 }
779}
780
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700781void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 const char* reason;
783 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700784 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700786 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700788 reason = "inbound event was dropped because the policy consumed it";
789 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700790 case DropReason::DISABLED:
791 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700792 ALOGI("Dropped event because input dispatch is disabled.");
793 }
794 reason = "inbound event was dropped because input dispatch is disabled";
795 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700796 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700797 ALOGI("Dropped event because of pending overdue app switch.");
798 reason = "inbound event was dropped because of pending overdue app switch";
799 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700800 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700801 ALOGI("Dropped event because the current application is not responding and the user "
802 "has started interacting with a different application.");
803 reason = "inbound event was dropped because the current application is not responding "
804 "and the user has started interacting with a different application";
805 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700806 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700807 ALOGI("Dropped event because it is stale.");
808 reason = "inbound event was dropped because it is stale";
809 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700810 case DropReason::NOT_DROPPED: {
811 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 }
815
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700816 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700817 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
819 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700820 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700822 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700823 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
824 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700825 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
826 synthesizeCancelationEventsForAllConnectionsLocked(options);
827 } else {
828 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
829 synthesizeCancelationEventsForAllConnectionsLocked(options);
830 }
831 break;
832 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100833 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700834 case EventEntry::Type::CONFIGURATION_CHANGED:
835 case EventEntry::Type::DEVICE_RESET: {
836 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
837 break;
838 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 }
840}
841
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800842static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700843 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
844 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845}
846
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700847bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
848 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
849 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
850 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851}
852
853bool InputDispatcher::isAppSwitchPendingLocked() {
854 return mAppSwitchDueTime != LONG_LONG_MAX;
855}
856
857void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
858 mAppSwitchDueTime = LONG_LONG_MAX;
859
860#if DEBUG_APP_SWITCH
861 if (handled) {
862 ALOGD("App switch has arrived.");
863 } else {
864 ALOGD("App switch was abandoned.");
865 }
866#endif
867}
868
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700870 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871}
872
873bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700874 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 return false;
876 }
877
878 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700879 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700880 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700882 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883
884 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700885 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 return true;
887}
888
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700889void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
890 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891}
892
893void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700894 while (!mInboundQueue.empty()) {
895 EventEntry* entry = mInboundQueue.front();
896 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 releaseInboundEventLocked(entry);
898 }
899 traceInboundQueueLengthLocked();
900}
901
902void InputDispatcher::releasePendingEventLocked() {
903 if (mPendingEvent) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700904 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700906 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 }
908}
909
910void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
911 InjectionState* injectionState = entry->injectionState;
912 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
913#if DEBUG_DISPATCH_CYCLE
914 ALOGD("Injected inbound event was dropped.");
915#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800916 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917 }
918 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700919 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 }
921 addRecentEventLocked(entry);
922 entry->release();
923}
924
925void InputDispatcher::resetKeyRepeatLocked() {
926 if (mKeyRepeatState.lastKeyEntry) {
927 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700928 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 }
930}
931
Garfield Tane84e6f92019-08-29 17:28:41 -0700932KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
934
935 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700936 uint32_t policyFlags = entry->policyFlags &
937 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 if (entry->refCount == 1) {
939 entry->recycle();
Garfield Tan1c7bc862020-01-28 13:24:04 -0800940 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941 entry->eventTime = currentTime;
942 entry->policyFlags = policyFlags;
943 entry->repeatCount += 1;
944 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700945 KeyEntry* newEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -0800946 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800947 entry->displayId, policyFlags, entry->action, entry->flags,
948 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700949 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950
951 mKeyRepeatState.lastKeyEntry = newEntry;
952 entry->release();
953
954 entry = newEntry;
955 }
956 entry->syntheticRepeat = true;
957
958 // Increment reference count since we keep a reference to the event in
959 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
960 entry->refCount += 1;
961
962 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
963 return entry;
964}
965
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700966bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
967 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700969 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970#endif
971
972 // Reset key repeating in case a keyboard device was added or removed or something.
973 resetKeyRepeatLocked();
974
975 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700976 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
977 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700979 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980 return true;
981}
982
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700983bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700985 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987#endif
988
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 options.deviceId = entry->deviceId;
991 synthesizeCancelationEventsForAllConnectionsLocked(options);
992 return true;
993}
994
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100995void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700996 if (mPendingEvent != nullptr) {
997 // Move the pending event to the front of the queue. This will give the chance
998 // for the pending event to get dispatched to the newly focused window
999 mInboundQueue.push_front(mPendingEvent);
1000 mPendingEvent = nullptr;
1001 }
1002
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001003 FocusEntry* focusEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08001004 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07001005
1006 // This event should go to the front of the queue, but behind all other focus events
1007 // Find the last focus event, and insert right after it
1008 std::deque<EventEntry*>::reverse_iterator it =
1009 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1010 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1011
1012 // Maintain the order of focus events. Insert the entry after all other focus events.
1013 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001014}
1015
1016void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1017 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1018 if (channel == nullptr) {
1019 return; // Window has gone away
1020 }
1021 InputTarget target;
1022 target.inputChannel = channel;
1023 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1024 entry->dispatchInProgress = true;
1025
1026 dispatchEventLocked(currentTime, entry, {target});
1027}
1028
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001032 if (!entry->dispatchInProgress) {
1033 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1034 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1035 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1036 if (mKeyRepeatState.lastKeyEntry &&
1037 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 // We have seen two identical key downs in a row which indicates that the device
1039 // driver is automatically generating key repeats itself. We take note of the
1040 // repeat here, but we disable our own next key repeat timer since it is clear that
1041 // we will not need to synthesize key repeats ourselves.
1042 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1043 resetKeyRepeatLocked();
1044 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1045 } else {
1046 // Not a repeat. Save key down state in case we do see a repeat later.
1047 resetKeyRepeatLocked();
1048 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1049 }
1050 mKeyRepeatState.lastKeyEntry = entry;
1051 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 resetKeyRepeatLocked();
1054 }
1055
1056 if (entry->repeatCount == 1) {
1057 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1058 } else {
1059 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1060 }
1061
1062 entry->dispatchInProgress = true;
1063
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001064 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 }
1066
1067 // Handle case where the policy asked us to try again later last time.
1068 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1069 if (currentTime < entry->interceptKeyWakeupTime) {
1070 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1071 *nextWakeupTime = entry->interceptKeyWakeupTime;
1072 }
1073 return false; // wait until next wakeup
1074 }
1075 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1076 entry->interceptKeyWakeupTime = 0;
1077 }
1078
1079 // Give the policy a chance to intercept the key.
1080 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1081 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001082 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001083 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001084 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001085 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001086 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001087 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 }
1089 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001090 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 entry->refCount += 1;
1092 return false; // wait for the command to run
1093 } else {
1094 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1095 }
1096 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001097 if (*dropReason == DropReason::NOT_DROPPED) {
1098 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 }
1100 }
1101
1102 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001105 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001106 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001107 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108 return true;
1109 }
1110
1111 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001112 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001113 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001114 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1116 return false;
1117 }
1118
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001119 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1121 return true;
1122 }
1123
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001124 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001125 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126
1127 // Dispatch the key.
1128 dispatchEventLocked(currentTime, entry, inputTargets);
1129 return true;
1130}
1131
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001132void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001134 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001135 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1136 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001137 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1138 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1139 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140#endif
1141}
1142
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001143bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1144 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001145 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001147 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 entry->dispatchInProgress = true;
1149
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001150 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 }
1152
1153 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001154 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001155 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001156 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001157 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 return true;
1159 }
1160
1161 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1162
1163 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001164 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165
1166 bool conflictingPointerActions = false;
1167 int32_t injectionResult;
1168 if (isPointerEvent) {
1169 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001170 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001171 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001172 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 } else {
1174 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001175 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001176 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 }
1178 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1179 return false;
1180 }
1181
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001182 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001183 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1184 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1185 return true;
1186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001188 CancelationOptions::Mode mode(isPointerEvent
1189 ? CancelationOptions::CANCEL_POINTER_EVENTS
1190 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1191 CancelationOptions options(mode, "input event injection failed");
1192 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 return true;
1194 }
1195
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001196 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001197 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001199 if (isPointerEvent) {
1200 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
1201 if (stateIndex >= 0) {
1202 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001203 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001204 // The event has gone through these portal windows, so we add monitoring targets of
1205 // the corresponding displays as well.
1206 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001207 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001208 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001209 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001210 }
1211 }
1212 }
1213 }
1214
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 // Dispatch the motion.
1216 if (conflictingPointerActions) {
1217 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001218 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 synthesizeCancelationEventsForAllConnectionsLocked(options);
1220 }
1221 dispatchEventLocked(currentTime, entry, inputTargets);
1222 return true;
1223}
1224
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001225void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001227 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001228 ", policyFlags=0x%x, "
1229 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1230 "metaState=0x%x, buttonState=0x%x,"
1231 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001232 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1233 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1234 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001236 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001238 "x=%f, y=%f, pressure=%f, size=%f, "
1239 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1240 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001241 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1242 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1243 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1244 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1245 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1246 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1247 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1248 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1249 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1250 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 }
1252#endif
1253}
1254
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001255void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1256 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001257 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258#if DEBUG_DISPATCH_CYCLE
1259 ALOGD("dispatchEventToCurrentInputTargets");
1260#endif
1261
1262 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1263
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001264 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001266 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001267 sp<Connection> connection =
1268 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001269 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001270 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001272 if (DEBUG_FOCUS) {
1273 ALOGD("Dropping event delivery to target with channel '%s' because it "
1274 "is no longer registered with the input dispatcher.",
1275 inputTarget.inputChannel->getName().c_str());
1276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 }
1278 }
1279}
1280
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001281int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001282 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001284 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001285 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001287 if (DEBUG_FOCUS) {
1288 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1291 mInputTargetWaitStartTime = currentTime;
1292 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1293 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001294 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 }
1296 } else {
1297 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001298 ALOGI("Waiting for application to become ready for input: %s. Reason: %s",
1299 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1300 std::chrono::nanoseconds timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001301 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001303 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001304 timeout =
1305 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 } else {
1307 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1308 }
1309
1310 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1311 mInputTargetWaitStartTime = currentTime;
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001312 mInputTargetWaitTimeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001314 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315
Yi Kong9b14ac62018-07-17 13:48:38 -07001316 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001317 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 }
Robert Carr740167f2018-10-11 19:03:41 -07001319 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1320 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 }
1322 }
1323 }
1324
1325 if (mInputTargetWaitTimeoutExpired) {
1326 return INPUT_EVENT_INJECTION_TIMED_OUT;
1327 }
1328
1329 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001330 onAnrLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001331 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332
1333 // Force poll loop to wake up immediately on next iteration once we get the
1334 // ANR response back from the policy.
1335 *nextWakeupTime = LONG_LONG_MIN;
1336 return INPUT_EVENT_INJECTION_PENDING;
1337 } else {
1338 // Force poll loop to wake up when timeout is due.
1339 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1340 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1341 }
1342 return INPUT_EVENT_INJECTION_PENDING;
1343 }
1344}
1345
Robert Carr803535b2018-08-02 16:38:15 -07001346void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1347 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1348 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1349 state.removeWindowByToken(token);
1350 }
1351}
1352
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001353void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001354 nsecs_t timeoutExtension, const sp<IBinder>& inputConnectionToken) {
1355 if (timeoutExtension > 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356 // Extend the timeout.
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001357 mInputTargetWaitTimeoutTime = now() + timeoutExtension;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 } else {
1359 // Give up.
1360 mInputTargetWaitTimeoutExpired = true;
1361
1362 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001363 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001364 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001365 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001367 if (connection->status == Connection::STATUS_NORMAL) {
1368 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1369 "application not responding");
1370 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371 }
1372 }
1373 }
1374}
1375
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001376void InputDispatcher::resetAnrTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001377 if (DEBUG_FOCUS) {
1378 ALOGD("Resetting ANR timeouts.");
1379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380
1381 // Reset input target wait timeout.
1382 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001383 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384}
1385
Tiger Huang721e26f2018-07-24 22:26:19 +08001386/**
1387 * Get the display id that the given event should go to. If this event specifies a valid display id,
1388 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1389 * Focused display is the display that the user most recently interacted with.
1390 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001391int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001392 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001393 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001394 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001395 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1396 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001397 break;
1398 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001399 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1401 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001402 break;
1403 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001404 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001405 case EventEntry::Type::CONFIGURATION_CHANGED:
1406 case EventEntry::Type::DEVICE_RESET: {
1407 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001408 return ADISPLAY_ID_NONE;
1409 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001410 }
1411 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1412}
1413
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001415 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001416 std::vector<InputTarget>& inputTargets,
1417 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001418 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419
Tiger Huang721e26f2018-07-24 22:26:19 +08001420 int32_t displayId = getTargetDisplayId(entry);
1421 sp<InputWindowHandle> focusedWindowHandle =
1422 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1423 sp<InputApplicationHandle> focusedApplicationHandle =
1424 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1425
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426 // If there is no currently focused window and no focused application
1427 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001428 if (focusedWindowHandle == nullptr) {
1429 if (focusedApplicationHandle != nullptr) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001430 return handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1431 nullptr, nextWakeupTime,
1432 "Waiting because no window has focus but there is "
1433 "a focused application that may eventually add a "
1434 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 }
1436
Arthur Hung3b413f22018-10-26 18:05:34 +08001437 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001438 "%" PRId32 ".",
1439 displayId);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001440 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441 }
1442
1443 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001444 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001445 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 }
1447
Jeff Brownffb49772014-10-10 19:01:34 -07001448 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001449 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001450 if (!reason.empty()) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001451 return handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1452 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 }
1454
1455 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001456 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001457 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1458 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459
1460 // Done.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001461 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462}
1463
1464int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001465 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001466 std::vector<InputTarget>& inputTargets,
1467 nsecs_t* nextWakeupTime,
1468 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001469 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 enum InjectionPermission {
1471 INJECTION_PERMISSION_UNKNOWN,
1472 INJECTION_PERMISSION_GRANTED,
1473 INJECTION_PERMISSION_DENIED
1474 };
1475
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 // For security reasons, we defer updating the touch state until we are sure that
1477 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001478 int32_t displayId = entry.displayId;
1479 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1481
1482 // Update the touch state as needed based on the properties of the touch event.
1483 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1484 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1485 sp<InputWindowHandle> newHoverWindowHandle;
1486
Jeff Brownf086ddb2014-02-11 14:28:48 -08001487 // Copy current touch state into mTempTouchState.
1488 // This state is always reset at the end of this function, so if we don't find state
1489 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001490 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001491 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1492 if (oldStateIndex >= 0) {
1493 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1494 mTempTouchState.copyFrom(*oldState);
1495 }
1496
1497 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001498 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001499 (mTempTouchState.deviceId != entry.deviceId || mTempTouchState.source != entry.source ||
1500 mTempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001501 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1502 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1503 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1504 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1505 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001506 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 bool wrongDevice = false;
1508 if (newGesture) {
1509 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001510 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001511 if (DEBUG_FOCUS) {
1512 ALOGD("Dropping event because a pointer for a different device is already down "
1513 "in display %" PRId32,
1514 displayId);
1515 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001516 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1518 switchedDevice = false;
1519 wrongDevice = true;
1520 goto Failed;
1521 }
1522 mTempTouchState.reset();
1523 mTempTouchState.down = down;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001524 mTempTouchState.deviceId = entry.deviceId;
1525 mTempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 mTempTouchState.displayId = displayId;
1527 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001528 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001529 if (DEBUG_FOCUS) {
1530 ALOGI("Dropping move event because a pointer for a different device is already active "
1531 "in display %" PRId32,
1532 displayId);
1533 }
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001534 // TODO: test multiple simultaneous input streams.
1535 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1536 switchedDevice = false;
1537 wrongDevice = true;
1538 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 }
1540
1541 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1542 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1543
Garfield Tan00f511d2019-06-12 16:55:40 -07001544 int32_t x;
1545 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001547 // Always dispatch mouse events to cursor position.
1548 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001549 x = int32_t(entry.xCursorPosition);
1550 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001551 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001552 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1553 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001554 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001555 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001556 sp<InputWindowHandle> newTouchedWindowHandle =
1557 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1558 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001559
1560 std::vector<TouchedMonitor> newGestureMonitors = isDown
1561 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1562 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001565 if (newTouchedWindowHandle != nullptr &&
1566 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001567 // New window supports splitting, but we should never split mouse events.
1568 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569 } else if (isSplit) {
1570 // New window does not support splitting but we have already split events.
1571 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001572 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 }
1574
1575 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001576 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 // Try to assign the pointer to the first foreground window we find, if there is one.
1578 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001579 }
1580
1581 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1582 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001583 "(%d, %d) in display %" PRId32 ".",
1584 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001585 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1586 goto Failed;
1587 }
1588
1589 if (newTouchedWindowHandle != nullptr) {
1590 // Set target flags.
1591 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1592 if (isSplit) {
1593 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001595 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1596 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1597 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1598 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1599 }
1600
1601 // Update hover state.
1602 if (isHoverAction) {
1603 newHoverWindowHandle = newTouchedWindowHandle;
1604 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1605 newHoverWindowHandle = mLastHoverWindowHandle;
1606 }
1607
1608 // Update the temporary touch state.
1609 BitSet32 pointerIds;
1610 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001611 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001612 pointerIds.markBit(pointerId);
1613 }
1614 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 }
1616
Michael Wright3dd60e22019-03-27 22:06:44 +00001617 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618 } else {
1619 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1620
1621 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001622 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001623 if (DEBUG_FOCUS) {
1624 ALOGD("Dropping event because the pointer is not down or we previously "
1625 "dropped the pointer down event in display %" PRId32,
1626 displayId);
1627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1629 goto Failed;
1630 }
1631
1632 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001633 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001634 mTempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001635 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1636 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637
1638 sp<InputWindowHandle> oldTouchedWindowHandle =
1639 mTempTouchState.getFirstForegroundWindowHandle();
1640 sp<InputWindowHandle> newTouchedWindowHandle =
1641 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001642 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1643 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001644 if (DEBUG_FOCUS) {
1645 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1646 oldTouchedWindowHandle->getName().c_str(),
1647 newTouchedWindowHandle->getName().c_str(), displayId);
1648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 // Make a slippery exit from the old window.
1650 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001651 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1652 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653
1654 // Make a slippery entrance into the new window.
1655 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1656 isSplit = true;
1657 }
1658
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001659 int32_t targetFlags =
1660 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 if (isSplit) {
1662 targetFlags |= InputTarget::FLAG_SPLIT;
1663 }
1664 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1665 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1666 }
1667
1668 BitSet32 pointerIds;
1669 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001670 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 }
1672 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1673 }
1674 }
1675 }
1676
1677 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1678 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001679 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680#if DEBUG_HOVER
1681 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001682 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683#endif
1684 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001685 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1686 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687 }
1688
1689 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001690 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691#if DEBUG_HOVER
1692 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001693 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694#endif
1695 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001696 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1697 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 }
1699 }
1700
1701 // Check permission to inject into all touched foreground windows and ensure there
1702 // is at least one touched foreground window.
1703 {
1704 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001705 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1707 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001708 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1710 injectionPermission = INJECTION_PERMISSION_DENIED;
1711 goto Failed;
1712 }
1713 }
1714 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001715 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1716 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001717 if (DEBUG_FOCUS) {
1718 ALOGD("Dropping event because there is no touched foreground window in display "
1719 "%" PRId32 " or gesture monitor to receive it.",
1720 displayId);
1721 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1723 goto Failed;
1724 }
1725
1726 // Permission granted to injection into all touched foreground windows.
1727 injectionPermission = INJECTION_PERMISSION_GRANTED;
1728 }
1729
1730 // Check whether windows listening for outside touches are owned by the same UID. If it is
1731 // set the policy flag that we will not reveal coordinate information to this window.
1732 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1733 sp<InputWindowHandle> foregroundWindowHandle =
1734 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001735 if (foregroundWindowHandle) {
1736 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1737 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1738 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1739 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1740 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1741 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001742 InputTarget::FLAG_ZERO_COORDS,
1743 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 }
1746 }
1747 }
1748 }
1749
1750 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001751 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001753 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001754 std::string reason =
1755 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1756 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001757 if (!reason.empty()) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001758 return handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1759 touchedWindow.windowHandle, nextWakeupTime,
1760 reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 }
1762 }
1763 }
1764
1765 // If this is the first pointer going down and the touched window has a wallpaper
1766 // then also add the touched wallpaper windows so they are locked in for the duration
1767 // of the touch gesture.
1768 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1769 // engine only supports touch events. We would need to add a mechanism similar
1770 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1771 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1772 sp<InputWindowHandle> foregroundWindowHandle =
1773 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001774 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001775 const std::vector<sp<InputWindowHandle>> windowHandles =
1776 getWindowHandlesLocked(displayId);
1777 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001779 if (info->displayId == displayId &&
1780 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1781 mTempTouchState
1782 .addOrUpdateWindow(windowHandle,
1783 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1784 InputTarget::
1785 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1786 InputTarget::FLAG_DISPATCH_AS_IS,
1787 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 }
1789 }
1790 }
1791 }
1792
1793 // Success! Output targets.
1794 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1795
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001796 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001798 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 }
1800
Michael Wright3dd60e22019-03-27 22:06:44 +00001801 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1802 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001803 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001804 }
1805
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 // Drop the outside or hover touch windows since we will not care about them
1807 // in the next iteration.
1808 mTempTouchState.filterNonAsIsTouchWindows();
1809
1810Failed:
1811 // Check injection permission once and for all.
1812 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001813 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 injectionPermission = INJECTION_PERMISSION_GRANTED;
1815 } else {
1816 injectionPermission = INJECTION_PERMISSION_DENIED;
1817 }
1818 }
1819
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001820 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1821 return injectionResult;
1822 }
1823
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001825 if (!wrongDevice) {
1826 if (switchedDevice) {
1827 if (DEBUG_FOCUS) {
1828 ALOGD("Conflicting pointer actions: Switched to a different device.");
1829 }
1830 *outConflictingPointerActions = true;
1831 }
1832
1833 if (isHoverAction) {
1834 // Started hovering, therefore no longer down.
1835 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001836 if (DEBUG_FOCUS) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001837 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1838 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840 *outConflictingPointerActions = true;
1841 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001842 mTempTouchState.reset();
1843 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1844 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1845 mTempTouchState.deviceId = entry.deviceId;
1846 mTempTouchState.source = entry.source;
1847 mTempTouchState.displayId = displayId;
1848 }
1849 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1850 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1851 // All pointers up or canceled.
1852 mTempTouchState.reset();
1853 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1854 // First pointer went down.
1855 if (oldState && oldState->down) {
1856 if (DEBUG_FOCUS) {
1857 ALOGD("Conflicting pointer actions: Down received while already down.");
1858 }
1859 *outConflictingPointerActions = true;
1860 }
1861 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1862 // One pointer went up.
1863 if (isSplit) {
1864 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1865 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001867 for (size_t i = 0; i < mTempTouchState.windows.size();) {
1868 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1869 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1870 touchedWindow.pointerIds.clearBit(pointerId);
1871 if (touchedWindow.pointerIds.isEmpty()) {
1872 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
1873 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001876 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001878 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001879 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001880
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001881 // Save changes unless the action was scroll in which case the temporary touch
1882 // state was only valid for this one action.
1883 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1884 if (mTempTouchState.displayId >= 0) {
1885 if (oldStateIndex >= 0) {
1886 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1887 } else {
1888 mTouchStatesByDisplay.add(displayId, mTempTouchState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001889 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001890 } else if (oldStateIndex >= 0) {
1891 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001895 // Update hover state.
1896 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 }
1898
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 return injectionResult;
1900}
1901
1902void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001903 int32_t targetFlags, BitSet32 pointerIds,
1904 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001905 std::vector<InputTarget>::iterator it =
1906 std::find_if(inputTargets.begin(), inputTargets.end(),
1907 [&windowHandle](const InputTarget& inputTarget) {
1908 return inputTarget.inputChannel->getConnectionToken() ==
1909 windowHandle->getToken();
1910 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00001911
Chavi Weingarten114b77f2020-01-15 22:35:10 +00001912 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001913
1914 if (it == inputTargets.end()) {
1915 InputTarget inputTarget;
1916 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1917 if (inputChannel == nullptr) {
1918 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1919 return;
1920 }
1921 inputTarget.inputChannel = inputChannel;
1922 inputTarget.flags = targetFlags;
1923 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
1924 inputTargets.push_back(inputTarget);
1925 it = inputTargets.end() - 1;
1926 }
1927
1928 ALOG_ASSERT(it->flags == targetFlags);
1929 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
1930
1931 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
1932 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933}
1934
Michael Wright3dd60e22019-03-27 22:06:44 +00001935void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001936 int32_t displayId, float xOffset,
1937 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001938 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1939 mGlobalMonitorsByDisplay.find(displayId);
1940
1941 if (it != mGlobalMonitorsByDisplay.end()) {
1942 const std::vector<Monitor>& monitors = it->second;
1943 for (const Monitor& monitor : monitors) {
1944 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 }
1947}
1948
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001949void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1950 float yOffset,
1951 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001952 InputTarget target;
1953 target.inputChannel = monitor.inputChannel;
1954 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001955 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00001956 inputTargets.push_back(target);
1957}
1958
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001960 const InjectionState* injectionState) {
1961 if (injectionState &&
1962 (windowHandle == nullptr ||
1963 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1964 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001965 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001967 "owned by uid %d",
1968 injectionState->injectorPid, injectionState->injectorUid,
1969 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 } else {
1971 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001972 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 }
1974 return false;
1975 }
1976 return true;
1977}
1978
Robert Carr9cada032020-04-13 17:21:08 -07001979/**
1980 * Indicate whether one window handle should be considered as obscuring
1981 * another window handle. We only check a few preconditions. Actually
1982 * checking the bounds is left to the caller.
1983 */
1984static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
1985 const sp<InputWindowHandle>& otherHandle) {
1986 // Compare by token so cloned layers aren't counted
1987 if (haveSameToken(windowHandle, otherHandle)) {
1988 return false;
1989 }
1990 auto info = windowHandle->getInfo();
1991 auto otherInfo = otherHandle->getInfo();
1992 if (!otherInfo->visible) {
1993 return false;
1994 } else if (info->ownerPid == otherInfo->ownerPid && otherHandle->getToken() == nullptr) {
1995 // In general, if ownerPid is the same we don't want to generate occlusion
1996 // events. This line is now necessary since we are including all Surfaces
1997 // in occlusion calculation, so if we didn't check PID like this SurfaceView
1998 // would occlude their parents. On the other hand before we started including
1999 // all surfaces in occlusion calculation and had this line, we would count
2000 // windows with an input channel from the same PID as occluding, and so we
2001 // preserve this behavior with the getToken() == null check.
2002 return false;
2003 } else if (otherInfo->isTrustedOverlay()) {
2004 return false;
2005 } else if (otherInfo->displayId != info->displayId) {
2006 return false;
2007 }
2008 return true;
2009}
2010
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002011bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2012 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002014 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2015 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002016 if (windowHandle == otherHandle) {
2017 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002020 if (canBeObscuredBy(windowHandle, otherHandle) &&
2021 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022 return true;
2023 }
2024 }
2025 return false;
2026}
2027
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002028bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2029 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002030 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002031 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002032 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002033 if (windowHandle == otherHandle) {
2034 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002035 }
2036
2037 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002038 if (canBeObscuredBy(windowHandle, otherHandle) &&
2039 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002040 return true;
2041 }
2042 }
2043 return false;
2044}
2045
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002046std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
2047 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002048 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07002049 // If the window is paused then keep waiting.
2050 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002051 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002052 }
2053
2054 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07002055 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002056 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002057 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002058 "registered with the input dispatcher. The window may be in the "
2059 "process of being removed.",
2060 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002061 }
2062
2063 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07002064 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002065 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002066 "The window may be in the process of being removed.",
2067 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07002068 }
2069
2070 // If the connection is backed up then keep waiting.
2071 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002072 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002073 "Outbound queue length: %zu. Wait queue length: %zu.",
2074 targetType, connection->outboundQueue.size(),
2075 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07002076 }
2077
2078 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002079 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07002080 // If the event is a key event, then we must wait for all previous events to
2081 // complete before delivering it because previous events may have the
2082 // side-effect of transferring focus to a different window and we want to
2083 // ensure that the following keys are sent to the new window.
2084 //
2085 // Suppose the user touches a button in a window then immediately presses "A".
2086 // If the button causes a pop-up window to appear then we want to ensure that
2087 // the "A" key is delivered to the new pop-up window. This is because users
2088 // often anticipate pending UI changes when typing on a keyboard.
2089 // To obtain this behavior, we must serialize key events with respect to all
2090 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002091 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002092 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002093 "finished processing all of the input events that were previously "
2094 "delivered to it. Outbound queue length: %zu. Wait queue length: "
2095 "%zu.",
2096 targetType, connection->outboundQueue.size(),
2097 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 }
Jeff Brownffb49772014-10-10 19:01:34 -07002099 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100 // Touch events can always be sent to a window immediately because the user intended
2101 // to touch whatever was visible at the time. Even if focus changes or a new
2102 // window appears moments later, the touch event was meant to be delivered to
2103 // whatever window happened to be on screen at the time.
2104 //
2105 // Generic motion events, such as trackball or joystick events are a little trickier.
2106 // Like key events, generic motion events are delivered to the focused window.
2107 // Unlike key events, generic motion events don't tend to transfer focus to other
2108 // windows and it is not important for them to be serialized. So we prefer to deliver
2109 // generic motion events as soon as possible to improve efficiency and reduce lag
2110 // through batching.
2111 //
2112 // The one case where we pause input event delivery is when the wait queue is piling
2113 // up with lots of events because the application is not responding.
2114 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002115 if (!connection->waitQueue.empty() &&
2116 currentTime >=
2117 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002118 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002119 "finished processing certain input events that were delivered to "
2120 "it over "
2121 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
2122 "%0.1fms.",
2123 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
2124 connection->waitQueue.size(),
2125 (currentTime - connection->waitQueue.front()->deliveryTime) *
2126 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127 }
2128 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002129 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130}
2131
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002132std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133 const sp<InputApplicationHandle>& applicationHandle,
2134 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002135 if (applicationHandle != nullptr) {
2136 if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002137 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 } else {
2139 return applicationHandle->getName();
2140 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002141 } else if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002142 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002144 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145 }
2146}
2147
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002148void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002149 if (eventEntry.type == EventEntry::Type::FOCUS) {
2150 // Focus events are passed to apps, but do not represent user activity.
2151 return;
2152 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002153 int32_t displayId = getTargetDisplayId(eventEntry);
2154 sp<InputWindowHandle> focusedWindowHandle =
2155 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2156 if (focusedWindowHandle != nullptr) {
2157 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2159#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002160 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161#endif
2162 return;
2163 }
2164 }
2165
2166 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002167 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002168 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002169 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2170 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002171 return;
2172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002174 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002175 eventType = USER_ACTIVITY_EVENT_TOUCH;
2176 }
2177 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002179 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002180 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2181 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002182 return;
2183 }
2184 eventType = USER_ACTIVITY_EVENT_BUTTON;
2185 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002187 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002188 case EventEntry::Type::CONFIGURATION_CHANGED:
2189 case EventEntry::Type::DEVICE_RESET: {
2190 LOG_ALWAYS_FATAL("%s events are not user activity",
2191 EventEntry::typeToString(eventEntry.type));
2192 break;
2193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194 }
2195
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002196 std::unique_ptr<CommandEntry> commandEntry =
2197 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002198 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002200 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201}
2202
2203void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002204 const sp<Connection>& connection,
2205 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002206 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002207 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002208 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002209 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002210 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002211 ATRACE_NAME(message.c_str());
2212 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213#if DEBUG_DISPATCH_CYCLE
2214 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002215 "globalScaleFactor=%f, pointerIds=0x%x %s",
2216 connection->getInputChannelName().c_str(), inputTarget.flags,
2217 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2218 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219#endif
2220
2221 // Skip this event if the connection status is not normal.
2222 // We don't want to enqueue additional outbound events if the connection is broken.
2223 if (connection->status != Connection::STATUS_NORMAL) {
2224#if DEBUG_DISPATCH_CYCLE
2225 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002226 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227#endif
2228 return;
2229 }
2230
2231 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002232 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2233 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2234 "Entry type %s should not have FLAG_SPLIT",
2235 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002237 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002238 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002239 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002240 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241 if (!splitMotionEntry) {
2242 return; // split event was dropped
2243 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002244 if (DEBUG_FOCUS) {
2245 ALOGD("channel '%s' ~ Split motion event.",
2246 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002247 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002248 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002249 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 splitMotionEntry->release();
2251 return;
2252 }
2253 }
2254
2255 // Not splitting. Enqueue dispatch entries for the event as is.
2256 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2257}
2258
2259void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002260 const sp<Connection>& connection,
2261 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002262 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002263 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002264 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002265 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002266 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002267 ATRACE_NAME(message.c_str());
2268 }
2269
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002270 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271
2272 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002273 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002274 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002275 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002276 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002277 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002278 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002279 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002280 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002281 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002282 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002283 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002284 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285
2286 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002287 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 startDispatchCycleLocked(currentTime, connection);
2289 }
2290}
2291
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002292void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2293 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002294 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002296 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2298 connection->getInputChannelName().c_str(),
2299 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002300 ATRACE_NAME(message.c_str());
2301 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002302 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 if (!(inputTargetFlags & dispatchMode)) {
2304 return;
2305 }
2306 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2307
2308 // This is a new event.
2309 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002310 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002311 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002313 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2314 // different EventEntry than what was passed in.
2315 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002317 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002318 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002319 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002320 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002321 dispatchEntry->resolvedAction = keyEntry.action;
2322 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002324 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2325 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002327 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2328 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002330 return; // skip the inconsistent event
2331 }
2332 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002335 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002336 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002337 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2338 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2339 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2340 static_cast<int32_t>(IdGenerator::Source::OTHER);
2341 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002342 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2343 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2344 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2345 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2346 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2347 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2348 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2349 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2350 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2351 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2352 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002353 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002354 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002355 }
2356 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002357 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2358 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002360 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2361 "event",
2362 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002363#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002364 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002367 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002368 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2369 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2370 }
2371 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2372 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002375 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2376 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002378 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2379 "event",
2380 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002382 return; // skip the inconsistent event
2383 }
2384
Garfield Tan1c7bc862020-01-28 13:24:04 -08002385 dispatchEntry->resolvedEventId =
2386 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2387 ? mIdGenerator.nextId()
2388 : motionEntry.id;
2389 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2390 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2391 ") to MotionEvent(id=0x%" PRIx32 ").",
2392 motionEntry.id, dispatchEntry->resolvedEventId);
2393 ATRACE_NAME(message.c_str());
2394 }
2395
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002396 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002397 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002398
2399 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002401 case EventEntry::Type::FOCUS: {
2402 break;
2403 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002404 case EventEntry::Type::CONFIGURATION_CHANGED:
2405 case EventEntry::Type::DEVICE_RESET: {
2406 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002407 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002408 break;
2409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 }
2411
2412 // Remember that we are waiting for this dispatch to complete.
2413 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002414 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415 }
2416
2417 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002418 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002419 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002420}
2421
chaviwfd6d3512019-03-25 13:23:49 -07002422void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002423 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002424 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002425 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2426 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002427 return;
2428 }
2429
2430 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2431 if (inputWindowHandle == nullptr) {
2432 return;
2433 }
2434
chaviw8c9cf542019-03-25 13:02:48 -07002435 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002436 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002437
2438 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2439
2440 if (!hasFocusChanged) {
2441 return;
2442 }
2443
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002444 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2445 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002446 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002447 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448}
2449
2450void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002451 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002452 if (ATRACE_ENABLED()) {
2453 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002454 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002455 ATRACE_NAME(message.c_str());
2456 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002458 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459#endif
2460
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002461 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2462 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 dispatchEntry->deliveryTime = currentTime;
2464
2465 // Publish the event.
2466 status_t status;
2467 EventEntry* eventEntry = dispatchEntry->eventEntry;
2468 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002469 case EventEntry::Type::KEY: {
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002470 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2471 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002473 // Publish the key event.
Garfield Tan1c7bc862020-01-28 13:24:04 -08002474 status =
2475 connection->inputPublisher
2476 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2477 keyEntry->deviceId, keyEntry->source,
2478 keyEntry->displayId, std::move(hmac),
2479 dispatchEntry->resolvedAction,
2480 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2481 keyEntry->scanCode, keyEntry->metaState,
2482 keyEntry->repeatCount, keyEntry->downTime,
2483 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002484 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485 }
2486
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002487 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002488 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002490 PointerCoords scaledCoords[MAX_POINTERS];
2491 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2492
chaviw82357092020-01-28 13:13:06 -08002493 // Set the X and Y offset and X and Y scale depending on the input source.
2494 float xOffset = 0.0f, yOffset = 0.0f;
2495 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002496 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2497 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2498 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002499 xScale = dispatchEntry->windowXScale;
2500 yScale = dispatchEntry->windowYScale;
2501 xOffset = dispatchEntry->xOffset * xScale;
2502 yOffset = dispatchEntry->yOffset * yScale;
2503 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002504 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2505 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002506 // Don't apply window scale here since we don't want scale to affect raw
2507 // coordinates. The scale will be sent back to the client and applied
2508 // later when requesting relative coordinates.
2509 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2510 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002511 }
2512 usingCoords = scaledCoords;
2513 }
2514 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002515 // We don't want the dispatch target to know.
2516 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2517 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2518 scaledCoords[i].clear();
2519 }
2520 usingCoords = scaledCoords;
2521 }
2522 }
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002523
2524 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002525
2526 // Publish the motion event.
2527 status = connection->inputPublisher
Garfield Tan1c7bc862020-01-28 13:24:04 -08002528 .publishMotionEvent(dispatchEntry->seq,
2529 dispatchEntry->resolvedEventId,
2530 motionEntry->deviceId, motionEntry->source,
2531 motionEntry->displayId, std::move(hmac),
2532 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533 motionEntry->actionButton,
2534 dispatchEntry->resolvedFlags,
2535 motionEntry->edgeFlags, motionEntry->metaState,
2536 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002537 motionEntry->classification, xScale, yScale,
2538 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002539 motionEntry->yPrecision,
2540 motionEntry->xCursorPosition,
2541 motionEntry->yCursorPosition,
2542 motionEntry->downTime, motionEntry->eventTime,
2543 motionEntry->pointerCount,
2544 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002545 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002546 break;
2547 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002548 case EventEntry::Type::FOCUS: {
2549 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2550 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tan1c7bc862020-01-28 13:24:04 -08002551 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002552 focusEntry->hasFocus,
2553 mInTouchMode);
2554 break;
2555 }
2556
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002557 case EventEntry::Type::CONFIGURATION_CHANGED:
2558 case EventEntry::Type::DEVICE_RESET: {
2559 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2560 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 }
2564
2565 // Check the result.
2566 if (status) {
2567 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002568 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002570 "This is unexpected because the wait queue is empty, so the pipe "
2571 "should be empty and we shouldn't have any problems writing an "
2572 "event to it, status=%d",
2573 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2575 } else {
2576 // Pipe is full and we are waiting for the app to finish process some events
2577 // before sending more events to it.
2578#if DEBUG_DISPATCH_CYCLE
2579 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002580 "waiting for the application to catch up",
2581 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582#endif
2583 connection->inputPublisherBlocked = true;
2584 }
2585 } else {
2586 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002587 "status=%d",
2588 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2590 }
2591 return;
2592 }
2593
2594 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002595 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2596 connection->outboundQueue.end(),
2597 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002598 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002599 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002600 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 }
2602}
2603
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002604const std::array<uint8_t, 32> InputDispatcher::getSignature(
2605 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2606 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2607 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2608 // Only sign events up and down events as the purely move events
2609 // are tied to their up/down counterparts so signing would be redundant.
2610 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2611 verifiedEvent.actionMasked = actionMasked;
2612 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2613 return mHmacKeyManager.sign(verifiedEvent);
2614 }
2615 return INVALID_HMAC;
2616}
2617
2618const std::array<uint8_t, 32> InputDispatcher::getSignature(
2619 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2620 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2621 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2622 verifiedEvent.action = dispatchEntry.resolvedAction;
2623 return mHmacKeyManager.sign(verifiedEvent);
2624}
2625
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002627 const sp<Connection>& connection, uint32_t seq,
2628 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629#if DEBUG_DISPATCH_CYCLE
2630 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002631 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632#endif
2633
2634 connection->inputPublisherBlocked = false;
2635
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002636 if (connection->status == Connection::STATUS_BROKEN ||
2637 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638 return;
2639 }
2640
2641 // Notify other system components and prepare to start the next dispatch cycle.
2642 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2643}
2644
2645void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002646 const sp<Connection>& connection,
2647 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648#if DEBUG_DISPATCH_CYCLE
2649 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002650 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651#endif
2652
2653 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002654 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002655 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002656 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002657 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658
2659 // The connection appears to be unrecoverably broken.
2660 // Ignore already broken or zombie connections.
2661 if (connection->status == Connection::STATUS_NORMAL) {
2662 connection->status = Connection::STATUS_BROKEN;
2663
2664 if (notify) {
2665 // Notify other system components.
2666 onDispatchCycleBrokenLocked(currentTime, connection);
2667 }
2668 }
2669}
2670
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002671void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2672 while (!queue.empty()) {
2673 DispatchEntry* dispatchEntry = queue.front();
2674 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002675 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676 }
2677}
2678
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002679void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002681 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 }
2683 delete dispatchEntry;
2684}
2685
2686int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2687 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2688
2689 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002690 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002692 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002694 "fd=%d, events=0x%x",
2695 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696 return 0; // remove the callback
2697 }
2698
2699 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002700 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2702 if (!(events & ALOOPER_EVENT_INPUT)) {
2703 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002704 "events=0x%x",
2705 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 return 1;
2707 }
2708
2709 nsecs_t currentTime = now();
2710 bool gotOne = false;
2711 status_t status;
2712 for (;;) {
2713 uint32_t seq;
2714 bool handled;
2715 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2716 if (status) {
2717 break;
2718 }
2719 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2720 gotOne = true;
2721 }
2722 if (gotOne) {
2723 d->runCommandsLockedInterruptible();
2724 if (status == WOULD_BLOCK) {
2725 return 1;
2726 }
2727 }
2728
2729 notify = status != DEAD_OBJECT || !connection->monitor;
2730 if (notify) {
2731 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002732 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733 }
2734 } else {
2735 // Monitor channels are never explicitly unregistered.
2736 // We do it automatically when the remote endpoint is closed so don't warn
2737 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002738 const bool stillHaveWindowHandle =
2739 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2740 nullptr;
2741 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 if (notify) {
2743 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002744 "events=0x%x",
2745 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746 }
2747 }
2748
2749 // Unregister the channel.
2750 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2751 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002752 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753}
2754
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002755void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002757 for (const auto& pair : mConnectionsByFd) {
2758 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759 }
2760}
2761
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002762void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002763 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002764 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2765 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2766}
2767
2768void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2769 const CancelationOptions& options,
2770 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2771 for (const auto& it : monitorsByDisplay) {
2772 const std::vector<Monitor>& monitors = it.second;
2773 for (const Monitor& monitor : monitors) {
2774 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002775 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002776 }
2777}
2778
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2780 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002781 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002782 if (connection == nullptr) {
2783 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002785
2786 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787}
2788
2789void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2790 const sp<Connection>& connection, const CancelationOptions& options) {
2791 if (connection->status == Connection::STATUS_BROKEN) {
2792 return;
2793 }
2794
2795 nsecs_t currentTime = now();
2796
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002797 std::vector<EventEntry*> cancelationEvents =
2798 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002799
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002800 if (cancelationEvents.empty()) {
2801 return;
2802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002804 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2805 "with reality: %s, mode=%d.",
2806 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2807 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002809
2810 InputTarget target;
2811 sp<InputWindowHandle> windowHandle =
2812 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2813 if (windowHandle != nullptr) {
2814 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2815 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2816 windowInfo->windowXScale, windowInfo->windowYScale);
2817 target.globalScaleFactor = windowInfo->globalScaleFactor;
2818 }
2819 target.inputChannel = connection->inputChannel;
2820 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2821
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002822 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2823 EventEntry* cancelationEventEntry = cancelationEvents[i];
2824 switch (cancelationEventEntry->type) {
2825 case EventEntry::Type::KEY: {
2826 logOutboundKeyDetails("cancel - ",
2827 static_cast<const KeyEntry&>(*cancelationEventEntry));
2828 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002830 case EventEntry::Type::MOTION: {
2831 logOutboundMotionDetails("cancel - ",
2832 static_cast<const MotionEntry&>(*cancelationEventEntry));
2833 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002835 case EventEntry::Type::FOCUS: {
2836 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2837 break;
2838 }
2839 case EventEntry::Type::CONFIGURATION_CHANGED:
2840 case EventEntry::Type::DEVICE_RESET: {
2841 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2842 EventEntry::typeToString(cancelationEventEntry->type));
2843 break;
2844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 }
2846
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002847 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2848 target, InputTarget::FLAG_DISPATCH_AS_IS);
2849
2850 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002852
2853 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854}
2855
Svet Ganov5d3bc372020-01-26 23:11:07 -08002856void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2857 const sp<Connection>& connection) {
2858 if (connection->status == Connection::STATUS_BROKEN) {
2859 return;
2860 }
2861
2862 nsecs_t currentTime = now();
2863
2864 std::vector<EventEntry*> downEvents =
2865 connection->inputState.synthesizePointerDownEvents(currentTime);
2866
2867 if (downEvents.empty()) {
2868 return;
2869 }
2870
2871#if DEBUG_OUTBOUND_EVENT_DETAILS
2872 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2873 connection->getInputChannelName().c_str(), downEvents.size());
2874#endif
2875
2876 InputTarget target;
2877 sp<InputWindowHandle> windowHandle =
2878 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2879 if (windowHandle != nullptr) {
2880 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2881 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2882 windowInfo->windowXScale, windowInfo->windowYScale);
2883 target.globalScaleFactor = windowInfo->globalScaleFactor;
2884 }
2885 target.inputChannel = connection->inputChannel;
2886 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2887
2888 for (EventEntry* downEventEntry : downEvents) {
2889 switch (downEventEntry->type) {
2890 case EventEntry::Type::MOTION: {
2891 logOutboundMotionDetails("down - ",
2892 static_cast<const MotionEntry&>(*downEventEntry));
2893 break;
2894 }
2895
2896 case EventEntry::Type::KEY:
2897 case EventEntry::Type::FOCUS:
2898 case EventEntry::Type::CONFIGURATION_CHANGED:
2899 case EventEntry::Type::DEVICE_RESET: {
2900 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2901 EventEntry::typeToString(downEventEntry->type));
2902 break;
2903 }
2904 }
2905
2906 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2907 target, InputTarget::FLAG_DISPATCH_AS_IS);
2908
2909 downEventEntry->release();
2910 }
2911
2912 startDispatchCycleLocked(currentTime, connection);
2913}
2914
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002915MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002916 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917 ALOG_ASSERT(pointerIds.value != 0);
2918
2919 uint32_t splitPointerIndexMap[MAX_POINTERS];
2920 PointerProperties splitPointerProperties[MAX_POINTERS];
2921 PointerCoords splitPointerCoords[MAX_POINTERS];
2922
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002923 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924 uint32_t splitPointerCount = 0;
2925
2926 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002927 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002929 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 uint32_t pointerId = uint32_t(pointerProperties.id);
2931 if (pointerIds.hasBit(pointerId)) {
2932 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2933 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2934 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002935 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936 splitPointerCount += 1;
2937 }
2938 }
2939
2940 if (splitPointerCount != pointerIds.count()) {
2941 // This is bad. We are missing some of the pointers that we expected to deliver.
2942 // Most likely this indicates that we received an ACTION_MOVE events that has
2943 // different pointer ids than we expected based on the previous ACTION_DOWN
2944 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2945 // in this way.
2946 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002947 "we expected there to be %d pointers. This probably means we received "
2948 "a broken sequence of pointer ids from the input device.",
2949 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002950 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951 }
2952
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002953 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002955 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2956 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2958 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002959 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960 uint32_t pointerId = uint32_t(pointerProperties.id);
2961 if (pointerIds.hasBit(pointerId)) {
2962 if (pointerIds.count() == 1) {
2963 // The first/last pointer went down/up.
2964 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002965 ? AMOTION_EVENT_ACTION_DOWN
2966 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 } else {
2968 // A secondary pointer went down/up.
2969 uint32_t splitPointerIndex = 0;
2970 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2971 splitPointerIndex += 1;
2972 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002973 action = maskedAction |
2974 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002975 }
2976 } else {
2977 // An unrelated pointer changed.
2978 action = AMOTION_EVENT_ACTION_MOVE;
2979 }
2980 }
2981
Garfield Tan1c7bc862020-01-28 13:24:04 -08002982 int32_t newId = mIdGenerator.nextId();
2983 if (ATRACE_ENABLED()) {
2984 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
2985 ") to MotionEvent(id=0x%" PRIx32 ").",
2986 originalMotionEntry.id, newId);
2987 ATRACE_NAME(message.c_str());
2988 }
Garfield Tan00f511d2019-06-12 16:55:40 -07002989 MotionEntry* splitMotionEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002990 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
2991 originalMotionEntry.source, originalMotionEntry.displayId,
2992 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002993 originalMotionEntry.actionButton, originalMotionEntry.flags,
2994 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2995 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2996 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2997 originalMotionEntry.xCursorPosition,
2998 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002999 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003001 if (originalMotionEntry.injectionState) {
3002 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003 splitMotionEntry->injectionState->refCount += 1;
3004 }
3005
3006 return splitMotionEntry;
3007}
3008
3009void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3010#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003011 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012#endif
3013
3014 bool needWake;
3015 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003016 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017
Prabir Pradhan42611e02018-11-27 14:04:02 -08003018 ConfigurationChangedEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003019 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003020 needWake = enqueueInboundEventLocked(newEntry);
3021 } // release lock
3022
3023 if (needWake) {
3024 mLooper->wake();
3025 }
3026}
3027
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003028/**
3029 * If one of the meta shortcuts is detected, process them here:
3030 * Meta + Backspace -> generate BACK
3031 * Meta + Enter -> generate HOME
3032 * This will potentially overwrite keyCode and metaState.
3033 */
3034void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003035 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003036 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3037 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3038 if (keyCode == AKEYCODE_DEL) {
3039 newKeyCode = AKEYCODE_BACK;
3040 } else if (keyCode == AKEYCODE_ENTER) {
3041 newKeyCode = AKEYCODE_HOME;
3042 }
3043 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003044 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003045 struct KeyReplacement replacement = {keyCode, deviceId};
3046 mReplacedKeys.add(replacement, newKeyCode);
3047 keyCode = newKeyCode;
3048 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3049 }
3050 } else if (action == AKEY_EVENT_ACTION_UP) {
3051 // In order to maintain a consistent stream of up and down events, check to see if the key
3052 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3053 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003054 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003055 struct KeyReplacement replacement = {keyCode, deviceId};
3056 ssize_t index = mReplacedKeys.indexOfKey(replacement);
3057 if (index >= 0) {
3058 keyCode = mReplacedKeys.valueAt(index);
3059 mReplacedKeys.removeItemsAt(index);
3060 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3061 }
3062 }
3063}
3064
Michael Wrightd02c5b62014-02-10 15:10:22 -08003065void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3066#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003067 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3068 "policyFlags=0x%x, action=0x%x, "
3069 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3070 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3071 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3072 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073#endif
3074 if (!validateKeyEvent(args->action)) {
3075 return;
3076 }
3077
3078 uint32_t policyFlags = args->policyFlags;
3079 int32_t flags = args->flags;
3080 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003081 // InputDispatcher tracks and generates key repeats on behalf of
3082 // whatever notifies it, so repeatCount should always be set to 0
3083 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3085 policyFlags |= POLICY_FLAG_VIRTUAL;
3086 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 if (policyFlags & POLICY_FLAG_FUNCTION) {
3089 metaState |= AMETA_FUNCTION_ON;
3090 }
3091
3092 policyFlags |= POLICY_FLAG_TRUSTED;
3093
Michael Wright78f24442014-08-06 15:55:28 -07003094 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003095 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003096
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003098 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08003099 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3100 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101
Michael Wright2b3c3302018-03-02 17:19:13 +00003102 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003104 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3105 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109 bool needWake;
3110 { // acquire lock
3111 mLock.lock();
3112
3113 if (shouldSendKeyToInputFilterLocked(args)) {
3114 mLock.unlock();
3115
3116 policyFlags |= POLICY_FLAG_FILTERED;
3117 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3118 return; // event was consumed by the filter
3119 }
3120
3121 mLock.lock();
3122 }
3123
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003124 KeyEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003125 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 args->displayId, policyFlags, args->action, flags, keyCode,
3127 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128
3129 needWake = enqueueInboundEventLocked(newEntry);
3130 mLock.unlock();
3131 } // release lock
3132
3133 if (needWake) {
3134 mLooper->wake();
3135 }
3136}
3137
3138bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3139 return mInputFilterEnabled;
3140}
3141
3142void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3143#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003144 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3145 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003146 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3147 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003148 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003149 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3150 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3151 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3152 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 for (uint32_t i = 0; i < args->pointerCount; i++) {
3154 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003155 "x=%f, y=%f, pressure=%f, size=%f, "
3156 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3157 "orientation=%f",
3158 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3159 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3160 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3161 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3162 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3163 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3164 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3165 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3166 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3167 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168 }
3169#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003170 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3171 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172 return;
3173 }
3174
3175 uint32_t policyFlags = args->policyFlags;
3176 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003177
3178 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003179 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003180 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3181 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003182 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184
3185 bool needWake;
3186 { // acquire lock
3187 mLock.lock();
3188
3189 if (shouldSendMotionToInputFilterLocked(args)) {
3190 mLock.unlock();
3191
3192 MotionEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003193 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3194 args->action, args->actionButton, args->flags, args->edgeFlags,
3195 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3196 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3197 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3198 args->downTime, args->eventTime, args->pointerCount,
3199 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200
3201 policyFlags |= POLICY_FLAG_FILTERED;
3202 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3203 return; // event was consumed by the filter
3204 }
3205
3206 mLock.lock();
3207 }
3208
3209 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003210 MotionEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003211 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003212 args->displayId, policyFlags, args->action, args->actionButton,
3213 args->flags, args->metaState, args->buttonState,
3214 args->classification, args->edgeFlags, args->xPrecision,
3215 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3216 args->downTime, args->pointerCount, args->pointerProperties,
3217 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218
3219 needWake = enqueueInboundEventLocked(newEntry);
3220 mLock.unlock();
3221 } // release lock
3222
3223 if (needWake) {
3224 mLooper->wake();
3225 }
3226}
3227
3228bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003229 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230}
3231
3232void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3233#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003234 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003235 "switchMask=0x%08x",
3236 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237#endif
3238
3239 uint32_t policyFlags = args->policyFlags;
3240 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003241 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242}
3243
3244void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3245#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003246 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3247 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248#endif
3249
3250 bool needWake;
3251 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003252 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253
Prabir Pradhan42611e02018-11-27 14:04:02 -08003254 DeviceResetEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003255 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256 needWake = enqueueInboundEventLocked(newEntry);
3257 } // release lock
3258
3259 if (needWake) {
3260 mLooper->wake();
3261 }
3262}
3263
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003264int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3265 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003266 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267#if DEBUG_INBOUND_EVENT_DETAILS
3268 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003269 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3270 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271#endif
3272
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003273 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274
3275 policyFlags |= POLICY_FLAG_INJECTED;
3276 if (hasInjectionPermission(injectorPid, injectorUid)) {
3277 policyFlags |= POLICY_FLAG_TRUSTED;
3278 }
3279
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003280 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003282 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003283 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3284 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003285 if (!validateKeyEvent(action)) {
3286 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003289 int32_t flags = incomingKey.getFlags();
3290 int32_t keyCode = incomingKey.getKeyCode();
3291 int32_t metaState = incomingKey.getMetaState();
3292 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003293 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003294 KeyEvent keyEvent;
Garfield Tanfbe732e2020-01-24 11:26:14 -08003295 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003296 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3297 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3298 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003300 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3301 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003302 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003303
3304 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3305 android::base::Timer t;
3306 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3307 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3308 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3309 std::to_string(t.duration().count()).c_str());
3310 }
3311 }
3312
3313 mLock.lock();
3314 KeyEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003315 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3316 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003317 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3318 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tanfbe732e2020-01-24 11:26:14 -08003319 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003320 injectedEntries.push(injectedEntry);
3321 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322 }
3323
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003324 case AINPUT_EVENT_TYPE_MOTION: {
3325 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3326 int32_t action = motionEvent->getAction();
3327 size_t pointerCount = motionEvent->getPointerCount();
3328 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3329 int32_t actionButton = motionEvent->getActionButton();
3330 int32_t displayId = motionEvent->getDisplayId();
3331 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3332 return INPUT_EVENT_INJECTION_FAILED;
3333 }
3334
3335 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3336 nsecs_t eventTime = motionEvent->getEventTime();
3337 android::base::Timer t;
3338 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3339 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3340 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3341 std::to_string(t.duration().count()).c_str());
3342 }
3343 }
3344
3345 mLock.lock();
3346 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3347 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3348 MotionEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003349 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3350 motionEvent->getSource(), motionEvent->getDisplayId(),
3351 policyFlags, action, actionButton, motionEvent->getFlags(),
3352 motionEvent->getMetaState(), motionEvent->getButtonState(),
3353 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3354 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003355 motionEvent->getRawXCursorPosition(),
3356 motionEvent->getRawYCursorPosition(),
3357 motionEvent->getDownTime(), uint32_t(pointerCount),
3358 pointerProperties, samplePointerCoords,
3359 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003360 injectedEntries.push(injectedEntry);
3361 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3362 sampleEventTimes += 1;
3363 samplePointerCoords += pointerCount;
3364 MotionEntry* nextInjectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003365 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003366 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 motionEvent->getDisplayId(), policyFlags, action,
3368 actionButton, motionEvent->getFlags(),
3369 motionEvent->getMetaState(), motionEvent->getButtonState(),
3370 motionEvent->getClassification(),
3371 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3372 motionEvent->getYPrecision(),
3373 motionEvent->getRawXCursorPosition(),
3374 motionEvent->getRawYCursorPosition(),
3375 motionEvent->getDownTime(), uint32_t(pointerCount),
3376 pointerProperties, samplePointerCoords,
3377 motionEvent->getXOffset(), motionEvent->getYOffset());
3378 injectedEntries.push(nextInjectedEntry);
3379 }
3380 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003383 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003384 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 }
3387
3388 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3389 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3390 injectionState->injectionIsAsync = true;
3391 }
3392
3393 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003394 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395
3396 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003397 while (!injectedEntries.empty()) {
3398 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3399 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 }
3401
3402 mLock.unlock();
3403
3404 if (needWake) {
3405 mLooper->wake();
3406 }
3407
3408 int32_t injectionResult;
3409 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003410 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411
3412 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3413 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3414 } else {
3415 for (;;) {
3416 injectionResult = injectionState->injectionResult;
3417 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3418 break;
3419 }
3420
3421 nsecs_t remainingTimeout = endTime - now();
3422 if (remainingTimeout <= 0) {
3423#if DEBUG_INJECTION
3424 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003425 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426#endif
3427 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3428 break;
3429 }
3430
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003431 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 }
3433
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003434 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3435 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 while (injectionState->pendingForegroundDispatches != 0) {
3437#if DEBUG_INJECTION
3438 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003439 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440#endif
3441 nsecs_t remainingTimeout = endTime - now();
3442 if (remainingTimeout <= 0) {
3443#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003444 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3445 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446#endif
3447 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3448 break;
3449 }
3450
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003451 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452 }
3453 }
3454 }
3455
3456 injectionState->release();
3457 } // release lock
3458
3459#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003460 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003461 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462#endif
3463
3464 return injectionResult;
3465}
3466
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003467std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003468 std::array<uint8_t, 32> calculatedHmac;
3469 std::unique_ptr<VerifiedInputEvent> result;
3470 switch (event.getType()) {
3471 case AINPUT_EVENT_TYPE_KEY: {
3472 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3473 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3474 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3475 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3476 break;
3477 }
3478 case AINPUT_EVENT_TYPE_MOTION: {
3479 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3480 VerifiedMotionEvent verifiedMotionEvent =
3481 verifiedMotionEventFromMotionEvent(motionEvent);
3482 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3483 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3484 break;
3485 }
3486 default: {
3487 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3488 return nullptr;
3489 }
3490 }
3491 if (calculatedHmac == INVALID_HMAC) {
3492 return nullptr;
3493 }
3494 if (calculatedHmac != event.getHmac()) {
3495 return nullptr;
3496 }
3497 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003498}
3499
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003501 return injectorUid == 0 ||
3502 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503}
3504
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003505void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506 InjectionState* injectionState = entry->injectionState;
3507 if (injectionState) {
3508#if DEBUG_INJECTION
3509 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003510 "injectorPid=%d, injectorUid=%d",
3511 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512#endif
3513
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003514 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515 // Log the outcome since the injector did not wait for the injection result.
3516 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003517 case INPUT_EVENT_INJECTION_SUCCEEDED:
3518 ALOGV("Asynchronous input event injection succeeded.");
3519 break;
3520 case INPUT_EVENT_INJECTION_FAILED:
3521 ALOGW("Asynchronous input event injection failed.");
3522 break;
3523 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3524 ALOGW("Asynchronous input event injection permission denied.");
3525 break;
3526 case INPUT_EVENT_INJECTION_TIMED_OUT:
3527 ALOGW("Asynchronous input event injection timed out.");
3528 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 }
3530 }
3531
3532 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003533 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 }
3535}
3536
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003537void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538 InjectionState* injectionState = entry->injectionState;
3539 if (injectionState) {
3540 injectionState->pendingForegroundDispatches += 1;
3541 }
3542}
3543
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003544void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 InjectionState* injectionState = entry->injectionState;
3546 if (injectionState) {
3547 injectionState->pendingForegroundDispatches -= 1;
3548
3549 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003550 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 }
3552 }
3553}
3554
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003555std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3556 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003557 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003558}
3559
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003561 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003562 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003563 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3564 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003565 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003566 return windowHandle;
3567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003568 }
3569 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003570 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571}
3572
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003573bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003574 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003575 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3576 for (const sp<InputWindowHandle>& handle : windowHandles) {
3577 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003578 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003579 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003580 ", but it should belong to display %" PRId32,
3581 windowHandle->getName().c_str(), it.first,
3582 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003583 }
3584 return true;
3585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 }
3587 }
3588 return false;
3589}
3590
Robert Carr5c8a0262018-10-03 16:30:44 -07003591sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3592 size_t count = mInputChannelsByToken.count(token);
3593 if (count == 0) {
3594 return nullptr;
3595 }
3596 return mInputChannelsByToken.at(token);
3597}
3598
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003599void InputDispatcher::updateWindowHandlesForDisplayLocked(
3600 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3601 if (inputWindowHandles.empty()) {
3602 // Remove all handles on a display if there are no windows left.
3603 mWindowHandlesByDisplay.erase(displayId);
3604 return;
3605 }
3606
3607 // Since we compare the pointer of input window handles across window updates, we need
3608 // to make sure the handle object for the same window stays unchanged across updates.
3609 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003610 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003611 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003612 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003613 }
3614
3615 std::vector<sp<InputWindowHandle>> newHandles;
3616 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3617 if (!handle->updateInfo()) {
3618 // handle no longer valid
3619 continue;
3620 }
3621
3622 const InputWindowInfo* info = handle->getInfo();
3623 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3624 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3625 const bool noInputChannel =
3626 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3627 const bool canReceiveInput =
3628 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3629 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3630 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003631 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003632 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003633 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003634 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003635 }
3636
3637 if (info->displayId != displayId) {
3638 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3639 handle->getName().c_str(), displayId, info->displayId);
3640 continue;
3641 }
3642
chaviwaf87b3e2019-10-01 16:59:28 -07003643 if (oldHandlesById.find(handle->getId()) != oldHandlesById.end()) {
3644 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003645 oldHandle->updateFrom(handle);
3646 newHandles.push_back(oldHandle);
3647 } else {
3648 newHandles.push_back(handle);
3649 }
3650 }
3651
3652 // Insert or replace
3653 mWindowHandlesByDisplay[displayId] = newHandles;
3654}
3655
Arthur Hung72d8dc32020-03-28 00:48:39 +00003656void InputDispatcher::setInputWindows(
3657 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3658 { // acquire lock
3659 std::scoped_lock _l(mLock);
3660 for (auto const& i : handlesPerDisplay) {
3661 setInputWindowsLocked(i.second, i.first);
3662 }
3663 }
3664 // Wake up poll loop since it may need to make new input dispatching choices.
3665 mLooper->wake();
3666}
3667
Arthur Hungb92218b2018-08-14 12:00:21 +08003668/**
3669 * Called from InputManagerService, update window handle list by displayId that can receive input.
3670 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3671 * If set an empty list, remove all handles from the specific display.
3672 * For focused handle, check if need to change and send a cancel event to previous one.
3673 * For removed handle, check if need to send a cancel event if already in touch.
3674 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003675void InputDispatcher::setInputWindowsLocked(
3676 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003677 if (DEBUG_FOCUS) {
3678 std::string windowList;
3679 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3680 windowList += iwh->getName() + " ";
3681 }
3682 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3683 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684
Arthur Hung72d8dc32020-03-28 00:48:39 +00003685 // Copy old handles for release if they are no longer present.
3686 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687
Arthur Hung72d8dc32020-03-28 00:48:39 +00003688 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003689
Arthur Hung72d8dc32020-03-28 00:48:39 +00003690 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3691 bool foundHoveredWindow = false;
3692 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3693 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3694 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3695 windowHandle->getInfo()->visible) {
3696 newFocusedWindowHandle = windowHandle;
3697 }
3698 if (windowHandle == mLastHoverWindowHandle) {
3699 foundHoveredWindow = true;
3700 }
3701 }
3702
3703 if (!foundHoveredWindow) {
3704 mLastHoverWindowHandle = nullptr;
3705 }
3706
3707 sp<InputWindowHandle> oldFocusedWindowHandle =
3708 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3709
3710 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3711 if (oldFocusedWindowHandle != nullptr) {
3712 if (DEBUG_FOCUS) {
3713 ALOGD("Focus left window: %s in display %" PRId32,
3714 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003715 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003716 sp<InputChannel> focusedInputChannel =
3717 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3718 if (focusedInputChannel != nullptr) {
3719 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3720 "focus left window");
3721 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3722 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003723 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003724 mFocusedWindowHandlesByDisplay.erase(displayId);
3725 }
3726 if (newFocusedWindowHandle != nullptr) {
3727 if (DEBUG_FOCUS) {
3728 ALOGD("Focus entered window: %s in display %" PRId32,
3729 newFocusedWindowHandle->getName().c_str(), displayId);
3730 }
3731 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3732 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 }
3734
Arthur Hung72d8dc32020-03-28 00:48:39 +00003735 if (mFocusedDisplayId == displayId) {
3736 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739
Arthur Hung72d8dc32020-03-28 00:48:39 +00003740 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3741 if (stateIndex >= 0) {
3742 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
3743 for (size_t i = 0; i < state.windows.size();) {
3744 TouchedWindow& touchedWindow = state.windows[i];
3745 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003746 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003747 ALOGD("Touched window was removed: %s in display %" PRId32,
3748 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003749 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003750 sp<InputChannel> touchedInputChannel =
3751 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3752 if (touchedInputChannel != nullptr) {
3753 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3754 "touched window was removed");
3755 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003757 state.windows.erase(state.windows.begin() + i);
3758 } else {
3759 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 }
3761 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003762 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003763
Arthur Hung72d8dc32020-03-28 00:48:39 +00003764 // Release information for windows that are no longer present.
3765 // This ensures that unused input channels are released promptly.
3766 // Otherwise, they might stick around until the window handle is destroyed
3767 // which might not happen until the next GC.
3768 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3769 if (!hasWindowHandleLocked(oldWindowHandle)) {
3770 if (DEBUG_FOCUS) {
3771 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003772 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003773 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003774 }
chaviw291d88a2019-02-14 10:33:58 -08003775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776}
3777
3778void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003779 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003780 if (DEBUG_FOCUS) {
3781 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3782 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003785 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786
Tiger Huang721e26f2018-07-24 22:26:19 +08003787 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3788 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003789 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003790 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3791 if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003792 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003794 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003796 } else if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003797 resetAnrTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003798 oldFocusedApplicationHandle.clear();
3799 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 } // release lock
3802
3803 // Wake up poll loop since it may need to make new input dispatching choices.
3804 mLooper->wake();
3805}
3806
Tiger Huang721e26f2018-07-24 22:26:19 +08003807/**
3808 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3809 * the display not specified.
3810 *
3811 * We track any unreleased events for each window. If a window loses the ability to receive the
3812 * released event, we will send a cancel event to it. So when the focused display is changed, we
3813 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3814 * display. The display-specified events won't be affected.
3815 */
3816void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003817 if (DEBUG_FOCUS) {
3818 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3819 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003820 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003821 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003822
3823 if (mFocusedDisplayId != displayId) {
3824 sp<InputWindowHandle> oldFocusedWindowHandle =
3825 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3826 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003827 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003828 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003829 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003830 CancelationOptions
3831 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3832 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003833 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003834 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3835 }
3836 }
3837 mFocusedDisplayId = displayId;
3838
3839 // Sanity check
3840 sp<InputWindowHandle> newFocusedWindowHandle =
3841 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003842 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003843
Tiger Huang721e26f2018-07-24 22:26:19 +08003844 if (newFocusedWindowHandle == nullptr) {
3845 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3846 if (!mFocusedWindowHandlesByDisplay.empty()) {
3847 ALOGE("But another display has a focused window:");
3848 for (auto& it : mFocusedWindowHandlesByDisplay) {
3849 const int32_t displayId = it.first;
3850 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003851 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3852 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003853 }
3854 }
3855 }
3856 }
3857
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003858 if (DEBUG_FOCUS) {
3859 logDispatchStateLocked();
3860 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003861 } // release lock
3862
3863 // Wake up poll loop since it may need to make new input dispatching choices.
3864 mLooper->wake();
3865}
3866
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003868 if (DEBUG_FOCUS) {
3869 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871
3872 bool changed;
3873 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003874 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875
3876 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3877 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003878 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 }
3880
3881 if (mDispatchEnabled && !enabled) {
3882 resetAndDropEverythingLocked("dispatcher is being disabled");
3883 }
3884
3885 mDispatchEnabled = enabled;
3886 mDispatchFrozen = frozen;
3887 changed = true;
3888 } else {
3889 changed = false;
3890 }
3891
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003892 if (DEBUG_FOCUS) {
3893 logDispatchStateLocked();
3894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895 } // release lock
3896
3897 if (changed) {
3898 // Wake up poll loop since it may need to make new input dispatching choices.
3899 mLooper->wake();
3900 }
3901}
3902
3903void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003904 if (DEBUG_FOCUS) {
3905 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907
3908 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003909 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910
3911 if (mInputFilterEnabled == enabled) {
3912 return;
3913 }
3914
3915 mInputFilterEnabled = enabled;
3916 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3917 } // release lock
3918
3919 // Wake up poll loop since there might be work to do to drop everything.
3920 mLooper->wake();
3921}
3922
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003923void InputDispatcher::setInTouchMode(bool inTouchMode) {
3924 std::scoped_lock lock(mLock);
3925 mInTouchMode = inTouchMode;
3926}
3927
chaviwfbe5d9c2018-12-26 12:23:37 -08003928bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3929 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003930 if (DEBUG_FOCUS) {
3931 ALOGD("Trivial transfer to same window.");
3932 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003933 return true;
3934 }
3935
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003937 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938
chaviwfbe5d9c2018-12-26 12:23:37 -08003939 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3940 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003941 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003942 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 return false;
3944 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003945 if (DEBUG_FOCUS) {
3946 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3947 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003950 if (DEBUG_FOCUS) {
3951 ALOGD("Cannot transfer focus because windows are on different displays.");
3952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 return false;
3954 }
3955
3956 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003957 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3958 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3959 for (size_t i = 0; i < state.windows.size(); i++) {
3960 const TouchedWindow& touchedWindow = state.windows[i];
3961 if (touchedWindow.windowHandle == fromWindowHandle) {
3962 int32_t oldTargetFlags = touchedWindow.targetFlags;
3963 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003965 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003967 int32_t newTargetFlags = oldTargetFlags &
3968 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3969 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003970 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971
Jeff Brownf086ddb2014-02-11 14:28:48 -08003972 found = true;
3973 goto Found;
3974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 }
3976 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003977 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003979 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003980 if (DEBUG_FOCUS) {
3981 ALOGD("Focus transfer failed because from window did not have focus.");
3982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 return false;
3984 }
3985
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003986 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3987 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003988 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003989 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003990 CancelationOptions
3991 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3992 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003994 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 }
3996
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003997 if (DEBUG_FOCUS) {
3998 logDispatchStateLocked();
3999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000 } // release lock
4001
4002 // Wake up poll loop since it may need to make new input dispatching choices.
4003 mLooper->wake();
4004 return true;
4005}
4006
4007void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004008 if (DEBUG_FOCUS) {
4009 ALOGD("Resetting and dropping all events (%s).", reason);
4010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011
4012 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4013 synthesizeCancelationEventsForAllConnectionsLocked(options);
4014
4015 resetKeyRepeatLocked();
4016 releasePendingEventLocked();
4017 drainInboundQueueLocked();
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004018 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019
Jeff Brownf086ddb2014-02-11 14:28:48 -08004020 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004022 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023}
4024
4025void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004026 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027 dumpDispatchStateLocked(dump);
4028
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004029 std::istringstream stream(dump);
4030 std::string line;
4031
4032 while (std::getline(stream, line, '\n')) {
4033 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034 }
4035}
4036
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004037void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004038 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4039 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4040 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004041 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042
Tiger Huang721e26f2018-07-24 22:26:19 +08004043 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4044 dump += StringPrintf(INDENT "FocusedApplications:\n");
4045 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4046 const int32_t displayId = it.first;
4047 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004048 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004049 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004050 displayId, applicationHandle->getName().c_str(),
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004051 ns2ms(applicationHandle
4052 ->getDispatchingTimeout(
4053 DEFAULT_INPUT_DISPATCHING_TIMEOUT)
4054 .count()));
Tiger Huang721e26f2018-07-24 22:26:19 +08004055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004057 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004059
4060 if (!mFocusedWindowHandlesByDisplay.empty()) {
4061 dump += StringPrintf(INDENT "FocusedWindows:\n");
4062 for (auto& it : mFocusedWindowHandlesByDisplay) {
4063 const int32_t displayId = it.first;
4064 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004065 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4066 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004067 }
4068 } else {
4069 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071
Jeff Brownf086ddb2014-02-11 14:28:48 -08004072 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004073 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08004074 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
4075 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004076 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004077 state.displayId, toString(state.down), toString(state.split),
4078 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004079 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004080 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004081 for (size_t i = 0; i < state.windows.size(); i++) {
4082 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004083 dump += StringPrintf(INDENT4
4084 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4085 i, touchedWindow.windowHandle->getName().c_str(),
4086 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004087 }
4088 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004089 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004090 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004091 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004092 dump += INDENT3 "Portal windows:\n";
4093 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004094 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004095 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4096 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004097 }
4098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099 }
4100 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004101 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102 }
4103
Arthur Hungb92218b2018-08-14 12:00:21 +08004104 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004105 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004106 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004107 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004108 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004109 dump += INDENT2 "Windows:\n";
4110 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004111 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004112 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113
Arthur Hungb92218b2018-08-14 12:00:21 +08004114 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004115 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004116 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4117 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004118 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004119 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004120 i, windowInfo->name.c_str(), windowInfo->displayId,
4121 windowInfo->portalToDisplayId,
4122 toString(windowInfo->paused),
4123 toString(windowInfo->hasFocus),
4124 toString(windowInfo->hasWallpaper),
4125 toString(windowInfo->visible),
4126 toString(windowInfo->canReceiveKeys),
4127 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004128 windowInfo->layoutParamsType, windowInfo->frameLeft,
4129 windowInfo->frameTop, windowInfo->frameRight,
4130 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4131 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004132 dumpRegion(dump, windowInfo->touchableRegion);
4133 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004134 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4135 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004136 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004137 ns2ms(windowInfo->dispatchingTimeout));
Arthur Hungb92218b2018-08-14 12:00:21 +08004138 }
4139 } else {
4140 dump += INDENT2 "Windows: <none>\n";
4141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 }
4143 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004144 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145 }
4146
Michael Wright3dd60e22019-03-27 22:06:44 +00004147 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004148 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004149 const std::vector<Monitor>& monitors = it.second;
4150 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4151 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004152 }
4153 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004154 const std::vector<Monitor>& monitors = it.second;
4155 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4156 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004159 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 }
4161
4162 nsecs_t currentTime = now();
4163
4164 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004165 if (!mRecentQueue.empty()) {
4166 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4167 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004168 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004170 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 }
4172 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004173 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 }
4175
4176 // Dump event currently being dispatched.
4177 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004178 dump += INDENT "PendingEvent:\n";
4179 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004181 dump += StringPrintf(", age=%" PRId64 "ms\n",
4182 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004184 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 }
4186
4187 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004188 if (!mInboundQueue.empty()) {
4189 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4190 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004191 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004193 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 }
4195 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004196 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197 }
4198
Michael Wright78f24442014-08-06 15:55:28 -07004199 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004200 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07004201 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
4202 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
4203 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004204 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
4205 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004206 }
4207 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004208 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004209 }
4210
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004211 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004212 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004213 for (const auto& pair : mConnectionsByFd) {
4214 const sp<Connection>& connection = pair.second;
4215 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
4216 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
4217 pair.first, connection->getInputChannelName().c_str(),
4218 connection->getWindowName().c_str(), connection->getStatusLabel(),
4219 toString(connection->monitor),
4220 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004222 if (!connection->outboundQueue.empty()) {
4223 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4224 connection->outboundQueue.size());
4225 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 dump.append(INDENT4);
4227 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004228 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4229 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004230 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004231 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 }
4233 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004234 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 }
4236
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004237 if (!connection->waitQueue.empty()) {
4238 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4239 connection->waitQueue.size());
4240 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004241 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004243 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004244 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004245 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004246 ns2ms(currentTime - entry->eventEntry->eventTime),
4247 ns2ms(currentTime - entry->deliveryTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 }
4249 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004250 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 }
4252 }
4253 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004254 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 }
4256
4257 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004258 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4259 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004261 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 }
4263
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004264 dump += INDENT "Configuration:\n";
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004265 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4266 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4267 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268}
4269
Michael Wright3dd60e22019-03-27 22:06:44 +00004270void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4271 const size_t numMonitors = monitors.size();
4272 for (size_t i = 0; i < numMonitors; i++) {
4273 const Monitor& monitor = monitors[i];
4274 const sp<InputChannel>& channel = monitor.inputChannel;
4275 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4276 dump += "\n";
4277 }
4278}
4279
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004280status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004282 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283#endif
4284
4285 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004286 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004287 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004288 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004290 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 return BAD_VALUE;
4292 }
4293
Garfield Tan1c7bc862020-01-28 13:24:04 -08004294 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295
4296 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 Wrightd02c5b62014-02-10 15:10:22 -08004299
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4301 } // release lock
4302
4303 // Wake the looper because some connections have changed.
4304 mLooper->wake();
4305 return OK;
4306}
4307
Michael Wright3dd60e22019-03-27 22:06:44 +00004308status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004309 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004310 { // acquire lock
4311 std::scoped_lock _l(mLock);
4312
4313 if (displayId < 0) {
4314 ALOGW("Attempted to register input monitor without a specified display.");
4315 return BAD_VALUE;
4316 }
4317
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004318 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004319 ALOGW("Attempted to register input monitor without an identifying token.");
4320 return BAD_VALUE;
4321 }
4322
Garfield Tan1c7bc862020-01-28 13:24:04 -08004323 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004324
4325 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004326 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004327 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004328
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004329 auto& monitorsByDisplay =
4330 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004331 monitorsByDisplay[displayId].emplace_back(inputChannel);
4332
4333 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004334 }
4335 // Wake the looper because some connections have changed.
4336 mLooper->wake();
4337 return OK;
4338}
4339
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4341#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004342 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343#endif
4344
4345 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004346 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347
4348 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4349 if (status) {
4350 return status;
4351 }
4352 } // release lock
4353
4354 // Wake the poll loop because removing the connection may have changed the current
4355 // synchronization state.
4356 mLooper->wake();
4357 return OK;
4358}
4359
4360status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004361 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004362 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004363 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004365 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 return BAD_VALUE;
4367 }
4368
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004369 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004370 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004371
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 if (connection->monitor) {
4373 removeMonitorChannelLocked(inputChannel);
4374 }
4375
4376 mLooper->removeFd(inputChannel->getFd());
4377
4378 nsecs_t currentTime = now();
4379 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4380
4381 connection->status = Connection::STATUS_ZOMBIE;
4382 return OK;
4383}
4384
4385void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004386 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4387 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4388}
4389
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004390void InputDispatcher::removeMonitorChannelLocked(
4391 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004392 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004393 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004394 std::vector<Monitor>& monitors = it->second;
4395 const size_t numMonitors = monitors.size();
4396 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004397 if (monitors[i].inputChannel == inputChannel) {
4398 monitors.erase(monitors.begin() + i);
4399 break;
4400 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004401 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004402 if (monitors.empty()) {
4403 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004404 } else {
4405 ++it;
4406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 }
4408}
4409
Michael Wright3dd60e22019-03-27 22:06:44 +00004410status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4411 { // acquire lock
4412 std::scoped_lock _l(mLock);
4413 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4414
4415 if (!foundDisplayId) {
4416 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4417 return BAD_VALUE;
4418 }
4419 int32_t displayId = foundDisplayId.value();
4420
4421 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4422 if (stateIndex < 0) {
4423 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4424 return BAD_VALUE;
4425 }
4426
4427 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4428 std::optional<int32_t> foundDeviceId;
4429 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004430 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004431 foundDeviceId = state.deviceId;
4432 }
4433 }
4434 if (!foundDeviceId || !state.down) {
4435 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004436 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004437 return BAD_VALUE;
4438 }
4439 int32_t deviceId = foundDeviceId.value();
4440
4441 // Send cancel events to all the input channels we're stealing from.
4442 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004443 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004444 options.deviceId = deviceId;
4445 options.displayId = displayId;
4446 for (const TouchedWindow& window : state.windows) {
4447 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004448 if (channel != nullptr) {
4449 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4450 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004451 }
4452 // Then clear the current touch state so we stop dispatching to them as well.
4453 state.filterNonMonitors();
4454 }
4455 return OK;
4456}
4457
Michael Wright3dd60e22019-03-27 22:06:44 +00004458std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4459 const sp<IBinder>& token) {
4460 for (const auto& it : mGestureMonitorsByDisplay) {
4461 const std::vector<Monitor>& monitors = it.second;
4462 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004463 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004464 return it.first;
4465 }
4466 }
4467 }
4468 return std::nullopt;
4469}
4470
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004471sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004472 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004473 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004474 }
4475
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004476 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004477 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004478 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004479 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480 }
4481 }
Robert Carr4e670e52018-08-15 13:26:12 -07004482
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004483 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484}
4485
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004486void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
4487 removeByValue(mConnectionsByFd, connection);
4488}
4489
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004490void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4491 const sp<Connection>& connection, uint32_t seq,
4492 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004493 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4494 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 commandEntry->connection = connection;
4496 commandEntry->eventTime = currentTime;
4497 commandEntry->seq = seq;
4498 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004499 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500}
4501
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004502void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4503 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004505 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004507 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4508 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004510 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511}
4512
chaviw0c06c6e2019-01-09 13:27:07 -08004513void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004514 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004515 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4516 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004517 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4518 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004519 commandEntry->oldToken = oldToken;
4520 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004521 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004522}
4523
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004524void InputDispatcher::onAnrLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004525 const sp<InputApplicationHandle>& applicationHandle,
4526 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4527 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4529 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4530 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004531 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4532 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4533 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534
4535 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004536 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537 struct tm tm;
4538 localtime_r(&t, &tm);
4539 char timestr[64];
4540 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004541 mLastAnrState.clear();
4542 mLastAnrState += INDENT "ANR:\n";
4543 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
4544 mLastAnrState +=
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004545 StringPrintf(INDENT2 "Window: %s\n",
4546 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004547 mLastAnrState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4548 mLastAnrState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4549 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason);
4550 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004552 std::unique_ptr<CommandEntry> commandEntry =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004553 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004555 commandEntry->inputChannel =
4556 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004558 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559}
4560
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004561void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562 mLock.unlock();
4563
4564 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4565
4566 mLock.lock();
4567}
4568
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004569void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570 sp<Connection> connection = commandEntry->connection;
4571
4572 if (connection->status != Connection::STATUS_ZOMBIE) {
4573 mLock.unlock();
4574
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004575 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576
4577 mLock.lock();
4578 }
4579}
4580
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004581void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004582 sp<IBinder> oldToken = commandEntry->oldToken;
4583 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004584 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004585 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004586 mLock.lock();
4587}
4588
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004589void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004590 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004591 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592 mLock.unlock();
4593
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004594 const nsecs_t timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004595 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596
4597 mLock.lock();
4598
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004599 resumeAfterTargetsNotReadyTimeoutLocked(timeoutExtension, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600}
4601
4602void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4603 CommandEntry* commandEntry) {
4604 KeyEntry* entry = commandEntry->keyEntry;
4605
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004606 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607
4608 mLock.unlock();
4609
Michael Wright2b3c3302018-03-02 17:19:13 +00004610 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004611 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004612 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004613 : nullptr;
4614 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004615 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4616 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004617 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619
4620 mLock.lock();
4621
4622 if (delay < 0) {
4623 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4624 } else if (!delay) {
4625 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4626 } else {
4627 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4628 entry->interceptKeyWakeupTime = now() + delay;
4629 }
4630 entry->release();
4631}
4632
chaviwfd6d3512019-03-25 13:23:49 -07004633void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4634 mLock.unlock();
4635 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4636 mLock.lock();
4637}
4638
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004639void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004641 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004642 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004643 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644
4645 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004646 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004647 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004648 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004650 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004651
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004652 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004653 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004654 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4655 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004656 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004657 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004658
4659 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004660 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004661 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4662 restartEvent =
4663 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004664 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004665 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4666 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4667 handled);
4668 } else {
4669 restartEvent = false;
4670 }
4671
4672 // Dequeue the event and start the next cycle.
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004673 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004674 // contents of the wait queue to have been drained, so we need to double-check
4675 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004676 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4677 if (dispatchEntryIt != connection->waitQueue.end()) {
4678 dispatchEntry = *dispatchEntryIt;
4679 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004680 traceWaitQueueLength(connection);
4681 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004682 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004683 traceOutboundQueueLength(connection);
4684 } else {
4685 releaseDispatchEntry(dispatchEntry);
4686 }
4687 }
4688
4689 // Start the next dispatch cycle for this connection.
4690 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691}
4692
4693bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004694 DispatchEntry* dispatchEntry,
4695 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004696 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004697 if (!handled) {
4698 // Report the key as unhandled, since the fallback was not handled.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004699 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004700 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004701 return false;
4702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004704 // Get the fallback key state.
4705 // Clear it out after dispatching the UP.
4706 int32_t originalKeyCode = keyEntry->keyCode;
4707 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4708 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4709 connection->inputState.removeFallbackKey(originalKeyCode);
4710 }
4711
4712 if (handled || !dispatchEntry->hasForegroundTarget()) {
4713 // If the application handles the original key for which we previously
4714 // generated a fallback or if the window is not a foreground window,
4715 // then cancel the associated fallback key, if any.
4716 if (fallbackKeyCode != -1) {
4717 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004719 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004720 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4721 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4722 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004724 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004725 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726
4727 mLock.unlock();
4728
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004729 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004730 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731
4732 mLock.lock();
4733
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004734 // Cancel the fallback key.
4735 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004737 "application handled the original non-fallback key "
4738 "or is no longer a foreground target, "
4739 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 options.keyCode = fallbackKeyCode;
4741 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004743 connection->inputState.removeFallbackKey(originalKeyCode);
4744 }
4745 } else {
4746 // If the application did not handle a non-fallback key, first check
4747 // that we are in a good state to perform unhandled key event processing
4748 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004749 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004750 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004752 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004753 "since this is not an initial down. "
4754 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4755 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004757 return false;
4758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004760 // Dispatch the unhandled key to the policy.
4761#if DEBUG_OUTBOUND_EVENT_DETAILS
4762 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004763 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4764 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004765#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004766 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004767
4768 mLock.unlock();
4769
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004770 bool fallback =
4771 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4772 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004773
4774 mLock.lock();
4775
4776 if (connection->status != Connection::STATUS_NORMAL) {
4777 connection->inputState.removeFallbackKey(originalKeyCode);
4778 return false;
4779 }
4780
4781 // Latch the fallback keycode for this key on an initial down.
4782 // The fallback keycode cannot change at any other point in the lifecycle.
4783 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004785 fallbackKeyCode = event.getKeyCode();
4786 } else {
4787 fallbackKeyCode = AKEYCODE_UNKNOWN;
4788 }
4789 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4790 }
4791
4792 ALOG_ASSERT(fallbackKeyCode != -1);
4793
4794 // Cancel the fallback key if the policy decides not to send it anymore.
4795 // We will continue to dispatch the key to the policy but we will no
4796 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004797 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4798 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004799#if DEBUG_OUTBOUND_EVENT_DETAILS
4800 if (fallback) {
4801 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004802 "as a fallback for %d, but on the DOWN it had requested "
4803 "to send %d instead. Fallback canceled.",
4804 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004805 } else {
4806 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004807 "but on the DOWN it had requested to send %d. "
4808 "Fallback canceled.",
4809 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004810 }
4811#endif
4812
4813 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4814 "canceling fallback, policy no longer desires it");
4815 options.keyCode = fallbackKeyCode;
4816 synthesizeCancelationEventsForConnectionLocked(connection, options);
4817
4818 fallback = false;
4819 fallbackKeyCode = AKEYCODE_UNKNOWN;
4820 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004821 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004822 }
4823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824
4825#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004826 {
4827 std::string msg;
4828 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4829 connection->inputState.getFallbackKeys();
4830 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004831 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004833 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004834 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004835 }
4836#endif
4837
4838 if (fallback) {
4839 // Restart the dispatch cycle using the fallback key.
4840 keyEntry->eventTime = event.getEventTime();
4841 keyEntry->deviceId = event.getDeviceId();
4842 keyEntry->source = event.getSource();
4843 keyEntry->displayId = event.getDisplayId();
4844 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4845 keyEntry->keyCode = fallbackKeyCode;
4846 keyEntry->scanCode = event.getScanCode();
4847 keyEntry->metaState = event.getMetaState();
4848 keyEntry->repeatCount = event.getRepeatCount();
4849 keyEntry->downTime = event.getDownTime();
4850 keyEntry->syntheticRepeat = false;
4851
4852#if DEBUG_OUTBOUND_EVENT_DETAILS
4853 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004854 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4855 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004856#endif
4857 return true; // restart the event
4858 } else {
4859#if DEBUG_OUTBOUND_EVENT_DETAILS
4860 ALOGD("Unhandled key event: No fallback key.");
4861#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004862
4863 // Report the key as unhandled, since there is no fallback key.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004864 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 }
4866 }
4867 return false;
4868}
4869
4870bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004871 DispatchEntry* dispatchEntry,
4872 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 return false;
4874}
4875
4876void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4877 mLock.unlock();
4878
4879 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4880
4881 mLock.lock();
4882}
4883
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004884KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4885 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004886 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08004887 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
4888 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004889 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890}
4891
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004892void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
4893 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 // TODO Write some statistics about how long we spend waiting.
4895}
4896
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004897/**
4898 * Report the touch event latency to the statsd server.
4899 * Input events are reported for statistics if:
4900 * - This is a touchscreen event
4901 * - InputFilter is not enabled
4902 * - Event is not injected or synthesized
4903 *
4904 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4905 * from getting aggregated with the "old" data.
4906 */
4907void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4908 REQUIRES(mLock) {
4909 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4910 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4911 if (!reportForStatistics) {
4912 return;
4913 }
4914
4915 if (mTouchStatistics.shouldReport()) {
4916 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4917 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4918 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4919 mTouchStatistics.reset();
4920 }
4921 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4922 mTouchStatistics.addValue(latencyMicros);
4923}
4924
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925void InputDispatcher::traceInboundQueueLengthLocked() {
4926 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004927 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 }
4929}
4930
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004931void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932 if (ATRACE_ENABLED()) {
4933 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004934 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004935 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936 }
4937}
4938
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004939void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940 if (ATRACE_ENABLED()) {
4941 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004942 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004943 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 }
4945}
4946
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004947void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004948 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004949
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004950 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951 dumpDispatchStateLocked(dump);
4952
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004953 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004954 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004955 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956 }
4957}
4958
4959void InputDispatcher::monitor() {
4960 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004961 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004962 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004963 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964}
4965
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004966/**
4967 * Wake up the dispatcher and wait until it processes all events and commands.
4968 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4969 * this method can be safely called from any thread, as long as you've ensured that
4970 * the work you are interested in completing has already been queued.
4971 */
4972bool InputDispatcher::waitForIdle() {
4973 /**
4974 * Timeout should represent the longest possible time that a device might spend processing
4975 * events and commands.
4976 */
4977 constexpr std::chrono::duration TIMEOUT = 100ms;
4978 std::unique_lock lock(mLock);
4979 mLooper->wake();
4980 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4981 return result == std::cv_status::no_timeout;
4982}
4983
Garfield Tane84e6f92019-08-29 17:28:41 -07004984} // namespace android::inputdispatcher