blob: 6fd801e8a2dfdd2e9eda4fb4c94d29a496b5a21b [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Garfield Tane84e6f92019-08-29 17:28:41 -070048#include "Connection.h"
49
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <errno.h>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080051#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <limits.h>
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -050053#include <statslog.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080055#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056#include <unistd.h>
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -070057#include <queue>
58#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070059
Michael Wright2b3c3302018-03-02 17:19:13 +000060#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070062#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080063#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <log/log.h>
Gang Wang342c9272020-01-13 13:15:04 -050065#include <openssl/hmac.h>
66#include <openssl/rand.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070067#include <powermanager/PowerManager.h>
68#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080069
70#define INDENT " "
71#define INDENT2 " "
72#define INDENT3 " "
73#define INDENT4 " "
74
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080075using android::base::StringPrintf;
76
Garfield Tane84e6f92019-08-29 17:28:41 -070077namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
79// Default input dispatching timeout if there is no focused application or paused window
80// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000081constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Amount of time to allow for all pending events to be processed when an app switch
84// key is on the way. This is used to preempt input dispatch and drop input events
85// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000086constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow for an event to be dispatched (measured since its eventTime)
89// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92// Amount of time to allow touch events to be streamed out to a connection before requiring
93// that the first event be finished. This value extends the ANR timeout by the specified
94// amount. For example, if streaming is allowed to get ahead by one second relative to the
95// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000096constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
98// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000099constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
100
101// Log a warning when an interception call takes longer than this to process.
102constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
104// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107static inline nsecs_t now() {
108 return systemTime(SYSTEM_TIME_MONOTONIC);
109}
110
111static inline const char* toString(bool value) {
112 return value ? "true" : "false";
113}
114
115static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700116 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
117 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118}
119
120static bool isValidKeyAction(int32_t action) {
121 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700122 case AKEY_EVENT_ACTION_DOWN:
123 case AKEY_EVENT_ACTION_UP:
124 return true;
125 default:
126 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127 }
128}
129
130static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 ALOGE("Key event has invalid action code 0x%x", action);
133 return false;
134 }
135 return true;
136}
137
Michael Wright7b159c92015-05-14 14:48:03 +0100138static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 case AMOTION_EVENT_ACTION_DOWN:
141 case AMOTION_EVENT_ACTION_UP:
142 case AMOTION_EVENT_ACTION_CANCEL:
143 case AMOTION_EVENT_ACTION_MOVE:
144 case AMOTION_EVENT_ACTION_OUTSIDE:
145 case AMOTION_EVENT_ACTION_HOVER_ENTER:
146 case AMOTION_EVENT_ACTION_HOVER_MOVE:
147 case AMOTION_EVENT_ACTION_HOVER_EXIT:
148 case AMOTION_EVENT_ACTION_SCROLL:
149 return true;
150 case AMOTION_EVENT_ACTION_POINTER_DOWN:
151 case AMOTION_EVENT_ACTION_POINTER_UP: {
152 int32_t index = getMotionEventActionPointerIndex(action);
153 return index >= 0 && index < pointerCount;
154 }
155 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
156 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
157 return actionButton != 0;
158 default:
159 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160 }
161}
162
Michael Wright7b159c92015-05-14 14:48:03 +0100163static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 const PointerProperties* pointerProperties) {
165 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 ALOGE("Motion event has invalid action code 0x%x", action);
167 return false;
168 }
169 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000170 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700171 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 return false;
173 }
174 BitSet32 pointerIdBits;
175 for (size_t i = 0; i < pointerCount; i++) {
176 int32_t id = pointerProperties[i].id;
177 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
179 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 return false;
181 }
182 if (pointerIdBits.hasBit(id)) {
183 ALOGE("Motion event has duplicate pointer id %d", id);
184 return false;
185 }
186 pointerIdBits.markBit(id);
187 }
188 return true;
189}
190
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800191static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800193 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 return;
195 }
196
197 bool first = true;
198 Region::const_iterator cur = region.begin();
199 Region::const_iterator const tail = region.end();
200 while (cur != tail) {
201 if (first) {
202 first = false;
203 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800204 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800206 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 cur++;
208 }
209}
210
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700211/**
212 * Find the entry in std::unordered_map by key, and return it.
213 * If the entry is not found, return a default constructed entry.
214 *
215 * Useful when the entries are vectors, since an empty vector will be returned
216 * if the entry is not found.
217 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
218 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700219template <typename K, typename V>
220static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700221 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700222 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800223}
224
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700225/**
226 * Find the entry in std::unordered_map by value, and remove it.
227 * If more than one entry has the same value, then all matching
228 * key-value pairs will be removed.
229 *
230 * Return true if at least one value has been removed.
231 */
232template <typename K, typename V>
233static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
234 bool removed = false;
235 for (auto it = map.begin(); it != map.end();) {
236 if (it->second == value) {
237 it = map.erase(it);
238 removed = true;
239 } else {
240 it++;
241 }
242 }
243 return removed;
244}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245
chaviwaf87b3e2019-10-01 16:59:28 -0700246static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
247 if (first == second) {
248 return true;
249 }
250
251 if (first == nullptr || second == nullptr) {
252 return false;
253 }
254
255 return first->getToken() == second->getToken();
256}
257
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800258static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
259 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
260}
261
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000262static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
263 EventEntry* eventEntry,
264 int32_t inputTargetFlags) {
265 if (inputTarget.useDefaultPointerInfo()) {
266 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
267 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
268 inputTargetFlags, pointerInfo.xOffset,
269 pointerInfo.yOffset, inputTarget.globalScaleFactor,
270 pointerInfo.windowXScale, pointerInfo.windowYScale);
271 }
272
273 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
274 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
275
276 PointerCoords pointerCoords[motionEntry.pointerCount];
277
278 // Use the first pointer information to normalize all other pointers. This could be any pointer
279 // as long as all other pointers are normalized to the same value and the final DispatchEntry
280 // uses the offset and scale for the normalized pointer.
281 const PointerInfo& firstPointerInfo =
282 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
283
284 // Iterate through all pointers in the event to normalize against the first.
285 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
286 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
287 uint32_t pointerId = uint32_t(pointerProperties.id);
288 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
289
290 // The scale factor is the ratio of the current pointers scale to the normalized scale.
291 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
292 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
293
294 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
295 // First apply the current pointers offset to set the window at 0,0
296 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
297 // Next scale the coordinates.
298 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
299 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
300 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
301 -firstPointerInfo.yOffset);
302 }
303
304 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-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
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700331static void addGestureMonitors(const std::vector<Monitor>& monitors,
332 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
333 float yOffset = 0) {
334 if (monitors.empty()) {
335 return;
336 }
337 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
338 for (const Monitor& monitor : monitors) {
339 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
340 }
341}
342
Gang Wang342c9272020-01-13 13:15:04 -0500343static std::array<uint8_t, 128> getRandomKey() {
344 std::array<uint8_t, 128> key;
345 if (RAND_bytes(key.data(), key.size()) != 1) {
346 LOG_ALWAYS_FATAL("Can't generate HMAC key");
347 }
348 return key;
349}
350
351// --- HmacKeyManager ---
352
353HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
354
355std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
356 size_t size;
357 switch (event.type) {
358 case VerifiedInputEvent::Type::KEY: {
359 size = sizeof(VerifiedKeyEvent);
360 break;
361 }
362 case VerifiedInputEvent::Type::MOTION: {
363 size = sizeof(VerifiedMotionEvent);
364 break;
365 }
366 }
367 std::vector<uint8_t> data;
368 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
369 data.assign(start, start + size);
370 return sign(data);
371}
372
373std::array<uint8_t, 32> HmacKeyManager::sign(const std::vector<uint8_t>& data) const {
374 // SHA256 always generates 32-bytes result
375 std::array<uint8_t, 32> hash;
376 unsigned int hashLen = 0;
377 uint8_t* result = HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data.data(), data.size(),
378 hash.data(), &hashLen);
379 if (result == nullptr) {
380 ALOGE("Could not sign the data using HMAC");
381 return INVALID_HMAC;
382 }
383
384 if (hashLen != hash.size()) {
385 ALOGE("HMAC-SHA256 has unexpected length");
386 return INVALID_HMAC;
387 }
388
389 return hash;
390}
391
Michael Wrightd02c5b62014-02-10 15:10:22 -0800392// --- InputDispatcher ---
393
Garfield Tan00f511d2019-06-12 16:55:40 -0700394InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
395 : mPolicy(policy),
396 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700397 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800398 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700399 mAppSwitchSawKeyDown(false),
400 mAppSwitchDueTime(LONG_LONG_MAX),
401 mNextUnblockedEvent(nullptr),
402 mDispatchEnabled(false),
403 mDispatchFrozen(false),
404 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800405 // mInTouchMode will be initialized by the WindowManager to the default device config.
406 // To avoid leaking stack in case that call never comes, and for tests,
407 // initialize it here anyways.
408 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700409 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
410 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800412 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413
Yi Kong9b14ac62018-07-17 13:48:38 -0700414 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800415
416 policy->getDispatcherConfiguration(&mConfig);
417}
418
419InputDispatcher::~InputDispatcher() {
420 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800421 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800422
423 resetKeyRepeatLocked();
424 releasePendingEventLocked();
425 drainInboundQueueLocked();
426 }
427
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700428 while (!mConnectionsByFd.empty()) {
429 sp<Connection> connection = mConnectionsByFd.begin()->second;
430 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 }
432}
433
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700434status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700435 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700436 return ALREADY_EXISTS;
437 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700438 mThread = std::make_unique<InputThread>(
439 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
440 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700441}
442
443status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700444 if (mThread && mThread->isCallingThread()) {
445 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700446 return INVALID_OPERATION;
447 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700448 mThread.reset();
449 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700450}
451
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452void InputDispatcher::dispatchOnce() {
453 nsecs_t nextWakeupTime = LONG_LONG_MAX;
454 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800455 std::scoped_lock _l(mLock);
456 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800457
458 // Run a dispatch loop if there are no pending commands.
459 // The dispatch loop might enqueue commands to run afterwards.
460 if (!haveCommandsLocked()) {
461 dispatchOnceInnerLocked(&nextWakeupTime);
462 }
463
464 // Run all pending commands if there are any.
465 // If any commands were run then force the next poll to wake up immediately.
466 if (runCommandsLockedInterruptible()) {
467 nextWakeupTime = LONG_LONG_MIN;
468 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800469
470 // We are about to enter an infinitely long sleep, because we have no commands or
471 // pending or queued events
472 if (nextWakeupTime == LONG_LONG_MAX) {
473 mDispatcherEnteredIdle.notify_all();
474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800475 } // release lock
476
477 // Wait for callback or timeout or wake. (make sure we round up, not down)
478 nsecs_t currentTime = now();
479 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
480 mLooper->pollOnce(timeoutMillis);
481}
482
483void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
484 nsecs_t currentTime = now();
485
Jeff Browndc5992e2014-04-11 01:27:26 -0700486 // Reset the key repeat timer whenever normal dispatch is suspended while the
487 // device is in a non-interactive state. This is to ensure that we abort a key
488 // repeat if the device is just coming out of sleep.
489 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490 resetKeyRepeatLocked();
491 }
492
493 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
494 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100495 if (DEBUG_FOCUS) {
496 ALOGD("Dispatch frozen. Waiting some more.");
497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800498 return;
499 }
500
501 // Optimize latency of app switches.
502 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
503 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
504 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
505 if (mAppSwitchDueTime < *nextWakeupTime) {
506 *nextWakeupTime = mAppSwitchDueTime;
507 }
508
509 // Ready to start a new event.
510 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700511 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700512 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513 if (isAppSwitchDue) {
514 // The inbound queue is empty so the app switch key we were waiting
515 // for will never arrive. Stop waiting for it.
516 resetPendingAppSwitchLocked(false);
517 isAppSwitchDue = false;
518 }
519
520 // Synthesize a key repeat if appropriate.
521 if (mKeyRepeatState.lastKeyEntry) {
522 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
523 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
524 } else {
525 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
526 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
527 }
528 }
529 }
530
531 // Nothing to do if there is no pending event.
532 if (!mPendingEvent) {
533 return;
534 }
535 } else {
536 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700537 mPendingEvent = mInboundQueue.front();
538 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539 traceInboundQueueLengthLocked();
540 }
541
542 // Poke user activity for this event.
543 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700544 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 }
546
547 // Get ready to dispatch the event.
548 resetANRTimeoutsLocked();
549 }
550
551 // Now we have an event to dispatch.
552 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700553 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700555 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700557 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700559 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560 }
561
562 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700563 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564 }
565
566 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700567 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700568 ConfigurationChangedEntry* typedEntry =
569 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
570 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700571 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700572 break;
573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700575 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700576 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
577 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700578 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700579 break;
580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100582 case EventEntry::Type::FOCUS: {
583 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
584 dispatchFocusLocked(currentTime, typedEntry);
585 done = true;
586 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
587 break;
588 }
589
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700590 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700591 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
592 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700593 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700594 resetPendingAppSwitchLocked(true);
595 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700596 } else if (dropReason == DropReason::NOT_DROPPED) {
597 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700598 }
599 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700600 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700601 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700602 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700603 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
604 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700605 }
606 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
607 break;
608 }
609
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700610 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700611 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700612 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
613 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800614 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700615 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700616 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700617 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700618 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
619 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700620 }
621 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
622 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 }
625
626 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700627 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700628 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 }
Michael Wright3a981722015-06-10 15:26:13 +0100630 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631
632 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700633 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634 }
635}
636
637bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700638 bool needWake = mInboundQueue.empty();
639 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640 traceInboundQueueLengthLocked();
641
642 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700643 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700644 // Optimize app switch latency.
645 // If the application takes too long to catch up then we drop all events preceding
646 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700647 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700648 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700649 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700650 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700651 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700652 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700654 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700656 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700657 mAppSwitchSawKeyDown = false;
658 needWake = true;
659 }
660 }
661 }
662 break;
663 }
664
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700665 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700666 // Optimize case where the current application is unresponsive and the user
667 // decides to touch a window in a different application.
668 // If the application takes too long to catch up then we drop all events preceding
669 // the touch into the other window.
670 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
671 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
672 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
673 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
674 mInputTargetWaitApplicationToken != nullptr) {
675 int32_t displayId = motionEntry->displayId;
676 int32_t x =
677 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
678 int32_t y =
679 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
680 sp<InputWindowHandle> touchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700681 findTouchedWindowAtLocked(displayId, x, y, nullptr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700682 if (touchedWindowHandle != nullptr &&
683 touchedWindowHandle->getApplicationToken() !=
684 mInputTargetWaitApplicationToken) {
685 // User touched a different application than the one we are waiting on.
686 // Flag the event, and start pruning the input queue.
687 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 needWake = true;
689 }
690 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700691 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700693 case EventEntry::Type::CONFIGURATION_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100694 case EventEntry::Type::DEVICE_RESET:
695 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700696 // nothing to do
697 break;
698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699 }
700
701 return needWake;
702}
703
704void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
705 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700706 mRecentQueue.push_back(entry);
707 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
708 mRecentQueue.front()->release();
709 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710 }
711}
712
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700713sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700714 int32_t y, TouchState* touchState,
715 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700716 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700717 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
718 LOG_ALWAYS_FATAL(
719 "Must provide a valid touch state if adding portal windows or outside targets");
720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800721 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800722 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
723 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 const InputWindowInfo* windowInfo = windowHandle->getInfo();
725 if (windowInfo->displayId == displayId) {
726 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727
728 if (windowInfo->visible) {
729 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700730 bool isTouchModal = (flags &
731 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
732 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800734 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700735 if (portalToDisplayId != ADISPLAY_ID_NONE &&
736 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800737 if (addPortalWindows) {
738 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700739 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800740 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700741 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700742 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 // Found window.
745 return windowHandle;
746 }
747 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800748
749 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700750 touchState->addOrUpdateWindow(windowHandle,
751 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
752 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 }
756 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700757 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758}
759
Garfield Tane84e6f92019-08-29 17:28:41 -0700760std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700761 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000762 std::vector<TouchedMonitor> touchedMonitors;
763
764 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
765 addGestureMonitors(monitors, touchedMonitors);
766 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
767 const InputWindowInfo* windowInfo = portalWindow->getInfo();
768 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700769 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
770 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000771 }
772 return touchedMonitors;
773}
774
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700775void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776 const char* reason;
777 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700778 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700780 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700782 reason = "inbound event was dropped because the policy consumed it";
783 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700784 case DropReason::DISABLED:
785 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700786 ALOGI("Dropped event because input dispatch is disabled.");
787 }
788 reason = "inbound event was dropped because input dispatch is disabled";
789 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700790 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700791 ALOGI("Dropped event because of pending overdue app switch.");
792 reason = "inbound event was dropped because of pending overdue app switch";
793 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700794 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700795 ALOGI("Dropped event because the current application is not responding and the user "
796 "has started interacting with a different application.");
797 reason = "inbound event was dropped because the current application is not responding "
798 "and the user has started interacting with a different application";
799 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700800 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700801 ALOGI("Dropped event because it is stale.");
802 reason = "inbound event was dropped because it is stale";
803 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700804 case DropReason::NOT_DROPPED: {
805 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700806 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808 }
809
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700810 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700811 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
813 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700814 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700816 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700817 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
818 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700819 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
820 synthesizeCancelationEventsForAllConnectionsLocked(options);
821 } else {
822 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
823 synthesizeCancelationEventsForAllConnectionsLocked(options);
824 }
825 break;
826 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100827 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700828 case EventEntry::Type::CONFIGURATION_CHANGED:
829 case EventEntry::Type::DEVICE_RESET: {
830 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
831 break;
832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 }
834}
835
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800836static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700837 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
838 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839}
840
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700841bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
842 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
843 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
844 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845}
846
847bool InputDispatcher::isAppSwitchPendingLocked() {
848 return mAppSwitchDueTime != LONG_LONG_MAX;
849}
850
851void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
852 mAppSwitchDueTime = LONG_LONG_MAX;
853
854#if DEBUG_APP_SWITCH
855 if (handled) {
856 ALOGD("App switch has arrived.");
857 } else {
858 ALOGD("App switch was abandoned.");
859 }
860#endif
861}
862
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700864 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865}
866
867bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700868 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 return false;
870 }
871
872 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700873 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700874 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700876 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877
878 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700879 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 return true;
881}
882
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700883void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
884 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885}
886
887void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700888 while (!mInboundQueue.empty()) {
889 EventEntry* entry = mInboundQueue.front();
890 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 releaseInboundEventLocked(entry);
892 }
893 traceInboundQueueLengthLocked();
894}
895
896void InputDispatcher::releasePendingEventLocked() {
897 if (mPendingEvent) {
898 resetANRTimeoutsLocked();
899 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700900 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 }
902}
903
904void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
905 InjectionState* injectionState = entry->injectionState;
906 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
907#if DEBUG_DISPATCH_CYCLE
908 ALOGD("Injected inbound event was dropped.");
909#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800910 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 }
912 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700913 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 }
915 addRecentEventLocked(entry);
916 entry->release();
917}
918
919void InputDispatcher::resetKeyRepeatLocked() {
920 if (mKeyRepeatState.lastKeyEntry) {
921 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700922 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 }
924}
925
Garfield Tane84e6f92019-08-29 17:28:41 -0700926KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
928
929 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700930 uint32_t policyFlags = entry->policyFlags &
931 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 if (entry->refCount == 1) {
933 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800934 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 entry->eventTime = currentTime;
936 entry->policyFlags = policyFlags;
937 entry->repeatCount += 1;
938 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700939 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800940 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800941 entry->displayId, policyFlags, entry->action, entry->flags,
942 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700943 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944
945 mKeyRepeatState.lastKeyEntry = newEntry;
946 entry->release();
947
948 entry = newEntry;
949 }
950 entry->syntheticRepeat = true;
951
952 // Increment reference count since we keep a reference to the event in
953 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
954 entry->refCount += 1;
955
956 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
957 return entry;
958}
959
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700960bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
961 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700963 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964#endif
965
966 // Reset key repeating in case a keyboard device was added or removed or something.
967 resetKeyRepeatLocked();
968
969 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700970 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
971 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700973 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974 return true;
975}
976
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700979 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700980 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981#endif
982
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700983 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 options.deviceId = entry->deviceId;
985 synthesizeCancelationEventsForAllConnectionsLocked(options);
986 return true;
987}
988
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100989void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
990 FocusEntry* focusEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800991 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100992 enqueueInboundEventLocked(focusEntry);
993}
994
995void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
996 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
997 if (channel == nullptr) {
998 return; // Window has gone away
999 }
1000 InputTarget target;
1001 target.inputChannel = channel;
1002 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1003 entry->dispatchInProgress = true;
1004
1005 dispatchEventLocked(currentTime, entry, {target});
1006}
1007
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001009 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001011 if (!entry->dispatchInProgress) {
1012 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1013 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1014 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1015 if (mKeyRepeatState.lastKeyEntry &&
1016 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 // We have seen two identical key downs in a row which indicates that the device
1018 // driver is automatically generating key repeats itself. We take note of the
1019 // repeat here, but we disable our own next key repeat timer since it is clear that
1020 // we will not need to synthesize key repeats ourselves.
1021 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1022 resetKeyRepeatLocked();
1023 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1024 } else {
1025 // Not a repeat. Save key down state in case we do see a repeat later.
1026 resetKeyRepeatLocked();
1027 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1028 }
1029 mKeyRepeatState.lastKeyEntry = entry;
1030 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 resetKeyRepeatLocked();
1033 }
1034
1035 if (entry->repeatCount == 1) {
1036 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1037 } else {
1038 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1039 }
1040
1041 entry->dispatchInProgress = true;
1042
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001043 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 }
1045
1046 // Handle case where the policy asked us to try again later last time.
1047 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1048 if (currentTime < entry->interceptKeyWakeupTime) {
1049 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1050 *nextWakeupTime = entry->interceptKeyWakeupTime;
1051 }
1052 return false; // wait until next wakeup
1053 }
1054 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1055 entry->interceptKeyWakeupTime = 0;
1056 }
1057
1058 // Give the policy a chance to intercept the key.
1059 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1060 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001061 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001062 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001063 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001064 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001065 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001066 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 }
1068 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001069 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070 entry->refCount += 1;
1071 return false; // wait for the command to run
1072 } else {
1073 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1074 }
1075 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001076 if (*dropReason == DropReason::NOT_DROPPED) {
1077 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078 }
1079 }
1080
1081 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001082 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001083 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001084 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001086 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087 return true;
1088 }
1089
1090 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001091 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001092 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001093 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1095 return false;
1096 }
1097
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001098 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1100 return true;
1101 }
1102
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001103 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001104 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105
1106 // Dispatch the key.
1107 dispatchEventLocked(currentTime, entry, inputTargets);
1108 return true;
1109}
1110
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001111void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001113 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1115 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001116 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1117 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1118 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119#endif
1120}
1121
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001122bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1123 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001124 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001126 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 entry->dispatchInProgress = true;
1128
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001129 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 }
1131
1132 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001133 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001134 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001135 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001136 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 return true;
1138 }
1139
1140 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1141
1142 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001143 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144
1145 bool conflictingPointerActions = false;
1146 int32_t injectionResult;
1147 if (isPointerEvent) {
1148 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001149 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001150 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001151 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 } else {
1153 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001154 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001155 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 }
1157 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1158 return false;
1159 }
1160
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001161 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001163 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001164 CancelationOptions::Mode mode(isPointerEvent
1165 ? CancelationOptions::CANCEL_POINTER_EVENTS
1166 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001167 CancelationOptions options(mode, "input event injection failed");
1168 synthesizeCancelationEventsForMonitorsLocked(options);
1169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 return true;
1171 }
1172
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001173 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001174 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001176 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001177 std::unordered_map<int32_t, TouchState>::iterator it =
1178 mTouchStatesByDisplay.find(entry->displayId);
1179 if (it != mTouchStatesByDisplay.end()) {
1180 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001181 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001182 // The event has gone through these portal windows, so we add monitoring targets of
1183 // the corresponding displays as well.
1184 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001185 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001186 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001187 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001188 }
1189 }
1190 }
1191 }
1192
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 // Dispatch the motion.
1194 if (conflictingPointerActions) {
1195 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001196 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 synthesizeCancelationEventsForAllConnectionsLocked(options);
1198 }
1199 dispatchEventLocked(currentTime, entry, inputTargets);
1200 return true;
1201}
1202
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001203void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001205 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001206 ", policyFlags=0x%x, "
1207 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1208 "metaState=0x%x, buttonState=0x%x,"
1209 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001210 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1211 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1212 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001214 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001216 "x=%f, y=%f, pressure=%f, size=%f, "
1217 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1218 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001219 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1220 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1221 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1222 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1223 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1224 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1225 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1226 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1227 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1228 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 }
1230#endif
1231}
1232
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001233void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1234 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001235 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236#if DEBUG_DISPATCH_CYCLE
1237 ALOGD("dispatchEventToCurrentInputTargets");
1238#endif
1239
1240 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1241
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001242 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001244 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001245 sp<Connection> connection =
1246 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001247 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001248 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001250 if (DEBUG_FOCUS) {
1251 ALOGD("Dropping event delivery to target with channel '%s' because it "
1252 "is no longer registered with the input dispatcher.",
1253 inputTarget.inputChannel->getName().c_str());
1254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 }
1256 }
1257}
1258
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001259int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001260 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001262 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001263 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001265 if (DEBUG_FOCUS) {
1266 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1267 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1269 mInputTargetWaitStartTime = currentTime;
1270 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1271 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001272 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 }
1274 } else {
1275 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001276 ALOGI("Waiting for application to become ready for input: %s. Reason: %s",
1277 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001279 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001281 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001282 timeout =
1283 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 } else {
1285 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1286 }
1287
1288 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1289 mInputTargetWaitStartTime = currentTime;
1290 mInputTargetWaitTimeoutTime = currentTime + timeout;
1291 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001292 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293
Yi Kong9b14ac62018-07-17 13:48:38 -07001294 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001295 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 }
Robert Carr740167f2018-10-11 19:03:41 -07001297 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1298 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 }
1300 }
1301 }
1302
1303 if (mInputTargetWaitTimeoutExpired) {
1304 return INPUT_EVENT_INJECTION_TIMED_OUT;
1305 }
1306
1307 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001308 onANRLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001309 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310
1311 // Force poll loop to wake up immediately on next iteration once we get the
1312 // ANR response back from the policy.
1313 *nextWakeupTime = LONG_LONG_MIN;
1314 return INPUT_EVENT_INJECTION_PENDING;
1315 } else {
1316 // Force poll loop to wake up when timeout is due.
1317 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1318 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1319 }
1320 return INPUT_EVENT_INJECTION_PENDING;
1321 }
1322}
1323
Robert Carr803535b2018-08-02 16:38:15 -07001324void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001325 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
1326 TouchState& state = pair.second;
Robert Carr803535b2018-08-02 16:38:15 -07001327 state.removeWindowByToken(token);
1328 }
1329}
1330
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001331void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001332 nsecs_t newTimeout, const sp<IBinder>& inputConnectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333 if (newTimeout > 0) {
1334 // Extend the timeout.
1335 mInputTargetWaitTimeoutTime = now() + newTimeout;
1336 } else {
1337 // Give up.
1338 mInputTargetWaitTimeoutExpired = true;
1339
1340 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001341 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001342 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001343 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001345 if (connection->status == Connection::STATUS_NORMAL) {
1346 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1347 "application not responding");
1348 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 }
1350 }
1351 }
1352}
1353
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001354nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1356 return currentTime - mInputTargetWaitStartTime;
1357 }
1358 return 0;
1359}
1360
1361void InputDispatcher::resetANRTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001362 if (DEBUG_FOCUS) {
1363 ALOGD("Resetting ANR timeouts.");
1364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365
1366 // Reset input target wait timeout.
1367 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001368 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369}
1370
Tiger Huang721e26f2018-07-24 22:26:19 +08001371/**
1372 * Get the display id that the given event should go to. If this event specifies a valid display id,
1373 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1374 * Focused display is the display that the user most recently interacted with.
1375 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001376int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001377 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001378 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001379 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001380 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1381 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001382 break;
1383 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001384 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001385 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1386 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001387 break;
1388 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001389 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001390 case EventEntry::Type::CONFIGURATION_CHANGED:
1391 case EventEntry::Type::DEVICE_RESET: {
1392 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001393 return ADISPLAY_ID_NONE;
1394 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001395 }
1396 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1397}
1398
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001401 std::vector<InputTarget>& inputTargets,
1402 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001404 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405
Tiger Huang721e26f2018-07-24 22:26:19 +08001406 int32_t displayId = getTargetDisplayId(entry);
1407 sp<InputWindowHandle> focusedWindowHandle =
1408 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1409 sp<InputApplicationHandle> focusedApplicationHandle =
1410 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1411
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412 // If there is no currently focused window and no focused application
1413 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001414 if (focusedWindowHandle == nullptr) {
1415 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001416 injectionResult =
1417 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1418 nullptr, nextWakeupTime,
1419 "Waiting because no window has focus but there is "
1420 "a focused application that may eventually add a "
1421 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 goto Unresponsive;
1423 }
1424
Arthur Hung3b413f22018-10-26 18:05:34 +08001425 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001426 "%" PRId32 ".",
1427 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1429 goto Failed;
1430 }
1431
1432 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001433 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1435 goto Failed;
1436 }
1437
Jeff Brownffb49772014-10-10 19:01:34 -07001438 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001439 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001440 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001441 injectionResult =
1442 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1443 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 goto Unresponsive;
1445 }
1446
1447 // Success! Output targets.
1448 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001449 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001450 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1451 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452
1453 // Done.
1454Failed:
1455Unresponsive:
1456 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001457 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001458 if (DEBUG_FOCUS) {
1459 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1460 "timeSpentWaitingForApplication=%0.1fms",
1461 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 return injectionResult;
1464}
1465
1466int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001467 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001468 std::vector<InputTarget>& inputTargets,
1469 nsecs_t* nextWakeupTime,
1470 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001471 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 enum InjectionPermission {
1473 INJECTION_PERMISSION_UNKNOWN,
1474 INJECTION_PERMISSION_GRANTED,
1475 INJECTION_PERMISSION_DENIED
1476 };
1477
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 // For security reasons, we defer updating the touch state until we are sure that
1479 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001480 int32_t displayId = entry.displayId;
1481 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1483
1484 // Update the touch state as needed based on the properties of the touch event.
1485 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1486 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1487 sp<InputWindowHandle> newHoverWindowHandle;
1488
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001489 // Copy current touch state into tempTouchState.
1490 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1491 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001492 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001493 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001494 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1495 mTouchStatesByDisplay.find(displayId);
1496 if (oldStateIt != mTouchStatesByDisplay.end()) {
1497 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001498 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001499 }
1500
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001501 bool isSplit = tempTouchState.split;
1502 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1503 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1504 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001505 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1506 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1507 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1508 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1509 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001510 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 bool wrongDevice = false;
1512 if (newGesture) {
1513 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001514 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001515 ALOGI("Dropping event because a pointer for a different device is already down "
1516 "in display %" PRId32,
1517 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001518 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1520 switchedDevice = false;
1521 wrongDevice = true;
1522 goto Failed;
1523 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001524 tempTouchState.reset();
1525 tempTouchState.down = down;
1526 tempTouchState.deviceId = entry.deviceId;
1527 tempTouchState.source = entry.source;
1528 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001530 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001531 ALOGI("Dropping move event because a pointer for a different device is already active "
1532 "in display %" PRId32,
1533 displayId);
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 =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001557 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1558 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001559
1560 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001561 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001562 : 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.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001578 newTouchedWindowHandle = tempTouchState.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 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001614 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 }
1616
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001617 tempTouchState.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.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001622 if (!tempTouchState.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 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001634 tempTouchState.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 =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001639 tempTouchState.getFirstForegroundWindowHandle();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001641 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
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.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001650 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1651 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 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001672 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 }
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
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001684 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1685 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 }
1687
1688 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001689 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690#if DEBUG_HOVER
1691 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001692 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001694 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1695 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1696 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 }
1698 }
1699
1700 // Check permission to inject into all touched foreground windows and ensure there
1701 // is at least one touched foreground window.
1702 {
1703 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001704 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1706 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001707 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1709 injectionPermission = INJECTION_PERMISSION_DENIED;
1710 goto Failed;
1711 }
1712 }
1713 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001714 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001715 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001716 ALOGI("Dropping event because there is no touched foreground window in display "
1717 "%" PRId32 " or gesture monitor to receive it.",
1718 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1720 goto Failed;
1721 }
1722
1723 // Permission granted to injection into all touched foreground windows.
1724 injectionPermission = INJECTION_PERMISSION_GRANTED;
1725 }
1726
1727 // Check whether windows listening for outside touches are owned by the same UID. If it is
1728 // set the policy flag that we will not reveal coordinate information to this window.
1729 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1730 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001731 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001732 if (foregroundWindowHandle) {
1733 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001734 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001735 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1736 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1737 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001738 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1739 InputTarget::FLAG_ZERO_COORDS,
1740 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 }
1743 }
1744 }
1745 }
1746
1747 // Ensure all touched foreground windows are ready for new input.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001748 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001750 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001751 std::string reason =
1752 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1753 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001754 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001755 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1756 touchedWindow.windowHandle,
1757 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 goto Unresponsive;
1759 }
1760 }
1761 }
1762
1763 // If this is the first pointer going down and the touched window has a wallpaper
1764 // then also add the touched wallpaper windows so they are locked in for the duration
1765 // of the touch gesture.
1766 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1767 // engine only supports touch events. We would need to add a mechanism similar
1768 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1769 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1770 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001771 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001772 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001773 const std::vector<sp<InputWindowHandle>> windowHandles =
1774 getWindowHandlesLocked(displayId);
1775 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001777 if (info->displayId == displayId &&
1778 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001779 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001780 .addOrUpdateWindow(windowHandle,
1781 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1782 InputTarget::
1783 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1784 InputTarget::FLAG_DISPATCH_AS_IS,
1785 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 }
1787 }
1788 }
1789 }
1790
1791 // Success! Output targets.
1792 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1793
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001794 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001796 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 }
1798
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001799 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001800 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001801 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001802 }
1803
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804 // Drop the outside or hover touch windows since we will not care about them
1805 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001806 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807
1808Failed:
1809 // Check injection permission once and for all.
1810 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001811 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 injectionPermission = INJECTION_PERMISSION_GRANTED;
1813 } else {
1814 injectionPermission = INJECTION_PERMISSION_DENIED;
1815 }
1816 }
1817
1818 // Update final pieces of touch state if the injector had permission.
1819 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1820 if (!wrongDevice) {
1821 if (switchedDevice) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001822 if (DEBUG_FOCUS) {
1823 ALOGD("Conflicting pointer actions: Switched to a different device.");
1824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 *outConflictingPointerActions = true;
1826 }
1827
1828 if (isHoverAction) {
1829 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001830 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001831 if (DEBUG_FOCUS) {
1832 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1833 "down.");
1834 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 *outConflictingPointerActions = true;
1836 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001837 tempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001838 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1839 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001840 tempTouchState.deviceId = entry.deviceId;
1841 tempTouchState.source = entry.source;
1842 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001844 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1845 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846 // All pointers up or canceled.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001847 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1849 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001850 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001851 if (DEBUG_FOCUS) {
1852 ALOGD("Conflicting pointer actions: Down received while already down.");
1853 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 *outConflictingPointerActions = true;
1855 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1857 // One pointer went up.
1858 if (isSplit) {
1859 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001860 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001862 for (size_t i = 0; i < tempTouchState.windows.size();) {
1863 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1865 touchedWindow.pointerIds.clearBit(pointerId);
1866 if (touchedWindow.pointerIds.isEmpty()) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001867 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 continue;
1869 }
1870 }
1871 i += 1;
1872 }
1873 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001874 }
1875
1876 // Save changes unless the action was scroll in which case the temporary touch
1877 // state was only valid for this one action.
1878 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001879 if (tempTouchState.displayId >= 0) {
1880 mTouchStatesByDisplay[displayId] = tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001881 } else {
1882 mTouchStatesByDisplay.erase(displayId);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001883 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 }
1885
1886 // Update hover state.
1887 mLastHoverWindowHandle = newHoverWindowHandle;
1888 }
1889 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001890 if (DEBUG_FOCUS) {
1891 ALOGD("Not updating touch focus because injection was denied.");
1892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 }
1894
1895Unresponsive:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896
1897 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001898 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001899 if (DEBUG_FOCUS) {
1900 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1901 "timeSpentWaitingForApplication=%0.1fms",
1902 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1903 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 return injectionResult;
1905}
1906
1907void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001908 int32_t targetFlags, BitSet32 pointerIds,
1909 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001910 std::vector<InputTarget>::iterator it =
1911 std::find_if(inputTargets.begin(), inputTargets.end(),
1912 [&windowHandle](const InputTarget& inputTarget) {
1913 return inputTarget.inputChannel->getConnectionToken() ==
1914 windowHandle->getToken();
1915 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00001916
Chavi Weingarten114b77f2020-01-15 22:35:10 +00001917 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001918
1919 if (it == inputTargets.end()) {
1920 InputTarget inputTarget;
1921 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1922 if (inputChannel == nullptr) {
1923 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1924 return;
1925 }
1926 inputTarget.inputChannel = inputChannel;
1927 inputTarget.flags = targetFlags;
1928 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
1929 inputTargets.push_back(inputTarget);
1930 it = inputTargets.end() - 1;
1931 }
1932
1933 ALOG_ASSERT(it->flags == targetFlags);
1934 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
1935
1936 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
1937 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938}
1939
Michael Wright3dd60e22019-03-27 22:06:44 +00001940void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001941 int32_t displayId, float xOffset,
1942 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001943 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1944 mGlobalMonitorsByDisplay.find(displayId);
1945
1946 if (it != mGlobalMonitorsByDisplay.end()) {
1947 const std::vector<Monitor>& monitors = it->second;
1948 for (const Monitor& monitor : monitors) {
1949 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951 }
1952}
1953
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001954void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1955 float yOffset,
1956 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001957 InputTarget target;
1958 target.inputChannel = monitor.inputChannel;
1959 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001960 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00001961 inputTargets.push_back(target);
1962}
1963
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001965 const InjectionState* injectionState) {
1966 if (injectionState &&
1967 (windowHandle == nullptr ||
1968 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1969 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001970 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001972 "owned by uid %d",
1973 injectionState->injectorPid, injectionState->injectorUid,
1974 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 } else {
1976 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001977 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 }
1979 return false;
1980 }
1981 return true;
1982}
1983
Robert Carrc9bf1d32020-04-13 17:21:08 -07001984/**
1985 * Indicate whether one window handle should be considered as obscuring
1986 * another window handle. We only check a few preconditions. Actually
1987 * checking the bounds is left to the caller.
1988 */
1989static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
1990 const sp<InputWindowHandle>& otherHandle) {
1991 // Compare by token so cloned layers aren't counted
1992 if (haveSameToken(windowHandle, otherHandle)) {
1993 return false;
1994 }
1995 auto info = windowHandle->getInfo();
1996 auto otherInfo = otherHandle->getInfo();
1997 if (!otherInfo->visible) {
1998 return false;
1999 } else if (info->ownerPid == otherInfo->ownerPid && otherHandle->getToken() == nullptr) {
2000 // In general, if ownerPid is the same we don't want to generate occlusion
2001 // events. This line is now necessary since we are including all Surfaces
2002 // in occlusion calculation, so if we didn't check PID like this SurfaceView
2003 // would occlude their parents. On the other hand before we started including
2004 // all surfaces in occlusion calculation and had this line, we would count
2005 // windows with an input channel from the same PID as occluding, and so we
2006 // preserve this behavior with the getToken() == null check.
2007 return false;
2008 } else if (otherInfo->isTrustedOverlay()) {
2009 return false;
2010 } else if (otherInfo->displayId != info->displayId) {
2011 return false;
2012 }
2013 return true;
2014}
2015
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002016bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2017 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002019 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2020 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002021 if (windowHandle == otherHandle) {
2022 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002025 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002026 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 return true;
2028 }
2029 }
2030 return false;
2031}
2032
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002033bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2034 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002035 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002036 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002037 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002038 if (windowHandle == otherHandle) {
2039 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002040 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002041 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002042 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002043 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002044 return true;
2045 }
2046 }
2047 return false;
2048}
2049
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002050std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
2051 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002052 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07002053 // If the window is paused then keep waiting.
2054 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002055 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002056 }
2057
2058 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07002059 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002060 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002061 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002062 "registered with the input dispatcher. The window may be in the "
2063 "process of being removed.",
2064 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002065 }
2066
2067 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07002068 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002069 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002070 "The window may be in the process of being removed.",
2071 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07002072 }
2073
2074 // If the connection is backed up then keep waiting.
2075 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002076 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002077 "Outbound queue length: %zu. Wait queue length: %zu.",
2078 targetType, connection->outboundQueue.size(),
2079 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07002080 }
2081
2082 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002083 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07002084 // If the event is a key event, then we must wait for all previous events to
2085 // complete before delivering it because previous events may have the
2086 // side-effect of transferring focus to a different window and we want to
2087 // ensure that the following keys are sent to the new window.
2088 //
2089 // Suppose the user touches a button in a window then immediately presses "A".
2090 // If the button causes a pop-up window to appear then we want to ensure that
2091 // the "A" key is delivered to the new pop-up window. This is because users
2092 // often anticipate pending UI changes when typing on a keyboard.
2093 // To obtain this behavior, we must serialize key events with respect to all
2094 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002095 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002096 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002097 "finished processing all of the input events that were previously "
2098 "delivered to it. Outbound queue length: %zu. Wait queue length: "
2099 "%zu.",
2100 targetType, connection->outboundQueue.size(),
2101 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 }
Jeff Brownffb49772014-10-10 19:01:34 -07002103 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 // Touch events can always be sent to a window immediately because the user intended
2105 // to touch whatever was visible at the time. Even if focus changes or a new
2106 // window appears moments later, the touch event was meant to be delivered to
2107 // whatever window happened to be on screen at the time.
2108 //
2109 // Generic motion events, such as trackball or joystick events are a little trickier.
2110 // Like key events, generic motion events are delivered to the focused window.
2111 // Unlike key events, generic motion events don't tend to transfer focus to other
2112 // windows and it is not important for them to be serialized. So we prefer to deliver
2113 // generic motion events as soon as possible to improve efficiency and reduce lag
2114 // through batching.
2115 //
2116 // The one case where we pause input event delivery is when the wait queue is piling
2117 // up with lots of events because the application is not responding.
2118 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002119 if (!connection->waitQueue.empty() &&
2120 currentTime >=
2121 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002122 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002123 "finished processing certain input events that were delivered to "
2124 "it over "
2125 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
2126 "%0.1fms.",
2127 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
2128 connection->waitQueue.size(),
2129 (currentTime - connection->waitQueue.front()->deliveryTime) *
2130 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 }
2132 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002133 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134}
2135
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002136std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 const sp<InputApplicationHandle>& applicationHandle,
2138 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002139 if (applicationHandle != nullptr) {
2140 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002141 std::string label(applicationHandle->getName());
2142 label += " - ";
2143 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 return label;
2145 } else {
2146 return applicationHandle->getName();
2147 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002148 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 return windowHandle->getName();
2150 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002151 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 }
2153}
2154
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002155void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002156 if (eventEntry.type == EventEntry::Type::FOCUS) {
2157 // Focus events are passed to apps, but do not represent user activity.
2158 return;
2159 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002160 int32_t displayId = getTargetDisplayId(eventEntry);
2161 sp<InputWindowHandle> focusedWindowHandle =
2162 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2163 if (focusedWindowHandle != nullptr) {
2164 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2166#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002167 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168#endif
2169 return;
2170 }
2171 }
2172
2173 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002174 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002175 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002176 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2177 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002178 return;
2179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002181 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002182 eventType = USER_ACTIVITY_EVENT_TOUCH;
2183 }
2184 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002186 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002187 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2188 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002189 return;
2190 }
2191 eventType = USER_ACTIVITY_EVENT_BUTTON;
2192 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002194 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002195 case EventEntry::Type::CONFIGURATION_CHANGED:
2196 case EventEntry::Type::DEVICE_RESET: {
2197 LOG_ALWAYS_FATAL("%s events are not user activity",
2198 EventEntry::typeToString(eventEntry.type));
2199 break;
2200 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 }
2202
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002203 std::unique_ptr<CommandEntry> commandEntry =
2204 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002205 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002207 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208}
2209
2210void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002211 const sp<Connection>& connection,
2212 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002213 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002214 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002215 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002216 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002217 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002218 ATRACE_NAME(message.c_str());
2219 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220#if DEBUG_DISPATCH_CYCLE
2221 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002222 "globalScaleFactor=%f, pointerIds=0x%x %s",
2223 connection->getInputChannelName().c_str(), inputTarget.flags,
2224 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2225 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226#endif
2227
2228 // Skip this event if the connection status is not normal.
2229 // We don't want to enqueue additional outbound events if the connection is broken.
2230 if (connection->status != Connection::STATUS_NORMAL) {
2231#if DEBUG_DISPATCH_CYCLE
2232 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002233 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234#endif
2235 return;
2236 }
2237
2238 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002239 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2240 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2241 "Entry type %s should not have FLAG_SPLIT",
2242 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002244 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002245 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002246 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002247 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 if (!splitMotionEntry) {
2249 return; // split event was dropped
2250 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002251 if (DEBUG_FOCUS) {
2252 ALOGD("channel '%s' ~ Split motion event.",
2253 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002254 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002255 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002256 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 splitMotionEntry->release();
2258 return;
2259 }
2260 }
2261
2262 // Not splitting. Enqueue dispatch entries for the event as is.
2263 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2264}
2265
2266void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002267 const sp<Connection>& connection,
2268 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002269 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002270 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002271 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002272 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002273 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002274 ATRACE_NAME(message.c_str());
2275 }
2276
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002277 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278
2279 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002280 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002281 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002282 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002283 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002284 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002285 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002286 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002287 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002288 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002290 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002291 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292
2293 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002294 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 startDispatchCycleLocked(currentTime, connection);
2296 }
2297}
2298
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002299void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2300 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002301 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002302 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002303 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002304 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2305 connection->getInputChannelName().c_str(),
2306 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002307 ATRACE_NAME(message.c_str());
2308 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002309 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 if (!(inputTargetFlags & dispatchMode)) {
2311 return;
2312 }
2313 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2314
2315 // This is a new event.
2316 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002317 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002318 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002320 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2321 // different EventEntry than what was passed in.
2322 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002324 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002325 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002326 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002327 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002328 dispatchEntry->resolvedAction = keyEntry.action;
2329 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002331 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2332 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002334 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2335 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002337 return; // skip the inconsistent event
2338 }
2339 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002342 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002343 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002344 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2345 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2346 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2347 static_cast<int32_t>(IdGenerator::Source::OTHER);
2348 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002349 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2350 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2351 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2352 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2353 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2354 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2355 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2356 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2357 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2358 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2359 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002360 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002361 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002362 }
2363 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002364 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2365 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002367 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2368 "event",
2369 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002371 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002374 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002375 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2376 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2377 }
2378 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2379 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002382 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2383 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002385 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2386 "event",
2387 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002389 return; // skip the inconsistent event
2390 }
2391
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002392 dispatchEntry->resolvedEventId =
2393 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2394 ? mIdGenerator.nextId()
2395 : motionEntry.id;
2396 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2397 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2398 ") to MotionEvent(id=0x%" PRIx32 ").",
2399 motionEntry.id, dispatchEntry->resolvedEventId);
2400 ATRACE_NAME(message.c_str());
2401 }
2402
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002403 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002404 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002405
2406 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002408 case EventEntry::Type::FOCUS: {
2409 break;
2410 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002411 case EventEntry::Type::CONFIGURATION_CHANGED:
2412 case EventEntry::Type::DEVICE_RESET: {
2413 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002414 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002415 break;
2416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 }
2418
2419 // Remember that we are waiting for this dispatch to complete.
2420 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002421 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 }
2423
2424 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002425 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002426 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002427}
2428
chaviwfd6d3512019-03-25 13:23:49 -07002429void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002430 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002431 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002432 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2433 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002434 return;
2435 }
2436
2437 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2438 if (inputWindowHandle == nullptr) {
2439 return;
2440 }
2441
chaviw8c9cf542019-03-25 13:02:48 -07002442 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002443 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002444
2445 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2446
2447 if (!hasFocusChanged) {
2448 return;
2449 }
2450
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002451 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2452 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002453 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002454 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455}
2456
2457void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002458 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002459 if (ATRACE_ENABLED()) {
2460 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002461 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002462 ATRACE_NAME(message.c_str());
2463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002465 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466#endif
2467
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002468 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2469 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 dispatchEntry->deliveryTime = currentTime;
2471
2472 // Publish the event.
2473 status_t status;
2474 EventEntry* eventEntry = dispatchEntry->eventEntry;
2475 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002476 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002477 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Gang Wange9087892020-01-07 12:17:14 -05002478 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(*keyEntry);
2479 verifiedEvent.flags = dispatchEntry->resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2480 verifiedEvent.action = dispatchEntry->resolvedAction;
2481 std::array<uint8_t, 32> hmac = mHmacKeyManager.sign(verifiedEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002483 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002484 status =
2485 connection->inputPublisher
2486 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2487 keyEntry->deviceId, keyEntry->source,
2488 keyEntry->displayId, std::move(hmac),
2489 dispatchEntry->resolvedAction,
2490 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2491 keyEntry->scanCode, keyEntry->metaState,
2492 keyEntry->repeatCount, keyEntry->downTime,
2493 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002494 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 }
2496
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002497 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002498 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002500 PointerCoords scaledCoords[MAX_POINTERS];
2501 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2502
chaviw82357092020-01-28 13:13:06 -08002503 // Set the X and Y offset and X and Y scale depending on the input source.
2504 float xOffset = 0.0f, yOffset = 0.0f;
2505 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002506 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2507 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2508 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002509 xScale = dispatchEntry->windowXScale;
2510 yScale = dispatchEntry->windowYScale;
2511 xOffset = dispatchEntry->xOffset * xScale;
2512 yOffset = dispatchEntry->yOffset * yScale;
2513 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002514 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2515 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002516 // Don't apply window scale here since we don't want scale to affect raw
2517 // coordinates. The scale will be sent back to the client and applied
2518 // later when requesting relative coordinates.
2519 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2520 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002521 }
2522 usingCoords = scaledCoords;
2523 }
2524 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002525 // We don't want the dispatch target to know.
2526 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2527 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2528 scaledCoords[i].clear();
2529 }
2530 usingCoords = scaledCoords;
2531 }
2532 }
Gang Wange9087892020-01-07 12:17:14 -05002533 VerifiedMotionEvent verifiedEvent =
2534 verifiedMotionEventFromMotionEntry(*motionEntry);
2535 verifiedEvent.actionMasked =
2536 dispatchEntry->resolvedAction & AMOTION_EVENT_ACTION_MASK;
2537 verifiedEvent.flags = dispatchEntry->resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2538 std::array<uint8_t, 32> hmac = mHmacKeyManager.sign(verifiedEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002539
2540 // Publish the motion event.
2541 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002542 .publishMotionEvent(dispatchEntry->seq,
2543 dispatchEntry->resolvedEventId,
2544 motionEntry->deviceId, motionEntry->source,
2545 motionEntry->displayId, std::move(hmac),
2546 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002547 motionEntry->actionButton,
2548 dispatchEntry->resolvedFlags,
2549 motionEntry->edgeFlags, motionEntry->metaState,
2550 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002551 motionEntry->classification, xScale, yScale,
2552 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002553 motionEntry->yPrecision,
2554 motionEntry->xCursorPosition,
2555 motionEntry->yCursorPosition,
2556 motionEntry->downTime, motionEntry->eventTime,
2557 motionEntry->pointerCount,
2558 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002559 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002560 break;
2561 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002562 case EventEntry::Type::FOCUS: {
2563 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2564 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002565 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002566 focusEntry->hasFocus,
2567 mInTouchMode);
2568 break;
2569 }
2570
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002571 case EventEntry::Type::CONFIGURATION_CHANGED:
2572 case EventEntry::Type::DEVICE_RESET: {
2573 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2574 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002575 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577 }
2578
2579 // Check the result.
2580 if (status) {
2581 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002582 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002584 "This is unexpected because the wait queue is empty, so the pipe "
2585 "should be empty and we shouldn't have any problems writing an "
2586 "event to it, status=%d",
2587 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2589 } else {
2590 // Pipe is full and we are waiting for the app to finish process some events
2591 // before sending more events to it.
2592#if DEBUG_DISPATCH_CYCLE
2593 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002594 "waiting for the application to catch up",
2595 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596#endif
2597 connection->inputPublisherBlocked = true;
2598 }
2599 } else {
2600 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002601 "status=%d",
2602 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2604 }
2605 return;
2606 }
2607
2608 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002609 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2610 connection->outboundQueue.end(),
2611 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002612 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002613 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002614 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 }
2616}
2617
2618void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002619 const sp<Connection>& connection, uint32_t seq,
2620 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621#if DEBUG_DISPATCH_CYCLE
2622 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002623 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624#endif
2625
2626 connection->inputPublisherBlocked = false;
2627
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002628 if (connection->status == Connection::STATUS_BROKEN ||
2629 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002630 return;
2631 }
2632
2633 // Notify other system components and prepare to start the next dispatch cycle.
2634 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2635}
2636
2637void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002638 const sp<Connection>& connection,
2639 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002640#if DEBUG_DISPATCH_CYCLE
2641 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002642 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643#endif
2644
2645 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002646 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002647 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002648 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002649 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650
2651 // The connection appears to be unrecoverably broken.
2652 // Ignore already broken or zombie connections.
2653 if (connection->status == Connection::STATUS_NORMAL) {
2654 connection->status = Connection::STATUS_BROKEN;
2655
2656 if (notify) {
2657 // Notify other system components.
2658 onDispatchCycleBrokenLocked(currentTime, connection);
2659 }
2660 }
2661}
2662
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002663void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2664 while (!queue.empty()) {
2665 DispatchEntry* dispatchEntry = queue.front();
2666 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002667 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668 }
2669}
2670
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002671void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002673 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674 }
2675 delete dispatchEntry;
2676}
2677
2678int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2679 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2680
2681 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002682 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002684 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002686 "fd=%d, events=0x%x",
2687 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688 return 0; // remove the callback
2689 }
2690
2691 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002692 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2694 if (!(events & ALOOPER_EVENT_INPUT)) {
2695 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002696 "events=0x%x",
2697 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 return 1;
2699 }
2700
2701 nsecs_t currentTime = now();
2702 bool gotOne = false;
2703 status_t status;
2704 for (;;) {
2705 uint32_t seq;
2706 bool handled;
2707 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2708 if (status) {
2709 break;
2710 }
2711 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2712 gotOne = true;
2713 }
2714 if (gotOne) {
2715 d->runCommandsLockedInterruptible();
2716 if (status == WOULD_BLOCK) {
2717 return 1;
2718 }
2719 }
2720
2721 notify = status != DEAD_OBJECT || !connection->monitor;
2722 if (notify) {
2723 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002724 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725 }
2726 } else {
2727 // Monitor channels are never explicitly unregistered.
2728 // We do it automatically when the remote endpoint is closed so don't warn
2729 // about them.
2730 notify = !connection->monitor;
2731 if (notify) {
2732 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002733 "events=0x%x",
2734 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735 }
2736 }
2737
2738 // Unregister the channel.
2739 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2740 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002741 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742}
2743
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002744void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002746 for (const auto& pair : mConnectionsByFd) {
2747 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748 }
2749}
2750
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002751void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002752 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002753 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2754 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2755}
2756
2757void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2758 const CancelationOptions& options,
2759 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2760 for (const auto& it : monitorsByDisplay) {
2761 const std::vector<Monitor>& monitors = it.second;
2762 for (const Monitor& monitor : monitors) {
2763 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002764 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002765 }
2766}
2767
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2769 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002770 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002771 if (connection == nullptr) {
2772 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002774
2775 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776}
2777
2778void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2779 const sp<Connection>& connection, const CancelationOptions& options) {
2780 if (connection->status == Connection::STATUS_BROKEN) {
2781 return;
2782 }
2783
2784 nsecs_t currentTime = now();
2785
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002786 std::vector<EventEntry*> cancelationEvents =
2787 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002789 if (cancelationEvents.empty()) {
2790 return;
2791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002793 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2794 "with reality: %s, mode=%d.",
2795 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2796 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002798
2799 InputTarget target;
2800 sp<InputWindowHandle> windowHandle =
2801 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2802 if (windowHandle != nullptr) {
2803 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2804 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2805 windowInfo->windowXScale, windowInfo->windowYScale);
2806 target.globalScaleFactor = windowInfo->globalScaleFactor;
2807 }
2808 target.inputChannel = connection->inputChannel;
2809 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2810
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002811 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2812 EventEntry* cancelationEventEntry = cancelationEvents[i];
2813 switch (cancelationEventEntry->type) {
2814 case EventEntry::Type::KEY: {
2815 logOutboundKeyDetails("cancel - ",
2816 static_cast<const KeyEntry&>(*cancelationEventEntry));
2817 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002819 case EventEntry::Type::MOTION: {
2820 logOutboundMotionDetails("cancel - ",
2821 static_cast<const MotionEntry&>(*cancelationEventEntry));
2822 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002824 case EventEntry::Type::FOCUS: {
2825 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2826 break;
2827 }
2828 case EventEntry::Type::CONFIGURATION_CHANGED:
2829 case EventEntry::Type::DEVICE_RESET: {
2830 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2831 EventEntry::typeToString(cancelationEventEntry->type));
2832 break;
2833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 }
2835
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002836 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2837 target, InputTarget::FLAG_DISPATCH_AS_IS);
2838
2839 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002841
2842 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843}
2844
Svet Ganov5d3bc372020-01-26 23:11:07 -08002845void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2846 const sp<Connection>& connection) {
2847 if (connection->status == Connection::STATUS_BROKEN) {
2848 return;
2849 }
2850
2851 nsecs_t currentTime = now();
2852
2853 std::vector<EventEntry*> downEvents =
2854 connection->inputState.synthesizePointerDownEvents(currentTime);
2855
2856 if (downEvents.empty()) {
2857 return;
2858 }
2859
2860#if DEBUG_OUTBOUND_EVENT_DETAILS
2861 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2862 connection->getInputChannelName().c_str(), downEvents.size());
2863#endif
2864
2865 InputTarget target;
2866 sp<InputWindowHandle> windowHandle =
2867 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2868 if (windowHandle != nullptr) {
2869 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2870 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2871 windowInfo->windowXScale, windowInfo->windowYScale);
2872 target.globalScaleFactor = windowInfo->globalScaleFactor;
2873 }
2874 target.inputChannel = connection->inputChannel;
2875 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2876
2877 for (EventEntry* downEventEntry : downEvents) {
2878 switch (downEventEntry->type) {
2879 case EventEntry::Type::MOTION: {
2880 logOutboundMotionDetails("down - ",
2881 static_cast<const MotionEntry&>(*downEventEntry));
2882 break;
2883 }
2884
2885 case EventEntry::Type::KEY:
2886 case EventEntry::Type::FOCUS:
2887 case EventEntry::Type::CONFIGURATION_CHANGED:
2888 case EventEntry::Type::DEVICE_RESET: {
2889 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2890 EventEntry::typeToString(downEventEntry->type));
2891 break;
2892 }
2893 }
2894
2895 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2896 target, InputTarget::FLAG_DISPATCH_AS_IS);
2897
2898 downEventEntry->release();
2899 }
2900
2901 startDispatchCycleLocked(currentTime, connection);
2902}
2903
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002904MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002905 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906 ALOG_ASSERT(pointerIds.value != 0);
2907
2908 uint32_t splitPointerIndexMap[MAX_POINTERS];
2909 PointerProperties splitPointerProperties[MAX_POINTERS];
2910 PointerCoords splitPointerCoords[MAX_POINTERS];
2911
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002912 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913 uint32_t splitPointerCount = 0;
2914
2915 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002916 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002918 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919 uint32_t pointerId = uint32_t(pointerProperties.id);
2920 if (pointerIds.hasBit(pointerId)) {
2921 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2922 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2923 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002924 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 splitPointerCount += 1;
2926 }
2927 }
2928
2929 if (splitPointerCount != pointerIds.count()) {
2930 // This is bad. We are missing some of the pointers that we expected to deliver.
2931 // Most likely this indicates that we received an ACTION_MOVE events that has
2932 // different pointer ids than we expected based on the previous ACTION_DOWN
2933 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2934 // in this way.
2935 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002936 "we expected there to be %d pointers. This probably means we received "
2937 "a broken sequence of pointer ids from the input device.",
2938 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002939 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 }
2941
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002942 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002944 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2945 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2947 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002948 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949 uint32_t pointerId = uint32_t(pointerProperties.id);
2950 if (pointerIds.hasBit(pointerId)) {
2951 if (pointerIds.count() == 1) {
2952 // The first/last pointer went down/up.
2953 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002954 ? AMOTION_EVENT_ACTION_DOWN
2955 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956 } else {
2957 // A secondary pointer went down/up.
2958 uint32_t splitPointerIndex = 0;
2959 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2960 splitPointerIndex += 1;
2961 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002962 action = maskedAction |
2963 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002964 }
2965 } else {
2966 // An unrelated pointer changed.
2967 action = AMOTION_EVENT_ACTION_MOVE;
2968 }
2969 }
2970
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002971 int32_t newId = mIdGenerator.nextId();
2972 if (ATRACE_ENABLED()) {
2973 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
2974 ") to MotionEvent(id=0x%" PRIx32 ").",
2975 originalMotionEntry.id, newId);
2976 ATRACE_NAME(message.c_str());
2977 }
Garfield Tan00f511d2019-06-12 16:55:40 -07002978 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002979 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
2980 originalMotionEntry.source, originalMotionEntry.displayId,
2981 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002982 originalMotionEntry.actionButton, originalMotionEntry.flags,
2983 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2984 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2985 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2986 originalMotionEntry.xCursorPosition,
2987 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002988 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002989
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002990 if (originalMotionEntry.injectionState) {
2991 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002992 splitMotionEntry->injectionState->refCount += 1;
2993 }
2994
2995 return splitMotionEntry;
2996}
2997
2998void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2999#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003000 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001#endif
3002
3003 bool needWake;
3004 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003005 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006
Prabir Pradhan42611e02018-11-27 14:04:02 -08003007 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003008 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 needWake = enqueueInboundEventLocked(newEntry);
3010 } // release lock
3011
3012 if (needWake) {
3013 mLooper->wake();
3014 }
3015}
3016
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003017/**
3018 * If one of the meta shortcuts is detected, process them here:
3019 * Meta + Backspace -> generate BACK
3020 * Meta + Enter -> generate HOME
3021 * This will potentially overwrite keyCode and metaState.
3022 */
3023void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003025 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3026 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3027 if (keyCode == AKEYCODE_DEL) {
3028 newKeyCode = AKEYCODE_BACK;
3029 } else if (keyCode == AKEYCODE_ENTER) {
3030 newKeyCode = AKEYCODE_HOME;
3031 }
3032 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003033 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003034 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003035 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003036 keyCode = newKeyCode;
3037 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3038 }
3039 } else if (action == AKEY_EVENT_ACTION_UP) {
3040 // In order to maintain a consistent stream of up and down events, check to see if the key
3041 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3042 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003043 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003044 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003045 auto replacementIt = mReplacedKeys.find(replacement);
3046 if (replacementIt != mReplacedKeys.end()) {
3047 keyCode = replacementIt->second;
3048 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003049 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3050 }
3051 }
3052}
3053
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3055#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003056 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3057 "policyFlags=0x%x, action=0x%x, "
3058 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3059 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3060 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3061 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062#endif
3063 if (!validateKeyEvent(args->action)) {
3064 return;
3065 }
3066
3067 uint32_t policyFlags = args->policyFlags;
3068 int32_t flags = args->flags;
3069 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003070 // InputDispatcher tracks and generates key repeats on behalf of
3071 // whatever notifies it, so repeatCount should always be set to 0
3072 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3074 policyFlags |= POLICY_FLAG_VIRTUAL;
3075 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3076 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077 if (policyFlags & POLICY_FLAG_FUNCTION) {
3078 metaState |= AMETA_FUNCTION_ON;
3079 }
3080
3081 policyFlags |= POLICY_FLAG_TRUSTED;
3082
Michael Wright78f24442014-08-06 15:55:28 -07003083 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003084 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003085
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003087 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003088 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3089 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090
Michael Wright2b3c3302018-03-02 17:19:13 +00003091 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003093 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3094 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003095 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098 bool needWake;
3099 { // acquire lock
3100 mLock.lock();
3101
3102 if (shouldSendKeyToInputFilterLocked(args)) {
3103 mLock.unlock();
3104
3105 policyFlags |= POLICY_FLAG_FILTERED;
3106 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3107 return; // event was consumed by the filter
3108 }
3109
3110 mLock.lock();
3111 }
3112
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003113 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003114 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003115 args->displayId, policyFlags, args->action, flags, keyCode,
3116 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117
3118 needWake = enqueueInboundEventLocked(newEntry);
3119 mLock.unlock();
3120 } // release lock
3121
3122 if (needWake) {
3123 mLooper->wake();
3124 }
3125}
3126
3127bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3128 return mInputFilterEnabled;
3129}
3130
3131void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3132#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003133 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3134 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003135 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3136 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003137 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003138 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3139 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3140 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3141 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 for (uint32_t i = 0; i < args->pointerCount; i++) {
3143 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003144 "x=%f, y=%f, pressure=%f, size=%f, "
3145 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3146 "orientation=%f",
3147 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3148 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3149 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3150 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3151 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3152 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3153 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3154 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3155 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3156 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 }
3158#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003159 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3160 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 return;
3162 }
3163
3164 uint32_t policyFlags = args->policyFlags;
3165 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003166
3167 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003168 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003169 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3170 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003171 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173
3174 bool needWake;
3175 { // acquire lock
3176 mLock.lock();
3177
3178 if (shouldSendMotionToInputFilterLocked(args)) {
3179 mLock.unlock();
3180
3181 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003182 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3183 args->action, args->actionButton, args->flags, args->edgeFlags,
3184 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3185 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3186 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3187 args->downTime, args->eventTime, args->pointerCount,
3188 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189
3190 policyFlags |= POLICY_FLAG_FILTERED;
3191 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3192 return; // event was consumed by the filter
3193 }
3194
3195 mLock.lock();
3196 }
3197
3198 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003199 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003200 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003201 args->displayId, policyFlags, args->action, args->actionButton,
3202 args->flags, args->metaState, args->buttonState,
3203 args->classification, args->edgeFlags, args->xPrecision,
3204 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3205 args->downTime, args->pointerCount, args->pointerProperties,
3206 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207
3208 needWake = enqueueInboundEventLocked(newEntry);
3209 mLock.unlock();
3210 } // release lock
3211
3212 if (needWake) {
3213 mLooper->wake();
3214 }
3215}
3216
3217bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003218 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219}
3220
3221void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3222#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003223 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003224 "switchMask=0x%08x",
3225 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226#endif
3227
3228 uint32_t policyFlags = args->policyFlags;
3229 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003230 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231}
3232
3233void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3234#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003235 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3236 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237#endif
3238
3239 bool needWake;
3240 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003241 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242
Prabir Pradhan42611e02018-11-27 14:04:02 -08003243 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003244 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 needWake = enqueueInboundEventLocked(newEntry);
3246 } // release lock
3247
3248 if (needWake) {
3249 mLooper->wake();
3250 }
3251}
3252
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003253int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3254 int32_t injectorUid, int32_t syncMode,
3255 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256#if DEBUG_INBOUND_EVENT_DETAILS
3257 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003258 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
3259 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003260#endif
3261
3262 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
3263
3264 policyFlags |= POLICY_FLAG_INJECTED;
3265 if (hasInjectionPermission(injectorPid, injectorUid)) {
3266 policyFlags |= POLICY_FLAG_TRUSTED;
3267 }
3268
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003269 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003271 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003272 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3273 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003274 if (!validateKeyEvent(action)) {
3275 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003278 int32_t flags = incomingKey.getFlags();
3279 int32_t keyCode = incomingKey.getKeyCode();
3280 int32_t metaState = incomingKey.getMetaState();
3281 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003282 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003283 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003284 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003285 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3286 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3287 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003289 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3290 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003291 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003292
3293 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3294 android::base::Timer t;
3295 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3296 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3297 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3298 std::to_string(t.duration().count()).c_str());
3299 }
3300 }
3301
3302 mLock.lock();
3303 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003304 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3305 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003306 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3307 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003308 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003309 injectedEntries.push(injectedEntry);
3310 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 }
3312
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003313 case AINPUT_EVENT_TYPE_MOTION: {
3314 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3315 int32_t action = motionEvent->getAction();
3316 size_t pointerCount = motionEvent->getPointerCount();
3317 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3318 int32_t actionButton = motionEvent->getActionButton();
3319 int32_t displayId = motionEvent->getDisplayId();
3320 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3321 return INPUT_EVENT_INJECTION_FAILED;
3322 }
3323
3324 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3325 nsecs_t eventTime = motionEvent->getEventTime();
3326 android::base::Timer t;
3327 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3328 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3329 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3330 std::to_string(t.duration().count()).c_str());
3331 }
3332 }
3333
3334 mLock.lock();
3335 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3336 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3337 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003338 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3339 motionEvent->getSource(), motionEvent->getDisplayId(),
3340 policyFlags, action, actionButton, motionEvent->getFlags(),
3341 motionEvent->getMetaState(), motionEvent->getButtonState(),
3342 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3343 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003344 motionEvent->getRawXCursorPosition(),
3345 motionEvent->getRawYCursorPosition(),
3346 motionEvent->getDownTime(), uint32_t(pointerCount),
3347 pointerProperties, samplePointerCoords,
3348 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003349 injectedEntries.push(injectedEntry);
3350 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3351 sampleEventTimes += 1;
3352 samplePointerCoords += pointerCount;
3353 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003354 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003355 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003356 motionEvent->getDisplayId(), policyFlags, action,
3357 actionButton, motionEvent->getFlags(),
3358 motionEvent->getMetaState(), motionEvent->getButtonState(),
3359 motionEvent->getClassification(),
3360 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3361 motionEvent->getYPrecision(),
3362 motionEvent->getRawXCursorPosition(),
3363 motionEvent->getRawYCursorPosition(),
3364 motionEvent->getDownTime(), uint32_t(pointerCount),
3365 pointerProperties, samplePointerCoords,
3366 motionEvent->getXOffset(), motionEvent->getYOffset());
3367 injectedEntries.push(nextInjectedEntry);
3368 }
3369 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003372 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003373 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003374 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 }
3376
3377 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3378 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3379 injectionState->injectionIsAsync = true;
3380 }
3381
3382 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003383 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384
3385 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003386 while (!injectedEntries.empty()) {
3387 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3388 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389 }
3390
3391 mLock.unlock();
3392
3393 if (needWake) {
3394 mLooper->wake();
3395 }
3396
3397 int32_t injectionResult;
3398 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003399 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400
3401 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3402 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3403 } else {
3404 for (;;) {
3405 injectionResult = injectionState->injectionResult;
3406 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3407 break;
3408 }
3409
3410 nsecs_t remainingTimeout = endTime - now();
3411 if (remainingTimeout <= 0) {
3412#if DEBUG_INJECTION
3413 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003414 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415#endif
3416 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3417 break;
3418 }
3419
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003420 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421 }
3422
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003423 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3424 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 while (injectionState->pendingForegroundDispatches != 0) {
3426#if DEBUG_INJECTION
3427 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003428 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429#endif
3430 nsecs_t remainingTimeout = endTime - now();
3431 if (remainingTimeout <= 0) {
3432#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003433 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3434 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435#endif
3436 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3437 break;
3438 }
3439
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003440 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441 }
3442 }
3443 }
3444
3445 injectionState->release();
3446 } // release lock
3447
3448#if DEBUG_INJECTION
3449 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003450 "injectorPid=%d, injectorUid=%d",
3451 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452#endif
3453
3454 return injectionResult;
3455}
3456
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003457std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003458 std::array<uint8_t, 32> calculatedHmac;
3459 std::unique_ptr<VerifiedInputEvent> result;
3460 switch (event.getType()) {
3461 case AINPUT_EVENT_TYPE_KEY: {
3462 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3463 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3464 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3465 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3466 break;
3467 }
3468 case AINPUT_EVENT_TYPE_MOTION: {
3469 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3470 VerifiedMotionEvent verifiedMotionEvent =
3471 verifiedMotionEventFromMotionEvent(motionEvent);
3472 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3473 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3474 break;
3475 }
3476 default: {
3477 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3478 return nullptr;
3479 }
3480 }
3481 if (calculatedHmac == INVALID_HMAC) {
3482 return nullptr;
3483 }
3484 if (calculatedHmac != event.getHmac()) {
3485 return nullptr;
3486 }
3487 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003488}
3489
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003491 return injectorUid == 0 ||
3492 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493}
3494
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003495void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 InjectionState* injectionState = entry->injectionState;
3497 if (injectionState) {
3498#if DEBUG_INJECTION
3499 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003500 "injectorPid=%d, injectorUid=%d",
3501 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502#endif
3503
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003504 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 // Log the outcome since the injector did not wait for the injection result.
3506 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003507 case INPUT_EVENT_INJECTION_SUCCEEDED:
3508 ALOGV("Asynchronous input event injection succeeded.");
3509 break;
3510 case INPUT_EVENT_INJECTION_FAILED:
3511 ALOGW("Asynchronous input event injection failed.");
3512 break;
3513 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3514 ALOGW("Asynchronous input event injection permission denied.");
3515 break;
3516 case INPUT_EVENT_INJECTION_TIMED_OUT:
3517 ALOGW("Asynchronous input event injection timed out.");
3518 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519 }
3520 }
3521
3522 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003523 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524 }
3525}
3526
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003527void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 InjectionState* injectionState = entry->injectionState;
3529 if (injectionState) {
3530 injectionState->pendingForegroundDispatches += 1;
3531 }
3532}
3533
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003534void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 InjectionState* injectionState = entry->injectionState;
3536 if (injectionState) {
3537 injectionState->pendingForegroundDispatches -= 1;
3538
3539 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003540 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003541 }
3542 }
3543}
3544
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003545std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3546 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003547 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003548}
3549
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003551 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003552 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003553 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3554 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003555 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003556 return windowHandle;
3557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 }
3559 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003560 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561}
3562
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003563bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003564 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003565 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3566 for (const sp<InputWindowHandle>& handle : windowHandles) {
3567 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003568 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003569 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003570 ", but it should belong to display %" PRId32,
3571 windowHandle->getName().c_str(), it.first,
3572 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003573 }
3574 return true;
3575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576 }
3577 }
3578 return false;
3579}
3580
Robert Carr5c8a0262018-10-03 16:30:44 -07003581sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3582 size_t count = mInputChannelsByToken.count(token);
3583 if (count == 0) {
3584 return nullptr;
3585 }
3586 return mInputChannelsByToken.at(token);
3587}
3588
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003589void InputDispatcher::updateWindowHandlesForDisplayLocked(
3590 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3591 if (inputWindowHandles.empty()) {
3592 // Remove all handles on a display if there are no windows left.
3593 mWindowHandlesByDisplay.erase(displayId);
3594 return;
3595 }
3596
3597 // Since we compare the pointer of input window handles across window updates, we need
3598 // to make sure the handle object for the same window stays unchanged across updates.
3599 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003600 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003601 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003602 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003603 }
3604
3605 std::vector<sp<InputWindowHandle>> newHandles;
3606 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3607 if (!handle->updateInfo()) {
3608 // handle no longer valid
3609 continue;
3610 }
3611
3612 const InputWindowInfo* info = handle->getInfo();
3613 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3614 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3615 const bool noInputChannel =
3616 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3617 const bool canReceiveInput =
3618 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3619 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3620 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003621 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003622 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003623 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003624 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003625 }
3626
3627 if (info->displayId != displayId) {
3628 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3629 handle->getName().c_str(), displayId, info->displayId);
3630 continue;
3631 }
3632
chaviwaf87b3e2019-10-01 16:59:28 -07003633 if (oldHandlesById.find(handle->getId()) != oldHandlesById.end()) {
3634 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003635 oldHandle->updateFrom(handle);
3636 newHandles.push_back(oldHandle);
3637 } else {
3638 newHandles.push_back(handle);
3639 }
3640 }
3641
3642 // Insert or replace
3643 mWindowHandlesByDisplay[displayId] = newHandles;
3644}
3645
Arthur Hung72d8dc32020-03-28 00:48:39 +00003646void InputDispatcher::setInputWindows(
3647 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3648 { // acquire lock
3649 std::scoped_lock _l(mLock);
3650 for (auto const& i : handlesPerDisplay) {
3651 setInputWindowsLocked(i.second, i.first);
3652 }
3653 }
3654 // Wake up poll loop since it may need to make new input dispatching choices.
3655 mLooper->wake();
3656}
3657
Arthur Hungb92218b2018-08-14 12:00:21 +08003658/**
3659 * Called from InputManagerService, update window handle list by displayId that can receive input.
3660 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3661 * If set an empty list, remove all handles from the specific display.
3662 * For focused handle, check if need to change and send a cancel event to previous one.
3663 * For removed handle, check if need to send a cancel event if already in touch.
3664 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003665void InputDispatcher::setInputWindowsLocked(
3666 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003667 if (DEBUG_FOCUS) {
3668 std::string windowList;
3669 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3670 windowList += iwh->getName() + " ";
3671 }
3672 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674
Arthur Hung72d8dc32020-03-28 00:48:39 +00003675 // Copy old handles for release if they are no longer present.
3676 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677
Arthur Hung72d8dc32020-03-28 00:48:39 +00003678 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003679
Arthur Hung72d8dc32020-03-28 00:48:39 +00003680 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3681 bool foundHoveredWindow = false;
3682 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3683 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3684 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3685 windowHandle->getInfo()->visible) {
3686 newFocusedWindowHandle = windowHandle;
3687 }
3688 if (windowHandle == mLastHoverWindowHandle) {
3689 foundHoveredWindow = true;
3690 }
3691 }
3692
3693 if (!foundHoveredWindow) {
3694 mLastHoverWindowHandle = nullptr;
3695 }
3696
3697 sp<InputWindowHandle> oldFocusedWindowHandle =
3698 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3699
3700 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3701 if (oldFocusedWindowHandle != nullptr) {
3702 if (DEBUG_FOCUS) {
3703 ALOGD("Focus left window: %s in display %" PRId32,
3704 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003705 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003706 sp<InputChannel> focusedInputChannel =
3707 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3708 if (focusedInputChannel != nullptr) {
3709 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3710 "focus left window");
3711 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3712 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003713 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003714 mFocusedWindowHandlesByDisplay.erase(displayId);
3715 }
3716 if (newFocusedWindowHandle != nullptr) {
3717 if (DEBUG_FOCUS) {
3718 ALOGD("Focus entered window: %s in display %" PRId32,
3719 newFocusedWindowHandle->getName().c_str(), displayId);
3720 }
3721 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3722 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723 }
3724
Arthur Hung72d8dc32020-03-28 00:48:39 +00003725 if (mFocusedDisplayId == displayId) {
3726 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003728 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003730 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3731 mTouchStatesByDisplay.find(displayId);
3732 if (stateIt != mTouchStatesByDisplay.end()) {
3733 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003734 for (size_t i = 0; i < state.windows.size();) {
3735 TouchedWindow& touchedWindow = state.windows[i];
3736 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003737 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003738 ALOGD("Touched window was removed: %s in display %" PRId32,
3739 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003740 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003741 sp<InputChannel> touchedInputChannel =
3742 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3743 if (touchedInputChannel != nullptr) {
3744 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3745 "touched window was removed");
3746 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003748 state.windows.erase(state.windows.begin() + i);
3749 } else {
3750 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 }
3752 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003753 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003754
Arthur Hung72d8dc32020-03-28 00:48:39 +00003755 // Release information for windows that are no longer present.
3756 // This ensures that unused input channels are released promptly.
3757 // Otherwise, they might stick around until the window handle is destroyed
3758 // which might not happen until the next GC.
3759 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3760 if (!hasWindowHandleLocked(oldWindowHandle)) {
3761 if (DEBUG_FOCUS) {
3762 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003763 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003764 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003765 }
chaviw291d88a2019-02-14 10:33:58 -08003766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767}
3768
3769void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003770 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003771 if (DEBUG_FOCUS) {
3772 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3773 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003776 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777
Tiger Huang721e26f2018-07-24 22:26:19 +08003778 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3779 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003780 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003781 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3782 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003785 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003787 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003789 oldFocusedApplicationHandle.clear();
3790 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 } // release lock
3793
3794 // Wake up poll loop since it may need to make new input dispatching choices.
3795 mLooper->wake();
3796}
3797
Tiger Huang721e26f2018-07-24 22:26:19 +08003798/**
3799 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3800 * the display not specified.
3801 *
3802 * We track any unreleased events for each window. If a window loses the ability to receive the
3803 * released event, we will send a cancel event to it. So when the focused display is changed, we
3804 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3805 * display. The display-specified events won't be affected.
3806 */
3807void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003808 if (DEBUG_FOCUS) {
3809 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3810 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003811 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003812 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003813
3814 if (mFocusedDisplayId != displayId) {
3815 sp<InputWindowHandle> oldFocusedWindowHandle =
3816 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3817 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003818 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003819 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003820 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003821 CancelationOptions
3822 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3823 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003824 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003825 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3826 }
3827 }
3828 mFocusedDisplayId = displayId;
3829
3830 // Sanity check
3831 sp<InputWindowHandle> newFocusedWindowHandle =
3832 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003833 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003834
Tiger Huang721e26f2018-07-24 22:26:19 +08003835 if (newFocusedWindowHandle == nullptr) {
3836 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3837 if (!mFocusedWindowHandlesByDisplay.empty()) {
3838 ALOGE("But another display has a focused window:");
3839 for (auto& it : mFocusedWindowHandlesByDisplay) {
3840 const int32_t displayId = it.first;
3841 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003842 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3843 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003844 }
3845 }
3846 }
3847 }
3848
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003849 if (DEBUG_FOCUS) {
3850 logDispatchStateLocked();
3851 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003852 } // release lock
3853
3854 // Wake up poll loop since it may need to make new input dispatching choices.
3855 mLooper->wake();
3856}
3857
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003859 if (DEBUG_FOCUS) {
3860 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3861 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862
3863 bool changed;
3864 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003865 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866
3867 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3868 if (mDispatchFrozen && !frozen) {
3869 resetANRTimeoutsLocked();
3870 }
3871
3872 if (mDispatchEnabled && !enabled) {
3873 resetAndDropEverythingLocked("dispatcher is being disabled");
3874 }
3875
3876 mDispatchEnabled = enabled;
3877 mDispatchFrozen = frozen;
3878 changed = true;
3879 } else {
3880 changed = false;
3881 }
3882
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003883 if (DEBUG_FOCUS) {
3884 logDispatchStateLocked();
3885 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886 } // release lock
3887
3888 if (changed) {
3889 // Wake up poll loop since it may need to make new input dispatching choices.
3890 mLooper->wake();
3891 }
3892}
3893
3894void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003895 if (DEBUG_FOCUS) {
3896 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898
3899 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003900 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901
3902 if (mInputFilterEnabled == enabled) {
3903 return;
3904 }
3905
3906 mInputFilterEnabled = enabled;
3907 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3908 } // release lock
3909
3910 // Wake up poll loop since there might be work to do to drop everything.
3911 mLooper->wake();
3912}
3913
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003914void InputDispatcher::setInTouchMode(bool inTouchMode) {
3915 std::scoped_lock lock(mLock);
3916 mInTouchMode = inTouchMode;
3917}
3918
chaviwfbe5d9c2018-12-26 12:23:37 -08003919bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3920 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003921 if (DEBUG_FOCUS) {
3922 ALOGD("Trivial transfer to same window.");
3923 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003924 return true;
3925 }
3926
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003928 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929
chaviwfbe5d9c2018-12-26 12:23:37 -08003930 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3931 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003932 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003933 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934 return false;
3935 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003936 if (DEBUG_FOCUS) {
3937 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3938 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003941 if (DEBUG_FOCUS) {
3942 ALOGD("Cannot transfer focus because windows are on different displays.");
3943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 return false;
3945 }
3946
3947 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003948 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
3949 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003950 for (size_t i = 0; i < state.windows.size(); i++) {
3951 const TouchedWindow& touchedWindow = state.windows[i];
3952 if (touchedWindow.windowHandle == fromWindowHandle) {
3953 int32_t oldTargetFlags = touchedWindow.targetFlags;
3954 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003956 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003958 int32_t newTargetFlags = oldTargetFlags &
3959 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3960 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003961 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962
Jeff Brownf086ddb2014-02-11 14:28:48 -08003963 found = true;
3964 goto Found;
3965 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 }
3967 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003968 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003970 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003971 if (DEBUG_FOCUS) {
3972 ALOGD("Focus transfer failed because from window did not have focus.");
3973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 return false;
3975 }
3976
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003977 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3978 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003979 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003980 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003981 CancelationOptions
3982 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3983 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003985 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 }
3987
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003988 if (DEBUG_FOCUS) {
3989 logDispatchStateLocked();
3990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 } // release lock
3992
3993 // Wake up poll loop since it may need to make new input dispatching choices.
3994 mLooper->wake();
3995 return true;
3996}
3997
3998void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003999 if (DEBUG_FOCUS) {
4000 ALOGD("Resetting and dropping all events (%s).", reason);
4001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002
4003 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4004 synthesizeCancelationEventsForAllConnectionsLocked(options);
4005
4006 resetKeyRepeatLocked();
4007 releasePendingEventLocked();
4008 drainInboundQueueLocked();
4009 resetANRTimeoutsLocked();
4010
Jeff Brownf086ddb2014-02-11 14:28:48 -08004011 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004013 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014}
4015
4016void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004017 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018 dumpDispatchStateLocked(dump);
4019
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004020 std::istringstream stream(dump);
4021 std::string line;
4022
4023 while (std::getline(stream, line, '\n')) {
4024 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025 }
4026}
4027
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004028void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004029 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4030 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4031 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004032 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033
Tiger Huang721e26f2018-07-24 22:26:19 +08004034 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4035 dump += StringPrintf(INDENT "FocusedApplications:\n");
4036 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4037 const int32_t displayId = it.first;
4038 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004039 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4040 ", name='%s', dispatchingTimeout=%0.3fms\n",
4041 displayId, applicationHandle->getName().c_str(),
4042 applicationHandle->getDispatchingTimeout(
4043 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
4044 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08004045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004047 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004049
4050 if (!mFocusedWindowHandlesByDisplay.empty()) {
4051 dump += StringPrintf(INDENT "FocusedWindows:\n");
4052 for (auto& it : mFocusedWindowHandlesByDisplay) {
4053 const int32_t displayId = it.first;
4054 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004055 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4056 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004057 }
4058 } else {
4059 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004062 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004063 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004064 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4065 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004066 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004067 state.displayId, toString(state.down), toString(state.split),
4068 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004069 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004070 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004071 for (size_t i = 0; i < state.windows.size(); i++) {
4072 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004073 dump += StringPrintf(INDENT4
4074 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4075 i, touchedWindow.windowHandle->getName().c_str(),
4076 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004077 }
4078 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004079 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004080 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004081 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004082 dump += INDENT3 "Portal windows:\n";
4083 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004084 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004085 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4086 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004087 }
4088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 }
4090 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004091 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 }
4093
Arthur Hungb92218b2018-08-14 12:00:21 +08004094 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004095 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004096 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004097 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004098 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004099 dump += INDENT2 "Windows:\n";
4100 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004101 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004102 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103
Arthur Hungb92218b2018-08-14 12:00:21 +08004104 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004105 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004106 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4107 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004108 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004109 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004110 i, windowInfo->name.c_str(), windowInfo->displayId,
4111 windowInfo->portalToDisplayId,
4112 toString(windowInfo->paused),
4113 toString(windowInfo->hasFocus),
4114 toString(windowInfo->hasWallpaper),
4115 toString(windowInfo->visible),
4116 toString(windowInfo->canReceiveKeys),
4117 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004118 windowInfo->layoutParamsType, windowInfo->frameLeft,
4119 windowInfo->frameTop, windowInfo->frameRight,
4120 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4121 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004122 dumpRegion(dump, windowInfo->touchableRegion);
4123 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
4124 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004125 windowInfo->ownerPid, windowInfo->ownerUid,
4126 windowInfo->dispatchingTimeout / 1000000.0);
Siarhei Vishniakou67d44502020-04-09 11:09:29 -07004127 dump += StringPrintf(INDENT4 " flags: %s\n",
4128 inputWindowFlagsToString(windowInfo->layoutParamsFlags)
4129 .c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004130 }
4131 } else {
4132 dump += INDENT2 "Windows: <none>\n";
4133 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 }
4135 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004136 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 }
4138
Michael Wright3dd60e22019-03-27 22:06:44 +00004139 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004140 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004141 const std::vector<Monitor>& monitors = it.second;
4142 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4143 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004144 }
4145 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004146 const std::vector<Monitor>& monitors = it.second;
4147 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4148 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004151 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152 }
4153
4154 nsecs_t currentTime = now();
4155
4156 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004157 if (!mRecentQueue.empty()) {
4158 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4159 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004160 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004162 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 }
4164 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004165 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 }
4167
4168 // Dump event currently being dispatched.
4169 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004170 dump += INDENT "PendingEvent:\n";
4171 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004173 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004174 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004176 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177 }
4178
4179 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004180 if (!mInboundQueue.empty()) {
4181 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4182 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004183 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004185 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 }
4187 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004188 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 }
4190
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004191 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004192 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004193 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4194 const KeyReplacement& replacement = pair.first;
4195 int32_t newKeyCode = pair.second;
4196 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004198 }
4199 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004200 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004201 }
4202
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004203 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004204 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004205 for (const auto& pair : mConnectionsByFd) {
4206 const sp<Connection>& connection = pair.second;
4207 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
4208 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
4209 pair.first, connection->getInputChannelName().c_str(),
4210 connection->getWindowName().c_str(), connection->getStatusLabel(),
4211 toString(connection->monitor),
4212 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004214 if (!connection->outboundQueue.empty()) {
4215 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4216 connection->outboundQueue.size());
4217 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 dump.append(INDENT4);
4219 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004220 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004221 entry->targetFlags, entry->resolvedAction,
4222 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 }
4224 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004225 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 }
4227
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004228 if (!connection->waitQueue.empty()) {
4229 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4230 connection->waitQueue.size());
4231 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004232 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004234 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004235 "age=%0.1fms, wait=%0.1fms\n",
4236 entry->targetFlags, entry->resolvedAction,
4237 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
4238 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239 }
4240 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004241 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242 }
4243 }
4244 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004245 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246 }
4247
4248 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004249 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004250 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004252 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 }
4254
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004255 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004256 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004257 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004258 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259}
4260
Michael Wright3dd60e22019-03-27 22:06:44 +00004261void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4262 const size_t numMonitors = monitors.size();
4263 for (size_t i = 0; i < numMonitors; i++) {
4264 const Monitor& monitor = monitors[i];
4265 const sp<InputChannel>& channel = monitor.inputChannel;
4266 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4267 dump += "\n";
4268 }
4269}
4270
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004271status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004273 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274#endif
4275
4276 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004277 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004278 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004279 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004281 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 return BAD_VALUE;
4283 }
4284
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004285 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286
4287 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004288 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004289 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4292 } // release lock
4293
4294 // Wake the looper because some connections have changed.
4295 mLooper->wake();
4296 return OK;
4297}
4298
Michael Wright3dd60e22019-03-27 22:06:44 +00004299status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004301 { // acquire lock
4302 std::scoped_lock _l(mLock);
4303
4304 if (displayId < 0) {
4305 ALOGW("Attempted to register input monitor without a specified display.");
4306 return BAD_VALUE;
4307 }
4308
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004309 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004310 ALOGW("Attempted to register input monitor without an identifying token.");
4311 return BAD_VALUE;
4312 }
4313
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004314 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004315
4316 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004317 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004318 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004319
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004320 auto& monitorsByDisplay =
4321 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004322 monitorsByDisplay[displayId].emplace_back(inputChannel);
4323
4324 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004325 }
4326 // Wake the looper because some connections have changed.
4327 mLooper->wake();
4328 return OK;
4329}
4330
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4332#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004333 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334#endif
4335
4336 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004337 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338
4339 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4340 if (status) {
4341 return status;
4342 }
4343 } // release lock
4344
4345 // Wake the poll loop because removing the connection may have changed the current
4346 // synchronization state.
4347 mLooper->wake();
4348 return OK;
4349}
4350
4351status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004352 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004353 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004354 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004356 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 return BAD_VALUE;
4358 }
4359
John Recke0710582019-09-26 13:46:12 -07004360 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004361 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004362 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004363
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 if (connection->monitor) {
4365 removeMonitorChannelLocked(inputChannel);
4366 }
4367
4368 mLooper->removeFd(inputChannel->getFd());
4369
4370 nsecs_t currentTime = now();
4371 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4372
4373 connection->status = Connection::STATUS_ZOMBIE;
4374 return OK;
4375}
4376
4377void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004378 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4379 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4380}
4381
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004382void InputDispatcher::removeMonitorChannelLocked(
4383 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004384 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004385 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004386 std::vector<Monitor>& monitors = it->second;
4387 const size_t numMonitors = monitors.size();
4388 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004389 if (monitors[i].inputChannel == inputChannel) {
4390 monitors.erase(monitors.begin() + i);
4391 break;
4392 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004393 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004394 if (monitors.empty()) {
4395 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004396 } else {
4397 ++it;
4398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399 }
4400}
4401
Michael Wright3dd60e22019-03-27 22:06:44 +00004402status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4403 { // acquire lock
4404 std::scoped_lock _l(mLock);
4405 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4406
4407 if (!foundDisplayId) {
4408 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4409 return BAD_VALUE;
4410 }
4411 int32_t displayId = foundDisplayId.value();
4412
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004413 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4414 mTouchStatesByDisplay.find(displayId);
4415 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004416 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4417 return BAD_VALUE;
4418 }
4419
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004420 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004421 std::optional<int32_t> foundDeviceId;
4422 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004423 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004424 foundDeviceId = state.deviceId;
4425 }
4426 }
4427 if (!foundDeviceId || !state.down) {
4428 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004429 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004430 return BAD_VALUE;
4431 }
4432 int32_t deviceId = foundDeviceId.value();
4433
4434 // Send cancel events to all the input channels we're stealing from.
4435 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004436 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004437 options.deviceId = deviceId;
4438 options.displayId = displayId;
4439 for (const TouchedWindow& window : state.windows) {
4440 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004441 if (channel != nullptr) {
4442 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4443 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004444 }
4445 // Then clear the current touch state so we stop dispatching to them as well.
4446 state.filterNonMonitors();
4447 }
4448 return OK;
4449}
4450
Michael Wright3dd60e22019-03-27 22:06:44 +00004451std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4452 const sp<IBinder>& token) {
4453 for (const auto& it : mGestureMonitorsByDisplay) {
4454 const std::vector<Monitor>& monitors = it.second;
4455 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004456 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004457 return it.first;
4458 }
4459 }
4460 }
4461 return std::nullopt;
4462}
4463
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004464sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4465 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004466 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004467 }
4468
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004469 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004470 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004471 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004472 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473 }
4474 }
Robert Carr4e670e52018-08-15 13:26:12 -07004475
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004476 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477}
4478
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004479void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4480 const sp<Connection>& connection, uint32_t seq,
4481 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004482 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4483 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 commandEntry->connection = connection;
4485 commandEntry->eventTime = currentTime;
4486 commandEntry->seq = seq;
4487 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004488 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489}
4490
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004491void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4492 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004494 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004496 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4497 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004499 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500}
4501
chaviw0c06c6e2019-01-09 13:27:07 -08004502void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004503 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004504 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4505 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004506 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4507 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004508 commandEntry->oldToken = oldToken;
4509 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004510 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004511}
4512
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004513void InputDispatcher::onANRLocked(nsecs_t currentTime,
4514 const sp<InputApplicationHandle>& applicationHandle,
4515 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4516 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4518 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4519 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004520 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4521 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4522 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523
4524 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004525 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526 struct tm tm;
4527 localtime_r(&t, &tm);
4528 char timestr[64];
4529 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4530 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004531 mLastANRState += INDENT "ANR:\n";
4532 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004533 mLastANRState +=
4534 StringPrintf(INDENT2 "Window: %s\n",
4535 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004536 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4537 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4538 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539 dumpDispatchStateLocked(mLastANRState);
4540
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004541 std::unique_ptr<CommandEntry> commandEntry =
4542 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004544 commandEntry->inputChannel =
4545 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004547 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548}
4549
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004550void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551 mLock.unlock();
4552
4553 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4554
4555 mLock.lock();
4556}
4557
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004558void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559 sp<Connection> connection = commandEntry->connection;
4560
4561 if (connection->status != Connection::STATUS_ZOMBIE) {
4562 mLock.unlock();
4563
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004564 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565
4566 mLock.lock();
4567 }
4568}
4569
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004570void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004571 sp<IBinder> oldToken = commandEntry->oldToken;
4572 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004573 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004574 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004575 mLock.lock();
4576}
4577
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004578void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004579 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004580 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 mLock.unlock();
4582
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004583 nsecs_t newTimeout =
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004584 mPolicy->notifyANR(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585
4586 mLock.lock();
4587
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004588 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589}
4590
4591void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4592 CommandEntry* commandEntry) {
4593 KeyEntry* entry = commandEntry->keyEntry;
4594
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004595 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596
4597 mLock.unlock();
4598
Michael Wright2b3c3302018-03-02 17:19:13 +00004599 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004600 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004601 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004602 : nullptr;
4603 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004604 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4605 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004606 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608
4609 mLock.lock();
4610
4611 if (delay < 0) {
4612 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4613 } else if (!delay) {
4614 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4615 } else {
4616 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4617 entry->interceptKeyWakeupTime = now() + delay;
4618 }
4619 entry->release();
4620}
4621
chaviwfd6d3512019-03-25 13:23:49 -07004622void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4623 mLock.unlock();
4624 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4625 mLock.lock();
4626}
4627
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004628void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004630 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004632 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633
4634 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004635 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004636 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004637 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004639 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004640
4641 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4642 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4643 std::string msg =
4644 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4645 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4646 dispatchEntry->eventEntry->appendDescription(msg);
4647 ALOGI("%s", msg.c_str());
4648 }
4649
4650 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004651 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004652 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4653 restartEvent =
4654 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004655 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004656 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4657 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4658 handled);
4659 } else {
4660 restartEvent = false;
4661 }
4662
4663 // Dequeue the event and start the next cycle.
4664 // Note that because the lock might have been released, it is possible that the
4665 // contents of the wait queue to have been drained, so we need to double-check
4666 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004667 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4668 if (dispatchEntryIt != connection->waitQueue.end()) {
4669 dispatchEntry = *dispatchEntryIt;
4670 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004671 traceWaitQueueLength(connection);
4672 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004673 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004674 traceOutboundQueueLength(connection);
4675 } else {
4676 releaseDispatchEntry(dispatchEntry);
4677 }
4678 }
4679
4680 // Start the next dispatch cycle for this connection.
4681 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682}
4683
4684bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004685 DispatchEntry* dispatchEntry,
4686 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004687 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004688 if (!handled) {
4689 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004690 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004691 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004692 return false;
4693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004695 // Get the fallback key state.
4696 // Clear it out after dispatching the UP.
4697 int32_t originalKeyCode = keyEntry->keyCode;
4698 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4699 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4700 connection->inputState.removeFallbackKey(originalKeyCode);
4701 }
4702
4703 if (handled || !dispatchEntry->hasForegroundTarget()) {
4704 // If the application handles the original key for which we previously
4705 // generated a fallback or if the window is not a foreground window,
4706 // then cancel the associated fallback key, if any.
4707 if (fallbackKeyCode != -1) {
4708 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004710 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004711 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4712 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4713 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004715 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004716 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717
4718 mLock.unlock();
4719
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004720 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004721 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722
4723 mLock.lock();
4724
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004725 // Cancel the fallback key.
4726 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004728 "application handled the original non-fallback key "
4729 "or is no longer a foreground target, "
4730 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 options.keyCode = fallbackKeyCode;
4732 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004734 connection->inputState.removeFallbackKey(originalKeyCode);
4735 }
4736 } else {
4737 // If the application did not handle a non-fallback key, first check
4738 // that we are in a good state to perform unhandled key event processing
4739 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004740 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004741 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004743 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004744 "since this is not an initial down. "
4745 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4746 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004748 return false;
4749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004751 // Dispatch the unhandled key to the policy.
4752#if DEBUG_OUTBOUND_EVENT_DETAILS
4753 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004754 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4755 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004756#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004757 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004758
4759 mLock.unlock();
4760
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004761 bool fallback =
4762 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4763 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004764
4765 mLock.lock();
4766
4767 if (connection->status != Connection::STATUS_NORMAL) {
4768 connection->inputState.removeFallbackKey(originalKeyCode);
4769 return false;
4770 }
4771
4772 // Latch the fallback keycode for this key on an initial down.
4773 // The fallback keycode cannot change at any other point in the lifecycle.
4774 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004776 fallbackKeyCode = event.getKeyCode();
4777 } else {
4778 fallbackKeyCode = AKEYCODE_UNKNOWN;
4779 }
4780 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4781 }
4782
4783 ALOG_ASSERT(fallbackKeyCode != -1);
4784
4785 // Cancel the fallback key if the policy decides not to send it anymore.
4786 // We will continue to dispatch the key to the policy but we will no
4787 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004788 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4789 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004790#if DEBUG_OUTBOUND_EVENT_DETAILS
4791 if (fallback) {
4792 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004793 "as a fallback for %d, but on the DOWN it had requested "
4794 "to send %d instead. Fallback canceled.",
4795 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004796 } else {
4797 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004798 "but on the DOWN it had requested to send %d. "
4799 "Fallback canceled.",
4800 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004801 }
4802#endif
4803
4804 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4805 "canceling fallback, policy no longer desires it");
4806 options.keyCode = fallbackKeyCode;
4807 synthesizeCancelationEventsForConnectionLocked(connection, options);
4808
4809 fallback = false;
4810 fallbackKeyCode = AKEYCODE_UNKNOWN;
4811 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004812 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004813 }
4814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815
4816#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004817 {
4818 std::string msg;
4819 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4820 connection->inputState.getFallbackKeys();
4821 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004822 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004824 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004825 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004826 }
4827#endif
4828
4829 if (fallback) {
4830 // Restart the dispatch cycle using the fallback key.
4831 keyEntry->eventTime = event.getEventTime();
4832 keyEntry->deviceId = event.getDeviceId();
4833 keyEntry->source = event.getSource();
4834 keyEntry->displayId = event.getDisplayId();
4835 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4836 keyEntry->keyCode = fallbackKeyCode;
4837 keyEntry->scanCode = event.getScanCode();
4838 keyEntry->metaState = event.getMetaState();
4839 keyEntry->repeatCount = event.getRepeatCount();
4840 keyEntry->downTime = event.getDownTime();
4841 keyEntry->syntheticRepeat = false;
4842
4843#if DEBUG_OUTBOUND_EVENT_DETAILS
4844 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004845 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4846 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004847#endif
4848 return true; // restart the event
4849 } else {
4850#if DEBUG_OUTBOUND_EVENT_DETAILS
4851 ALOGD("Unhandled key event: No fallback key.");
4852#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004853
4854 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004855 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004856 }
4857 }
4858 return false;
4859}
4860
4861bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004862 DispatchEntry* dispatchEntry,
4863 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 return false;
4865}
4866
4867void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4868 mLock.unlock();
4869
4870 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4871
4872 mLock.lock();
4873}
4874
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004875KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4876 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004877 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004878 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
4879 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004880 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881}
4882
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004883void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004884 int32_t injectionResult,
4885 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886 // TODO Write some statistics about how long we spend waiting.
4887}
4888
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004889/**
4890 * Report the touch event latency to the statsd server.
4891 * Input events are reported for statistics if:
4892 * - This is a touchscreen event
4893 * - InputFilter is not enabled
4894 * - Event is not injected or synthesized
4895 *
4896 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4897 * from getting aggregated with the "old" data.
4898 */
4899void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4900 REQUIRES(mLock) {
4901 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4902 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4903 if (!reportForStatistics) {
4904 return;
4905 }
4906
4907 if (mTouchStatistics.shouldReport()) {
4908 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4909 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4910 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4911 mTouchStatistics.reset();
4912 }
4913 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4914 mTouchStatistics.addValue(latencyMicros);
4915}
4916
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917void InputDispatcher::traceInboundQueueLengthLocked() {
4918 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004919 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920 }
4921}
4922
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004923void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 if (ATRACE_ENABLED()) {
4925 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004926 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004927 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 }
4929}
4930
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004931void InputDispatcher::traceWaitQueueLength(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), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004935 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936 }
4937}
4938
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004939void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004940 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004942 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943 dumpDispatchStateLocked(dump);
4944
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004945 if (!mLastANRState.empty()) {
4946 dump += "\nInput Dispatcher State at time of last ANR:\n";
4947 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948 }
4949}
4950
4951void InputDispatcher::monitor() {
4952 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004953 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004954 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004955 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956}
4957
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004958/**
4959 * Wake up the dispatcher and wait until it processes all events and commands.
4960 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4961 * this method can be safely called from any thread, as long as you've ensured that
4962 * the work you are interested in completing has already been queued.
4963 */
4964bool InputDispatcher::waitForIdle() {
4965 /**
4966 * Timeout should represent the longest possible time that a device might spend processing
4967 * events and commands.
4968 */
4969 constexpr std::chrono::duration TIMEOUT = 100ms;
4970 std::unique_lock lock(mLock);
4971 mLooper->wake();
4972 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4973 return result == std::cv_status::no_timeout;
4974}
4975
Garfield Tane84e6f92019-08-29 17:28:41 -07004976} // namespace android::inputdispatcher