blob: 46f6f446125ee387c64906280efb2bb104439bba [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Garfield Tane84e6f92019-08-29 17:28:41 -070048#include "Connection.h"
49
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <errno.h>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080051#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <limits.h>
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -050053#include <statslog.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080055#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056#include <unistd.h>
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -070057#include <queue>
58#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070059
Michael Wright2b3c3302018-03-02 17:19:13 +000060#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070062#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080063#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <log/log.h>
Gang Wang342c9272020-01-13 13:15:04 -050065#include <openssl/hmac.h>
66#include <openssl/rand.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070067#include <powermanager/PowerManager.h>
68#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080069
70#define INDENT " "
71#define INDENT2 " "
72#define INDENT3 " "
73#define INDENT4 " "
74
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080075using android::base::StringPrintf;
76
Garfield Tane84e6f92019-08-29 17:28:41 -070077namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
79// Default input dispatching timeout if there is no focused application or paused window
80// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -070081constexpr std::chrono::nanoseconds DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5s;
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Amount of time to allow for all pending events to be processed when an app switch
84// key is on the way. This is used to preempt input dispatch and drop input events
85// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000086constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow for an event to be dispatched (measured since its eventTime)
89// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92// Amount of time to allow touch events to be streamed out to a connection before requiring
93// that the first event be finished. This value extends the ANR timeout by the specified
94// amount. For example, if streaming is allowed to get ahead by one second relative to the
95// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000096constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
98// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000099constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
100
101// Log a warning when an interception call takes longer than this to process.
102constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
104// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107static inline nsecs_t now() {
108 return systemTime(SYSTEM_TIME_MONOTONIC);
109}
110
111static inline const char* toString(bool value) {
112 return value ? "true" : "false";
113}
114
115static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700116 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
117 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118}
119
120static bool isValidKeyAction(int32_t action) {
121 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700122 case AKEY_EVENT_ACTION_DOWN:
123 case AKEY_EVENT_ACTION_UP:
124 return true;
125 default:
126 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127 }
128}
129
130static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 ALOGE("Key event has invalid action code 0x%x", action);
133 return false;
134 }
135 return true;
136}
137
Michael Wright7b159c92015-05-14 14:48:03 +0100138static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 case AMOTION_EVENT_ACTION_DOWN:
141 case AMOTION_EVENT_ACTION_UP:
142 case AMOTION_EVENT_ACTION_CANCEL:
143 case AMOTION_EVENT_ACTION_MOVE:
144 case AMOTION_EVENT_ACTION_OUTSIDE:
145 case AMOTION_EVENT_ACTION_HOVER_ENTER:
146 case AMOTION_EVENT_ACTION_HOVER_MOVE:
147 case AMOTION_EVENT_ACTION_HOVER_EXIT:
148 case AMOTION_EVENT_ACTION_SCROLL:
149 return true;
150 case AMOTION_EVENT_ACTION_POINTER_DOWN:
151 case AMOTION_EVENT_ACTION_POINTER_UP: {
152 int32_t index = getMotionEventActionPointerIndex(action);
153 return index >= 0 && index < pointerCount;
154 }
155 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
156 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
157 return actionButton != 0;
158 default:
159 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160 }
161}
162
Michael Wright7b159c92015-05-14 14:48:03 +0100163static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 const PointerProperties* pointerProperties) {
165 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 ALOGE("Motion event has invalid action code 0x%x", action);
167 return false;
168 }
169 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000170 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700171 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 return false;
173 }
174 BitSet32 pointerIdBits;
175 for (size_t i = 0; i < pointerCount; i++) {
176 int32_t id = pointerProperties[i].id;
177 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
179 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 return false;
181 }
182 if (pointerIdBits.hasBit(id)) {
183 ALOGE("Motion event has duplicate pointer id %d", id);
184 return false;
185 }
186 pointerIdBits.markBit(id);
187 }
188 return true;
189}
190
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800191static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800193 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 return;
195 }
196
197 bool first = true;
198 Region::const_iterator cur = region.begin();
199 Region::const_iterator const tail = region.end();
200 while (cur != tail) {
201 if (first) {
202 first = false;
203 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800204 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800206 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 cur++;
208 }
209}
210
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700211/**
212 * Find the entry in std::unordered_map by key, and return it.
213 * If the entry is not found, return a default constructed entry.
214 *
215 * Useful when the entries are vectors, since an empty vector will be returned
216 * if the entry is not found.
217 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
218 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700219template <typename K, typename V>
220static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700221 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700222 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800223}
224
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700225/**
226 * Find the entry in std::unordered_map by value, and remove it.
227 * If more than one entry has the same value, then all matching
228 * key-value pairs will be removed.
229 *
230 * Return true if at least one value has been removed.
231 */
232template <typename K, typename V>
233static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
234 bool removed = false;
235 for (auto it = map.begin(); it != map.end();) {
236 if (it->second == value) {
237 it = map.erase(it);
238 removed = true;
239 } else {
240 it++;
241 }
242 }
243 return removed;
244}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245
chaviwaf87b3e2019-10-01 16:59:28 -0700246static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
247 if (first == second) {
248 return true;
249 }
250
251 if (first == nullptr || second == nullptr) {
252 return false;
253 }
254
255 return first->getToken() == second->getToken();
256}
257
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800258static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
259 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
260}
261
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000262static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
263 EventEntry* eventEntry,
264 int32_t inputTargetFlags) {
265 if (inputTarget.useDefaultPointerInfo()) {
266 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
267 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
268 inputTargetFlags, pointerInfo.xOffset,
269 pointerInfo.yOffset, inputTarget.globalScaleFactor,
270 pointerInfo.windowXScale, pointerInfo.windowYScale);
271 }
272
273 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
274 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
275
276 PointerCoords pointerCoords[motionEntry.pointerCount];
277
278 // Use the first pointer information to normalize all other pointers. This could be any pointer
279 // as long as all other pointers are normalized to the same value and the final DispatchEntry
280 // uses the offset and scale for the normalized pointer.
281 const PointerInfo& firstPointerInfo =
282 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
283
284 // Iterate through all pointers in the event to normalize against the first.
285 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
286 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
287 uint32_t pointerId = uint32_t(pointerProperties.id);
288 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
289
290 // The scale factor is the ratio of the current pointers scale to the normalized scale.
291 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
292 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
293
294 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
295 // First apply the current pointers offset to set the window at 0,0
296 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
297 // Next scale the coordinates.
298 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
299 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
300 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
301 -firstPointerInfo.yOffset);
302 }
303
304 MotionEntry* combinedMotionEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800305 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000306 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
307 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
308 motionEntry.metaState, motionEntry.buttonState,
309 motionEntry.classification, motionEntry.edgeFlags,
310 motionEntry.xPrecision, motionEntry.yPrecision,
311 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
312 motionEntry.downTime, motionEntry.pointerCount,
313 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
314 0 /* yOffset */);
315
316 if (motionEntry.injectionState) {
317 combinedMotionEntry->injectionState = motionEntry.injectionState;
318 combinedMotionEntry->injectionState->refCount += 1;
319 }
320
321 std::unique_ptr<DispatchEntry> dispatchEntry =
322 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
323 inputTargetFlags, firstPointerInfo.xOffset,
324 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
325 firstPointerInfo.windowXScale,
326 firstPointerInfo.windowYScale);
327 combinedMotionEntry->release();
328 return dispatchEntry;
329}
330
Siarhei Vishniakoue0fb6bd2020-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 }
Gang Wang342c9272020-01-13 13:15:04 -0500367 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700368 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500369}
370
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700371std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500372 // SHA256 always generates 32-bytes result
373 std::array<uint8_t, 32> hash;
374 unsigned int hashLen = 0;
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700375 uint8_t* result =
376 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500377 if (result == nullptr) {
378 ALOGE("Could not sign the data using HMAC");
379 return INVALID_HMAC;
380 }
381
382 if (hashLen != hash.size()) {
383 ALOGE("HMAC-SHA256 has unexpected length");
384 return INVALID_HMAC;
385 }
386
387 return hash;
388}
389
Michael Wrightd02c5b62014-02-10 15:10:22 -0800390// --- InputDispatcher ---
391
Garfield Tan00f511d2019-06-12 16:55:40 -0700392InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
393 : mPolicy(policy),
394 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700395 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tan1c7bc862020-01-28 13:24:04 -0800396 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700397 mAppSwitchSawKeyDown(false),
398 mAppSwitchDueTime(LONG_LONG_MAX),
399 mNextUnblockedEvent(nullptr),
400 mDispatchEnabled(false),
401 mDispatchFrozen(false),
402 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800403 // mInTouchMode will be initialized by the WindowManager to the default device config.
404 // To avoid leaking stack in case that call never comes, and for tests,
405 // initialize it here anyways.
406 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700407 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
408 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800410 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411
Yi Kong9b14ac62018-07-17 13:48:38 -0700412 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413
414 policy->getDispatcherConfiguration(&mConfig);
415}
416
417InputDispatcher::~InputDispatcher() {
418 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800419 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800420
421 resetKeyRepeatLocked();
422 releasePendingEventLocked();
423 drainInboundQueueLocked();
424 }
425
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700426 while (!mConnectionsByFd.empty()) {
427 sp<Connection> connection = mConnectionsByFd.begin()->second;
428 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800429 }
430}
431
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700432status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700433 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700434 return ALREADY_EXISTS;
435 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700436 mThread = std::make_unique<InputThread>(
437 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
438 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700439}
440
441status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700442 if (mThread && mThread->isCallingThread()) {
443 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700444 return INVALID_OPERATION;
445 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700446 mThread.reset();
447 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700448}
449
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450void InputDispatcher::dispatchOnce() {
451 nsecs_t nextWakeupTime = LONG_LONG_MAX;
452 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800453 std::scoped_lock _l(mLock);
454 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455
456 // Run a dispatch loop if there are no pending commands.
457 // The dispatch loop might enqueue commands to run afterwards.
458 if (!haveCommandsLocked()) {
459 dispatchOnceInnerLocked(&nextWakeupTime);
460 }
461
462 // Run all pending commands if there are any.
463 // If any commands were run then force the next poll to wake up immediately.
464 if (runCommandsLockedInterruptible()) {
465 nextWakeupTime = LONG_LONG_MIN;
466 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800467
468 // We are about to enter an infinitely long sleep, because we have no commands or
469 // pending or queued events
470 if (nextWakeupTime == LONG_LONG_MAX) {
471 mDispatcherEnteredIdle.notify_all();
472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800473 } // release lock
474
475 // Wait for callback or timeout or wake. (make sure we round up, not down)
476 nsecs_t currentTime = now();
477 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
478 mLooper->pollOnce(timeoutMillis);
479}
480
481void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
482 nsecs_t currentTime = now();
483
Jeff Browndc5992e2014-04-11 01:27:26 -0700484 // Reset the key repeat timer whenever normal dispatch is suspended while the
485 // device is in a non-interactive state. This is to ensure that we abort a key
486 // repeat if the device is just coming out of sleep.
487 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488 resetKeyRepeatLocked();
489 }
490
491 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
492 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100493 if (DEBUG_FOCUS) {
494 ALOGD("Dispatch frozen. Waiting some more.");
495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496 return;
497 }
498
499 // Optimize latency of app switches.
500 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
501 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
502 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
503 if (mAppSwitchDueTime < *nextWakeupTime) {
504 *nextWakeupTime = mAppSwitchDueTime;
505 }
506
507 // Ready to start a new event.
508 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700509 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700510 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 if (isAppSwitchDue) {
512 // The inbound queue is empty so the app switch key we were waiting
513 // for will never arrive. Stop waiting for it.
514 resetPendingAppSwitchLocked(false);
515 isAppSwitchDue = false;
516 }
517
518 // Synthesize a key repeat if appropriate.
519 if (mKeyRepeatState.lastKeyEntry) {
520 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
521 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
522 } else {
523 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
524 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
525 }
526 }
527 }
528
529 // Nothing to do if there is no pending event.
530 if (!mPendingEvent) {
531 return;
532 }
533 } else {
534 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700535 mPendingEvent = mInboundQueue.front();
536 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537 traceInboundQueueLengthLocked();
538 }
539
540 // Poke user activity for this event.
541 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700542 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 }
544
545 // Get ready to dispatch the event.
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700546 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547 }
548
549 // Now we have an event to dispatch.
550 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700551 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700553 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700555 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700557 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 }
559
560 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700561 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 }
563
564 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700565 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700566 ConfigurationChangedEntry* typedEntry =
567 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
568 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700569 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700570 break;
571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700573 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700574 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
575 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700576 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700577 break;
578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100580 case EventEntry::Type::FOCUS: {
581 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
582 dispatchFocusLocked(currentTime, typedEntry);
583 done = true;
584 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
585 break;
586 }
587
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700588 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700589 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
590 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700591 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700592 resetPendingAppSwitchLocked(true);
593 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700594 } else if (dropReason == DropReason::NOT_DROPPED) {
595 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700596 }
597 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700598 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700599 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700600 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700601 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
602 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700603 }
604 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
605 break;
606 }
607
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700608 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700609 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700610 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
611 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700613 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700614 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700615 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700616 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
617 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700618 }
619 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
620 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 }
623
624 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700625 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700626 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 }
Michael Wright3a981722015-06-10 15:26:13 +0100628 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629
630 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700631 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 }
633}
634
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700635/**
636 * Return true if the events preceding this incoming motion event should be dropped
637 * Return false otherwise (the default behaviour)
638 */
639bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
640 bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
641 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
642 if (isPointerDownEvent &&
643 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
644 mInputTargetWaitApplicationToken != nullptr) {
645 int32_t displayId = motionEntry.displayId;
646 int32_t x = static_cast<int32_t>(
647 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
648 int32_t y = static_cast<int32_t>(
649 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700650 sp<InputWindowHandle> touchedWindowHandle =
651 findTouchedWindowAtLocked(displayId, x, y, nullptr);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700652 if (touchedWindowHandle != nullptr &&
653 touchedWindowHandle->getApplicationToken() != mInputTargetWaitApplicationToken) {
654 // User touched a different application than the one we are waiting on.
655 // Flag the event, and start pruning the input queue.
656 ALOGI("Pruning input queue because user touched a different application");
657 return true;
658 }
659 }
660 return false;
661}
662
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700664 bool needWake = mInboundQueue.empty();
665 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666 traceInboundQueueLengthLocked();
667
668 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700669 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700670 // Optimize app switch latency.
671 // If the application takes too long to catch up then we drop all events preceding
672 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700673 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700674 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700675 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700676 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700677 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700678 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700682 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700683 mAppSwitchSawKeyDown = false;
684 needWake = true;
685 }
686 }
687 }
688 break;
689 }
690
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700691 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700692 // Optimize case where the current application is unresponsive and the user
693 // decides to touch a window in a different application.
694 // If the application takes too long to catch up then we drop all events preceding
695 // the touch into the other window.
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700696 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
697 mNextUnblockedEvent = entry;
698 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700700 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100702 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700703 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
704 break;
705 }
706 case EventEntry::Type::CONFIGURATION_CHANGED:
707 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700708 // nothing to do
709 break;
710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711 }
712
713 return needWake;
714}
715
716void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
717 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700718 mRecentQueue.push_back(entry);
719 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
720 mRecentQueue.front()->release();
721 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722 }
723}
724
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700725sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700726 int32_t y, TouchState* touchState,
727 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700728 bool addPortalWindows) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700729 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
730 LOG_ALWAYS_FATAL(
731 "Must provide a valid touch state if adding portal windows or outside targets");
732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800734 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
735 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736 const InputWindowInfo* windowInfo = windowHandle->getInfo();
737 if (windowInfo->displayId == displayId) {
738 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739
740 if (windowInfo->visible) {
741 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700742 bool isTouchModal = (flags &
743 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
744 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800746 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700747 if (portalToDisplayId != ADISPLAY_ID_NONE &&
748 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800749 if (addPortalWindows) {
750 // For the monitoring channels of the display.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700751 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800752 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700753 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700754 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 // Found window.
757 return windowHandle;
758 }
759 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800760
761 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700762 touchState->addOrUpdateWindow(windowHandle,
763 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
764 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767 }
768 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700769 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770}
771
Garfield Tane84e6f92019-08-29 17:28:41 -0700772std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -0700773 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000774 std::vector<TouchedMonitor> touchedMonitors;
775
776 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
777 addGestureMonitors(monitors, touchedMonitors);
778 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
779 const InputWindowInfo* windowInfo = portalWindow->getInfo();
780 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700781 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
782 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000783 }
784 return touchedMonitors;
785}
786
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700787void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 const char* reason;
789 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700790 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700792 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700794 reason = "inbound event was dropped because the policy consumed it";
795 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700796 case DropReason::DISABLED:
797 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700798 ALOGI("Dropped event because input dispatch is disabled.");
799 }
800 reason = "inbound event was dropped because input dispatch is disabled";
801 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700802 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700803 ALOGI("Dropped event because of pending overdue app switch.");
804 reason = "inbound event was dropped because of pending overdue app switch";
805 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700806 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700807 ALOGI("Dropped event because the current application is not responding and the user "
808 "has started interacting with a different application.");
809 reason = "inbound event was dropped because the current application is not responding "
810 "and the user has started interacting with a different application";
811 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700812 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700813 ALOGI("Dropped event because it is stale.");
814 reason = "inbound event was dropped because it is stale";
815 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700816 case DropReason::NOT_DROPPED: {
817 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700818 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820 }
821
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700822 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700823 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
825 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700826 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700828 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700829 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
830 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700831 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
832 synthesizeCancelationEventsForAllConnectionsLocked(options);
833 } else {
834 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
835 synthesizeCancelationEventsForAllConnectionsLocked(options);
836 }
837 break;
838 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100839 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700840 case EventEntry::Type::CONFIGURATION_CHANGED:
841 case EventEntry::Type::DEVICE_RESET: {
842 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
843 break;
844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 }
846}
847
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800848static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700849 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
850 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851}
852
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700853bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
854 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
855 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
856 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857}
858
859bool InputDispatcher::isAppSwitchPendingLocked() {
860 return mAppSwitchDueTime != LONG_LONG_MAX;
861}
862
863void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
864 mAppSwitchDueTime = LONG_LONG_MAX;
865
866#if DEBUG_APP_SWITCH
867 if (handled) {
868 ALOGD("App switch has arrived.");
869 } else {
870 ALOGD("App switch was abandoned.");
871 }
872#endif
873}
874
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700876 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877}
878
879bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700880 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 return false;
882 }
883
884 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700885 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700886 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700888 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889
890 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700891 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 return true;
893}
894
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700895void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
896 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897}
898
899void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700900 while (!mInboundQueue.empty()) {
901 EventEntry* entry = mInboundQueue.front();
902 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903 releaseInboundEventLocked(entry);
904 }
905 traceInboundQueueLengthLocked();
906}
907
908void InputDispatcher::releasePendingEventLocked() {
909 if (mPendingEvent) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700910 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700912 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913 }
914}
915
916void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
917 InjectionState* injectionState = entry->injectionState;
918 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
919#if DEBUG_DISPATCH_CYCLE
920 ALOGD("Injected inbound event was dropped.");
921#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800922 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 }
924 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700925 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 }
927 addRecentEventLocked(entry);
928 entry->release();
929}
930
931void InputDispatcher::resetKeyRepeatLocked() {
932 if (mKeyRepeatState.lastKeyEntry) {
933 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700934 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 }
936}
937
Garfield Tane84e6f92019-08-29 17:28:41 -0700938KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
940
941 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700942 uint32_t policyFlags = entry->policyFlags &
943 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944 if (entry->refCount == 1) {
945 entry->recycle();
Garfield Tan1c7bc862020-01-28 13:24:04 -0800946 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 entry->eventTime = currentTime;
948 entry->policyFlags = policyFlags;
949 entry->repeatCount += 1;
950 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700951 KeyEntry* newEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -0800952 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800953 entry->displayId, policyFlags, entry->action, entry->flags,
954 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700955 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956
957 mKeyRepeatState.lastKeyEntry = newEntry;
958 entry->release();
959
960 entry = newEntry;
961 }
962 entry->syntheticRepeat = true;
963
964 // Increment reference count since we keep a reference to the event in
965 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
966 entry->refCount += 1;
967
968 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
969 return entry;
970}
971
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700972bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
973 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700975 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976#endif
977
978 // Reset key repeating in case a keyboard device was added or removed or something.
979 resetKeyRepeatLocked();
980
981 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700982 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
983 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700985 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 return true;
987}
988
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700991 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700992 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993#endif
994
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700995 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 options.deviceId = entry->deviceId;
997 synthesizeCancelationEventsForAllConnectionsLocked(options);
998 return true;
999}
1000
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001001void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07001002 if (mPendingEvent != nullptr) {
1003 // Move the pending event to the front of the queue. This will give the chance
1004 // for the pending event to get dispatched to the newly focused window
1005 mInboundQueue.push_front(mPendingEvent);
1006 mPendingEvent = nullptr;
1007 }
1008
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001009 FocusEntry* focusEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08001010 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07001011
1012 // This event should go to the front of the queue, but behind all other focus events
1013 // Find the last focus event, and insert right after it
1014 std::deque<EventEntry*>::reverse_iterator it =
1015 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1016 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1017
1018 // Maintain the order of focus events. Insert the entry after all other focus events.
1019 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001020}
1021
1022void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1023 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1024 if (channel == nullptr) {
1025 return; // Window has gone away
1026 }
1027 InputTarget target;
1028 target.inputChannel = channel;
1029 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1030 entry->dispatchInProgress = true;
1031
1032 dispatchEventLocked(currentTime, entry, {target});
1033}
1034
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001036 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001038 if (!entry->dispatchInProgress) {
1039 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1040 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1041 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1042 if (mKeyRepeatState.lastKeyEntry &&
1043 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 // We have seen two identical key downs in a row which indicates that the device
1045 // driver is automatically generating key repeats itself. We take note of the
1046 // repeat here, but we disable our own next key repeat timer since it is clear that
1047 // we will not need to synthesize key repeats ourselves.
1048 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1049 resetKeyRepeatLocked();
1050 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1051 } else {
1052 // Not a repeat. Save key down state in case we do see a repeat later.
1053 resetKeyRepeatLocked();
1054 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1055 }
1056 mKeyRepeatState.lastKeyEntry = entry;
1057 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001058 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 resetKeyRepeatLocked();
1060 }
1061
1062 if (entry->repeatCount == 1) {
1063 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1064 } else {
1065 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1066 }
1067
1068 entry->dispatchInProgress = true;
1069
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001070 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 }
1072
1073 // Handle case where the policy asked us to try again later last time.
1074 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1075 if (currentTime < entry->interceptKeyWakeupTime) {
1076 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1077 *nextWakeupTime = entry->interceptKeyWakeupTime;
1078 }
1079 return false; // wait until next wakeup
1080 }
1081 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1082 entry->interceptKeyWakeupTime = 0;
1083 }
1084
1085 // Give the policy a chance to intercept the key.
1086 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1087 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001088 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001089 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001090 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001091 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001092 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 }
1095 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001096 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 entry->refCount += 1;
1098 return false; // wait for the command to run
1099 } else {
1100 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1101 }
1102 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 if (*dropReason == DropReason::NOT_DROPPED) {
1104 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105 }
1106 }
1107
1108 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001109 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001110 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001111 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001112 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001113 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114 return true;
1115 }
1116
1117 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001118 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001119 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001120 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1122 return false;
1123 }
1124
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001125 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1127 return true;
1128 }
1129
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001130 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001131 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132
1133 // Dispatch the key.
1134 dispatchEventLocked(currentTime, entry, inputTargets);
1135 return true;
1136}
1137
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001138void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001140 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001141 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1142 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001143 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1144 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1145 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146#endif
1147}
1148
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001149bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1150 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001151 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001153 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 entry->dispatchInProgress = true;
1155
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001156 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 }
1158
1159 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001160 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001161 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001162 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001163 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 return true;
1165 }
1166
1167 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1168
1169 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001170 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171
1172 bool conflictingPointerActions = false;
1173 int32_t injectionResult;
1174 if (isPointerEvent) {
1175 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001176 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001177 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001178 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 } else {
1180 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001181 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001182 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 }
1184 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1185 return false;
1186 }
1187
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001188 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001189 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1190 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1191 return true;
1192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001194 CancelationOptions::Mode mode(isPointerEvent
1195 ? CancelationOptions::CANCEL_POINTER_EVENTS
1196 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1197 CancelationOptions options(mode, "input event injection failed");
1198 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 return true;
1200 }
1201
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001202 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001203 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001205 if (isPointerEvent) {
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001206 std::unordered_map<int32_t, TouchState>::iterator it =
1207 mTouchStatesByDisplay.find(entry->displayId);
1208 if (it != mTouchStatesByDisplay.end()) {
1209 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001210 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001211 // The event has gone through these portal windows, so we add monitoring targets of
1212 // the corresponding displays as well.
1213 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001214 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001215 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001216 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001217 }
1218 }
1219 }
1220 }
1221
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 // Dispatch the motion.
1223 if (conflictingPointerActions) {
1224 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001225 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 synthesizeCancelationEventsForAllConnectionsLocked(options);
1227 }
1228 dispatchEventLocked(currentTime, entry, inputTargets);
1229 return true;
1230}
1231
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001232void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001234 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001235 ", policyFlags=0x%x, "
1236 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1237 "metaState=0x%x, buttonState=0x%x,"
1238 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001239 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1240 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1241 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001243 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001245 "x=%f, y=%f, pressure=%f, size=%f, "
1246 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1247 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001248 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1249 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1250 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1251 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1252 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1253 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1254 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1255 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1256 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1257 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 }
1259#endif
1260}
1261
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001262void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1263 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001264 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265#if DEBUG_DISPATCH_CYCLE
1266 ALOGD("dispatchEventToCurrentInputTargets");
1267#endif
1268
1269 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1270
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001271 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001273 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001274 sp<Connection> connection =
1275 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001276 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001277 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001279 if (DEBUG_FOCUS) {
1280 ALOGD("Dropping event delivery to target with channel '%s' because it "
1281 "is no longer registered with the input dispatcher.",
1282 inputTarget.inputChannel->getName().c_str());
1283 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 }
1285 }
1286}
1287
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001288int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001289 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001291 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001292 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001294 if (DEBUG_FOCUS) {
1295 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1298 mInputTargetWaitStartTime = currentTime;
1299 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1300 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001301 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 }
1303 } else {
1304 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001305 ALOGI("Waiting for application to become ready for input: %s. Reason: %s",
1306 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1307 std::chrono::nanoseconds timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001308 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001310 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001311 timeout =
1312 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 } else {
1314 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1315 }
1316
1317 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1318 mInputTargetWaitStartTime = currentTime;
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001319 mInputTargetWaitTimeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001321 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322
Yi Kong9b14ac62018-07-17 13:48:38 -07001323 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001324 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 }
Robert Carr740167f2018-10-11 19:03:41 -07001326 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1327 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 }
1329 }
1330 }
1331
1332 if (mInputTargetWaitTimeoutExpired) {
1333 return INPUT_EVENT_INJECTION_TIMED_OUT;
1334 }
1335
1336 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001337 onAnrLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001338 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339
1340 // Force poll loop to wake up immediately on next iteration once we get the
1341 // ANR response back from the policy.
1342 *nextWakeupTime = LONG_LONG_MIN;
1343 return INPUT_EVENT_INJECTION_PENDING;
1344 } else {
1345 // Force poll loop to wake up when timeout is due.
1346 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1347 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1348 }
1349 return INPUT_EVENT_INJECTION_PENDING;
1350 }
1351}
1352
Robert Carr803535b2018-08-02 16:38:15 -07001353void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001354 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
1355 TouchState& state = pair.second;
Robert Carr803535b2018-08-02 16:38:15 -07001356 state.removeWindowByToken(token);
1357 }
1358}
1359
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001360void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001361 nsecs_t timeoutExtension, const sp<IBinder>& inputConnectionToken) {
1362 if (timeoutExtension > 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 // Extend the timeout.
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001364 mInputTargetWaitTimeoutTime = now() + timeoutExtension;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 } else {
1366 // Give up.
1367 mInputTargetWaitTimeoutExpired = true;
1368
1369 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001370 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001371 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001372 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001374 if (connection->status == Connection::STATUS_NORMAL) {
1375 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1376 "application not responding");
1377 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 }
1379 }
1380 }
1381}
1382
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001383void InputDispatcher::resetAnrTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001384 if (DEBUG_FOCUS) {
1385 ALOGD("Resetting ANR timeouts.");
1386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387
1388 // Reset input target wait timeout.
1389 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001390 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391}
1392
Tiger Huang721e26f2018-07-24 22:26:19 +08001393/**
1394 * Get the display id that the given event should go to. If this event specifies a valid display id,
1395 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1396 * Focused display is the display that the user most recently interacted with.
1397 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001399 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001401 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001402 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1403 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001404 break;
1405 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001406 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001407 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1408 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001409 break;
1410 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001411 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001412 case EventEntry::Type::CONFIGURATION_CHANGED:
1413 case EventEntry::Type::DEVICE_RESET: {
1414 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001415 return ADISPLAY_ID_NONE;
1416 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001417 }
1418 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1419}
1420
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001422 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001423 std::vector<InputTarget>& inputTargets,
1424 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001425 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426
Tiger Huang721e26f2018-07-24 22:26:19 +08001427 int32_t displayId = getTargetDisplayId(entry);
1428 sp<InputWindowHandle> focusedWindowHandle =
1429 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1430 sp<InputApplicationHandle> focusedApplicationHandle =
1431 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1432
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433 // If there is no currently focused window and no focused application
1434 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001435 if (focusedWindowHandle == nullptr) {
1436 if (focusedApplicationHandle != nullptr) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001437 return handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1438 nullptr, nextWakeupTime,
1439 "Waiting because no window has focus but there is "
1440 "a focused application that may eventually add a "
1441 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 }
1443
Arthur Hung3b413f22018-10-26 18:05:34 +08001444 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001445 "%" PRId32 ".",
1446 displayId);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001447 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 }
1449
1450 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001451 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001452 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 }
1454
Jeff Brownffb49772014-10-10 19:01:34 -07001455 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001456 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001457 if (!reason.empty()) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001458 return handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1459 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 }
1461
1462 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001463 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001464 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1465 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466
1467 // Done.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001468 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469}
1470
1471int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001472 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001473 std::vector<InputTarget>& inputTargets,
1474 nsecs_t* nextWakeupTime,
1475 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001476 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477 enum InjectionPermission {
1478 INJECTION_PERMISSION_UNKNOWN,
1479 INJECTION_PERMISSION_GRANTED,
1480 INJECTION_PERMISSION_DENIED
1481 };
1482
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 // For security reasons, we defer updating the touch state until we are sure that
1484 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001485 int32_t displayId = entry.displayId;
1486 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1488
1489 // Update the touch state as needed based on the properties of the touch event.
1490 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1491 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1492 sp<InputWindowHandle> newHoverWindowHandle;
1493
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001494 // Copy current touch state into tempTouchState.
1495 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1496 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001497 const TouchState* oldState = nullptr;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001498 TouchState tempTouchState;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001499 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1500 mTouchStatesByDisplay.find(displayId);
1501 if (oldStateIt != mTouchStatesByDisplay.end()) {
1502 oldState = &(oldStateIt->second);
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001503 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001504 }
1505
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001506 bool isSplit = tempTouchState.split;
1507 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1508 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1509 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001510 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1511 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1512 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1513 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1514 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001515 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 bool wrongDevice = false;
1517 if (newGesture) {
1518 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001519 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001520 ALOGI("Dropping event because a pointer for a different device is already down "
1521 "in display %" PRId32,
1522 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001523 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1525 switchedDevice = false;
1526 wrongDevice = true;
1527 goto Failed;
1528 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001529 tempTouchState.reset();
1530 tempTouchState.down = down;
1531 tempTouchState.deviceId = entry.deviceId;
1532 tempTouchState.source = entry.source;
1533 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001535 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001536 ALOGI("Dropping move event because a pointer for a different device is already active "
1537 "in display %" PRId32,
1538 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001539 // TODO: test multiple simultaneous input streams.
1540 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1541 switchedDevice = false;
1542 wrongDevice = true;
1543 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 }
1545
1546 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1547 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1548
Garfield Tan00f511d2019-06-12 16:55:40 -07001549 int32_t x;
1550 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001552 // Always dispatch mouse events to cursor position.
1553 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001554 x = int32_t(entry.xCursorPosition);
1555 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001556 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001557 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1558 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001559 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001560 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001561 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001562 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1563 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001564
1565 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001566 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001567 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001570 if (newTouchedWindowHandle != nullptr &&
1571 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001572 // New window supports splitting, but we should never split mouse events.
1573 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 } else if (isSplit) {
1575 // New window does not support splitting but we have already split events.
1576 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001577 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 }
1579
1580 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001581 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001583 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001584 }
1585
1586 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1587 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001588 "(%d, %d) in display %" PRId32 ".",
1589 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001590 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1591 goto Failed;
1592 }
1593
1594 if (newTouchedWindowHandle != nullptr) {
1595 // Set target flags.
1596 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1597 if (isSplit) {
1598 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001600 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1601 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1602 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1603 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1604 }
1605
1606 // Update hover state.
1607 if (isHoverAction) {
1608 newHoverWindowHandle = newTouchedWindowHandle;
1609 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1610 newHoverWindowHandle = mLastHoverWindowHandle;
1611 }
1612
1613 // Update the temporary touch state.
1614 BitSet32 pointerIds;
1615 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001616 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001617 pointerIds.markBit(pointerId);
1618 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001619 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 }
1621
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001622 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 } else {
1624 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1625
1626 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001627 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001628 if (DEBUG_FOCUS) {
1629 ALOGD("Dropping event because the pointer is not down or we previously "
1630 "dropped the pointer down event in display %" PRId32,
1631 displayId);
1632 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1634 goto Failed;
1635 }
1636
1637 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001638 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001639 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001640 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1641 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642
1643 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001644 tempTouchState.getFirstForegroundWindowHandle();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001646 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001647 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1648 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001649 if (DEBUG_FOCUS) {
1650 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1651 oldTouchedWindowHandle->getName().c_str(),
1652 newTouchedWindowHandle->getName().c_str(), displayId);
1653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 // Make a slippery exit from the old window.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001655 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1656 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1657 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658
1659 // Make a slippery entrance into the new window.
1660 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1661 isSplit = true;
1662 }
1663
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001664 int32_t targetFlags =
1665 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 if (isSplit) {
1667 targetFlags |= InputTarget::FLAG_SPLIT;
1668 }
1669 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1670 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1671 }
1672
1673 BitSet32 pointerIds;
1674 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001675 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001677 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 }
1679 }
1680 }
1681
1682 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1683 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001684 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685#if DEBUG_HOVER
1686 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001687 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688#endif
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001689 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1690 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691 }
1692
1693 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001694 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695#if DEBUG_HOVER
1696 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001697 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698#endif
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001699 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1700 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1701 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702 }
1703 }
1704
1705 // Check permission to inject into all touched foreground windows and ensure there
1706 // is at least one touched foreground window.
1707 {
1708 bool haveForegroundWindow = false;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001709 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1711 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001712 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1714 injectionPermission = INJECTION_PERMISSION_DENIED;
1715 goto Failed;
1716 }
1717 }
1718 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001719 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001720 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001721 ALOGI("Dropping event because there is no touched foreground window in display "
1722 "%" PRId32 " or gesture monitor to receive it.",
1723 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1725 goto Failed;
1726 }
1727
1728 // Permission granted to injection into all touched foreground windows.
1729 injectionPermission = INJECTION_PERMISSION_GRANTED;
1730 }
1731
1732 // Check whether windows listening for outside touches are owned by the same UID. If it is
1733 // set the policy flag that we will not reveal coordinate information to this window.
1734 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1735 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001736 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001737 if (foregroundWindowHandle) {
1738 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001739 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001740 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1741 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1742 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001743 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1744 InputTarget::FLAG_ZERO_COORDS,
1745 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001746 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 }
1748 }
1749 }
1750 }
1751
1752 // Ensure all touched foreground windows are ready for new input.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001753 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001755 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001756 std::string reason =
1757 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1758 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001759 if (!reason.empty()) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001760 return handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1761 touchedWindow.windowHandle, nextWakeupTime,
1762 reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 }
1764 }
1765 }
1766
1767 // If this is the first pointer going down and the touched window has a wallpaper
1768 // then also add the touched wallpaper windows so they are locked in for the duration
1769 // of the touch gesture.
1770 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1771 // engine only supports touch events. We would need to add a mechanism similar
1772 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1773 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1774 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001775 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001776 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001777 const std::vector<sp<InputWindowHandle>> windowHandles =
1778 getWindowHandlesLocked(displayId);
1779 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001781 if (info->displayId == displayId &&
1782 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001783 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001784 .addOrUpdateWindow(windowHandle,
1785 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1786 InputTarget::
1787 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1788 InputTarget::FLAG_DISPATCH_AS_IS,
1789 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790 }
1791 }
1792 }
1793 }
1794
1795 // Success! Output targets.
1796 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1797
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001798 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001800 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 }
1802
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001803 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001804 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001805 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001806 }
1807
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 // Drop the outside or hover touch windows since we will not care about them
1809 // in the next iteration.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001810 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811
1812Failed:
1813 // Check injection permission once and for all.
1814 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001815 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 injectionPermission = INJECTION_PERMISSION_GRANTED;
1817 } else {
1818 injectionPermission = INJECTION_PERMISSION_DENIED;
1819 }
1820 }
1821
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001822 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1823 return injectionResult;
1824 }
1825
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001827 if (!wrongDevice) {
1828 if (switchedDevice) {
1829 if (DEBUG_FOCUS) {
1830 ALOGD("Conflicting pointer actions: Switched to a different device.");
1831 }
1832 *outConflictingPointerActions = true;
1833 }
1834
1835 if (isHoverAction) {
1836 // Started hovering, therefore no longer down.
1837 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001838 if (DEBUG_FOCUS) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001839 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1840 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 *outConflictingPointerActions = true;
1843 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001844 tempTouchState.reset();
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001845 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1846 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001847 tempTouchState.deviceId = entry.deviceId;
1848 tempTouchState.source = entry.source;
1849 tempTouchState.displayId = displayId;
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001850 }
1851 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1852 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1853 // All pointers up or canceled.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001854 tempTouchState.reset();
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001855 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1856 // First pointer went down.
1857 if (oldState && oldState->down) {
1858 if (DEBUG_FOCUS) {
1859 ALOGD("Conflicting pointer actions: Down received while already down.");
1860 }
1861 *outConflictingPointerActions = true;
1862 }
1863 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1864 // One pointer went up.
1865 if (isSplit) {
1866 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1867 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001869 for (size_t i = 0; i < tempTouchState.windows.size();) {
1870 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001871 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1872 touchedWindow.pointerIds.clearBit(pointerId);
1873 if (touchedWindow.pointerIds.isEmpty()) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001874 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001875 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001878 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001880 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001881 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001882
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001883 // Save changes unless the action was scroll in which case the temporary touch
1884 // state was only valid for this one action.
1885 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001886 if (tempTouchState.displayId >= 0) {
1887 mTouchStatesByDisplay[displayId] = tempTouchState;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001888 } else {
1889 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001893 // Update hover state.
1894 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 }
1896
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 return injectionResult;
1898}
1899
1900void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001901 int32_t targetFlags, BitSet32 pointerIds,
1902 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001903 std::vector<InputTarget>::iterator it =
1904 std::find_if(inputTargets.begin(), inputTargets.end(),
1905 [&windowHandle](const InputTarget& inputTarget) {
1906 return inputTarget.inputChannel->getConnectionToken() ==
1907 windowHandle->getToken();
1908 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00001909
Chavi Weingarten114b77f2020-01-15 22:35:10 +00001910 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001911
1912 if (it == inputTargets.end()) {
1913 InputTarget inputTarget;
1914 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1915 if (inputChannel == nullptr) {
1916 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1917 return;
1918 }
1919 inputTarget.inputChannel = inputChannel;
1920 inputTarget.flags = targetFlags;
1921 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
1922 inputTargets.push_back(inputTarget);
1923 it = inputTargets.end() - 1;
1924 }
1925
1926 ALOG_ASSERT(it->flags == targetFlags);
1927 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
1928
1929 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
1930 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931}
1932
Michael Wright3dd60e22019-03-27 22:06:44 +00001933void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001934 int32_t displayId, float xOffset,
1935 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001936 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1937 mGlobalMonitorsByDisplay.find(displayId);
1938
1939 if (it != mGlobalMonitorsByDisplay.end()) {
1940 const std::vector<Monitor>& monitors = it->second;
1941 for (const Monitor& monitor : monitors) {
1942 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 }
1945}
1946
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001947void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1948 float yOffset,
1949 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001950 InputTarget target;
1951 target.inputChannel = monitor.inputChannel;
1952 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001953 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00001954 inputTargets.push_back(target);
1955}
1956
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001958 const InjectionState* injectionState) {
1959 if (injectionState &&
1960 (windowHandle == nullptr ||
1961 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1962 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001963 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001965 "owned by uid %d",
1966 injectionState->injectorPid, injectionState->injectorUid,
1967 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 } else {
1969 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001970 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 }
1972 return false;
1973 }
1974 return true;
1975}
1976
Robert Carr9cada032020-04-13 17:21:08 -07001977/**
1978 * Indicate whether one window handle should be considered as obscuring
1979 * another window handle. We only check a few preconditions. Actually
1980 * checking the bounds is left to the caller.
1981 */
1982static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
1983 const sp<InputWindowHandle>& otherHandle) {
1984 // Compare by token so cloned layers aren't counted
1985 if (haveSameToken(windowHandle, otherHandle)) {
1986 return false;
1987 }
1988 auto info = windowHandle->getInfo();
1989 auto otherInfo = otherHandle->getInfo();
1990 if (!otherInfo->visible) {
1991 return false;
1992 } else if (info->ownerPid == otherInfo->ownerPid && otherHandle->getToken() == nullptr) {
1993 // In general, if ownerPid is the same we don't want to generate occlusion
1994 // events. This line is now necessary since we are including all Surfaces
1995 // in occlusion calculation, so if we didn't check PID like this SurfaceView
1996 // would occlude their parents. On the other hand before we started including
1997 // all surfaces in occlusion calculation and had this line, we would count
1998 // windows with an input channel from the same PID as occluding, and so we
1999 // preserve this behavior with the getToken() == null check.
2000 return false;
2001 } else if (otherInfo->isTrustedOverlay()) {
2002 return false;
2003 } else if (otherInfo->displayId != info->displayId) {
2004 return false;
2005 }
2006 return true;
2007}
2008
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002009bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2010 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002012 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2013 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002014 if (windowHandle == otherHandle) {
2015 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002018 if (canBeObscuredBy(windowHandle, otherHandle) &&
2019 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 return true;
2021 }
2022 }
2023 return false;
2024}
2025
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002026bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2027 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002028 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002029 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002030 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002031 if (windowHandle == otherHandle) {
2032 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002033 }
2034
2035 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002036 if (canBeObscuredBy(windowHandle, otherHandle) &&
2037 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002038 return true;
2039 }
2040 }
2041 return false;
2042}
2043
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002044std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
2045 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002046 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07002047 // If the window is paused then keep waiting.
2048 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002049 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002050 }
2051
2052 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07002053 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002054 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002055 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002056 "registered with the input dispatcher. The window may be in the "
2057 "process of being removed.",
2058 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002059 }
2060
2061 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07002062 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002063 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002064 "The window may be in the process of being removed.",
2065 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07002066 }
2067
2068 // If the connection is backed up then keep waiting.
2069 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002070 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002071 "Outbound queue length: %zu. Wait queue length: %zu.",
2072 targetType, connection->outboundQueue.size(),
2073 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07002074 }
2075
2076 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002077 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07002078 // If the event is a key event, then we must wait for all previous events to
2079 // complete before delivering it because previous events may have the
2080 // side-effect of transferring focus to a different window and we want to
2081 // ensure that the following keys are sent to the new window.
2082 //
2083 // Suppose the user touches a button in a window then immediately presses "A".
2084 // If the button causes a pop-up window to appear then we want to ensure that
2085 // the "A" key is delivered to the new pop-up window. This is because users
2086 // often anticipate pending UI changes when typing on a keyboard.
2087 // To obtain this behavior, we must serialize key events with respect to all
2088 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002089 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002090 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002091 "finished processing all of the input events that were previously "
2092 "delivered to it. Outbound queue length: %zu. Wait queue length: "
2093 "%zu.",
2094 targetType, connection->outboundQueue.size(),
2095 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 }
Jeff Brownffb49772014-10-10 19:01:34 -07002097 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 // Touch events can always be sent to a window immediately because the user intended
2099 // to touch whatever was visible at the time. Even if focus changes or a new
2100 // window appears moments later, the touch event was meant to be delivered to
2101 // whatever window happened to be on screen at the time.
2102 //
2103 // Generic motion events, such as trackball or joystick events are a little trickier.
2104 // Like key events, generic motion events are delivered to the focused window.
2105 // Unlike key events, generic motion events don't tend to transfer focus to other
2106 // windows and it is not important for them to be serialized. So we prefer to deliver
2107 // generic motion events as soon as possible to improve efficiency and reduce lag
2108 // through batching.
2109 //
2110 // The one case where we pause input event delivery is when the wait queue is piling
2111 // up with lots of events because the application is not responding.
2112 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002113 if (!connection->waitQueue.empty() &&
2114 currentTime >=
2115 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002116 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002117 "finished processing certain input events that were delivered to "
2118 "it over "
2119 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
2120 "%0.1fms.",
2121 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
2122 connection->waitQueue.size(),
2123 (currentTime - connection->waitQueue.front()->deliveryTime) *
2124 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 }
2126 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002127 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128}
2129
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002130std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 const sp<InputApplicationHandle>& applicationHandle,
2132 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002133 if (applicationHandle != nullptr) {
2134 if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002135 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 } else {
2137 return applicationHandle->getName();
2138 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002139 } else if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002140 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002142 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 }
2144}
2145
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002146void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002147 if (eventEntry.type == EventEntry::Type::FOCUS) {
2148 // Focus events are passed to apps, but do not represent user activity.
2149 return;
2150 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002151 int32_t displayId = getTargetDisplayId(eventEntry);
2152 sp<InputWindowHandle> focusedWindowHandle =
2153 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2154 if (focusedWindowHandle != nullptr) {
2155 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2157#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002158 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159#endif
2160 return;
2161 }
2162 }
2163
2164 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002165 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002166 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002167 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2168 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002169 return;
2170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002172 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002173 eventType = USER_ACTIVITY_EVENT_TOUCH;
2174 }
2175 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002177 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002178 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2179 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002180 return;
2181 }
2182 eventType = USER_ACTIVITY_EVENT_BUTTON;
2183 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002185 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002186 case EventEntry::Type::CONFIGURATION_CHANGED:
2187 case EventEntry::Type::DEVICE_RESET: {
2188 LOG_ALWAYS_FATAL("%s events are not user activity",
2189 EventEntry::typeToString(eventEntry.type));
2190 break;
2191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 }
2193
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002194 std::unique_ptr<CommandEntry> commandEntry =
2195 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002196 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002198 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199}
2200
2201void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002202 const sp<Connection>& connection,
2203 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002204 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002205 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002206 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002207 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002208 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002209 ATRACE_NAME(message.c_str());
2210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211#if DEBUG_DISPATCH_CYCLE
2212 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002213 "globalScaleFactor=%f, pointerIds=0x%x %s",
2214 connection->getInputChannelName().c_str(), inputTarget.flags,
2215 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2216 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217#endif
2218
2219 // Skip this event if the connection status is not normal.
2220 // We don't want to enqueue additional outbound events if the connection is broken.
2221 if (connection->status != Connection::STATUS_NORMAL) {
2222#if DEBUG_DISPATCH_CYCLE
2223 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002224 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225#endif
2226 return;
2227 }
2228
2229 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002230 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2231 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2232 "Entry type %s should not have FLAG_SPLIT",
2233 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002235 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002236 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002237 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002238 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002239 if (!splitMotionEntry) {
2240 return; // split event was dropped
2241 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002242 if (DEBUG_FOCUS) {
2243 ALOGD("channel '%s' ~ Split motion event.",
2244 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002245 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002246 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002247 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 splitMotionEntry->release();
2249 return;
2250 }
2251 }
2252
2253 // Not splitting. Enqueue dispatch entries for the event as is.
2254 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2255}
2256
2257void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002258 const sp<Connection>& connection,
2259 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002260 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002261 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002262 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002263 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002264 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002265 ATRACE_NAME(message.c_str());
2266 }
2267
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002268 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269
2270 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002271 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002272 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002273 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002274 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002275 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002276 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002277 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002278 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002279 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002280 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002281 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002282 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283
2284 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002285 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 startDispatchCycleLocked(currentTime, connection);
2287 }
2288}
2289
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002290void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2291 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002292 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002293 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002294 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2296 connection->getInputChannelName().c_str(),
2297 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002298 ATRACE_NAME(message.c_str());
2299 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002300 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 if (!(inputTargetFlags & dispatchMode)) {
2302 return;
2303 }
2304 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2305
2306 // This is a new event.
2307 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002308 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002309 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002311 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2312 // different EventEntry than what was passed in.
2313 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002315 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002316 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002317 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002318 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002319 dispatchEntry->resolvedAction = keyEntry.action;
2320 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002322 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2323 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002325 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2326 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002328 return; // skip the inconsistent event
2329 }
2330 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002333 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002334 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002335 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2336 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2337 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2338 static_cast<int32_t>(IdGenerator::Source::OTHER);
2339 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002340 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2341 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2342 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2343 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2344 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2345 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2346 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2347 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2348 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2349 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2350 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002351 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002352 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002353 }
2354 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002355 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2356 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002358 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2359 "event",
2360 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002362 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002365 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002366 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2367 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2368 }
2369 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2370 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002373 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2374 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002376 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2377 "event",
2378 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002380 return; // skip the inconsistent event
2381 }
2382
Garfield Tan1c7bc862020-01-28 13:24:04 -08002383 dispatchEntry->resolvedEventId =
2384 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2385 ? mIdGenerator.nextId()
2386 : motionEntry.id;
2387 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2388 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2389 ") to MotionEvent(id=0x%" PRIx32 ").",
2390 motionEntry.id, dispatchEntry->resolvedEventId);
2391 ATRACE_NAME(message.c_str());
2392 }
2393
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002394 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002395 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002396
2397 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002399 case EventEntry::Type::FOCUS: {
2400 break;
2401 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002402 case EventEntry::Type::CONFIGURATION_CHANGED:
2403 case EventEntry::Type::DEVICE_RESET: {
2404 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002405 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002406 break;
2407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 }
2409
2410 // Remember that we are waiting for this dispatch to complete.
2411 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002412 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 }
2414
2415 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002416 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002417 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002418}
2419
chaviwfd6d3512019-03-25 13:23:49 -07002420void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002421 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002422 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002423 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2424 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002425 return;
2426 }
2427
2428 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2429 if (inputWindowHandle == nullptr) {
2430 return;
2431 }
2432
chaviw8c9cf542019-03-25 13:02:48 -07002433 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002434 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002435
2436 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2437
2438 if (!hasFocusChanged) {
2439 return;
2440 }
2441
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002442 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2443 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002444 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002445 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446}
2447
2448void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002449 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002450 if (ATRACE_ENABLED()) {
2451 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002452 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002453 ATRACE_NAME(message.c_str());
2454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002456 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457#endif
2458
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002459 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2460 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002461 dispatchEntry->deliveryTime = currentTime;
2462
2463 // Publish the event.
2464 status_t status;
2465 EventEntry* eventEntry = dispatchEntry->eventEntry;
2466 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002467 case EventEntry::Type::KEY: {
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002468 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2469 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002471 // Publish the key event.
Garfield Tan1c7bc862020-01-28 13:24:04 -08002472 status =
2473 connection->inputPublisher
2474 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2475 keyEntry->deviceId, keyEntry->source,
2476 keyEntry->displayId, std::move(hmac),
2477 dispatchEntry->resolvedAction,
2478 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2479 keyEntry->scanCode, keyEntry->metaState,
2480 keyEntry->repeatCount, keyEntry->downTime,
2481 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002482 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 }
2484
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002485 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002486 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002488 PointerCoords scaledCoords[MAX_POINTERS];
2489 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2490
chaviw82357092020-01-28 13:13:06 -08002491 // Set the X and Y offset and X and Y scale depending on the input source.
2492 float xOffset = 0.0f, yOffset = 0.0f;
2493 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002494 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2495 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2496 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002497 xScale = dispatchEntry->windowXScale;
2498 yScale = dispatchEntry->windowYScale;
2499 xOffset = dispatchEntry->xOffset * xScale;
2500 yOffset = dispatchEntry->yOffset * yScale;
2501 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002502 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2503 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002504 // Don't apply window scale here since we don't want scale to affect raw
2505 // coordinates. The scale will be sent back to the client and applied
2506 // later when requesting relative coordinates.
2507 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2508 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002509 }
2510 usingCoords = scaledCoords;
2511 }
2512 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002513 // We don't want the dispatch target to know.
2514 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2515 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2516 scaledCoords[i].clear();
2517 }
2518 usingCoords = scaledCoords;
2519 }
2520 }
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002521
2522 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002523
2524 // Publish the motion event.
2525 status = connection->inputPublisher
Garfield Tan1c7bc862020-01-28 13:24:04 -08002526 .publishMotionEvent(dispatchEntry->seq,
2527 dispatchEntry->resolvedEventId,
2528 motionEntry->deviceId, motionEntry->source,
2529 motionEntry->displayId, std::move(hmac),
2530 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002531 motionEntry->actionButton,
2532 dispatchEntry->resolvedFlags,
2533 motionEntry->edgeFlags, motionEntry->metaState,
2534 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002535 motionEntry->classification, xScale, yScale,
2536 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002537 motionEntry->yPrecision,
2538 motionEntry->xCursorPosition,
2539 motionEntry->yCursorPosition,
2540 motionEntry->downTime, motionEntry->eventTime,
2541 motionEntry->pointerCount,
2542 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002543 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002544 break;
2545 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002546 case EventEntry::Type::FOCUS: {
2547 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2548 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tan1c7bc862020-01-28 13:24:04 -08002549 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002550 focusEntry->hasFocus,
2551 mInTouchMode);
2552 break;
2553 }
2554
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002555 case EventEntry::Type::CONFIGURATION_CHANGED:
2556 case EventEntry::Type::DEVICE_RESET: {
2557 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2558 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002559 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002560 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561 }
2562
2563 // Check the result.
2564 if (status) {
2565 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002566 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002568 "This is unexpected because the wait queue is empty, so the pipe "
2569 "should be empty and we shouldn't have any problems writing an "
2570 "event to it, status=%d",
2571 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2573 } else {
2574 // Pipe is full and we are waiting for the app to finish process some events
2575 // before sending more events to it.
2576#if DEBUG_DISPATCH_CYCLE
2577 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002578 "waiting for the application to catch up",
2579 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580#endif
2581 connection->inputPublisherBlocked = true;
2582 }
2583 } else {
2584 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002585 "status=%d",
2586 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2588 }
2589 return;
2590 }
2591
2592 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002593 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2594 connection->outboundQueue.end(),
2595 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002596 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002597 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002598 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 }
2600}
2601
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002602const std::array<uint8_t, 32> InputDispatcher::getSignature(
2603 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2604 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2605 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2606 // Only sign events up and down events as the purely move events
2607 // are tied to their up/down counterparts so signing would be redundant.
2608 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2609 verifiedEvent.actionMasked = actionMasked;
2610 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2611 return mHmacKeyManager.sign(verifiedEvent);
2612 }
2613 return INVALID_HMAC;
2614}
2615
2616const std::array<uint8_t, 32> InputDispatcher::getSignature(
2617 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2618 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2619 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2620 verifiedEvent.action = dispatchEntry.resolvedAction;
2621 return mHmacKeyManager.sign(verifiedEvent);
2622}
2623
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002625 const sp<Connection>& connection, uint32_t seq,
2626 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627#if DEBUG_DISPATCH_CYCLE
2628 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002629 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002630#endif
2631
2632 connection->inputPublisherBlocked = false;
2633
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002634 if (connection->status == Connection::STATUS_BROKEN ||
2635 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002636 return;
2637 }
2638
2639 // Notify other system components and prepare to start the next dispatch cycle.
2640 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2641}
2642
2643void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002644 const sp<Connection>& connection,
2645 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646#if DEBUG_DISPATCH_CYCLE
2647 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002648 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649#endif
2650
2651 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002652 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002653 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002654 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002655 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656
2657 // The connection appears to be unrecoverably broken.
2658 // Ignore already broken or zombie connections.
2659 if (connection->status == Connection::STATUS_NORMAL) {
2660 connection->status = Connection::STATUS_BROKEN;
2661
2662 if (notify) {
2663 // Notify other system components.
2664 onDispatchCycleBrokenLocked(currentTime, connection);
2665 }
2666 }
2667}
2668
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002669void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2670 while (!queue.empty()) {
2671 DispatchEntry* dispatchEntry = queue.front();
2672 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002673 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674 }
2675}
2676
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002677void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002679 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 }
2681 delete dispatchEntry;
2682}
2683
2684int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2685 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2686
2687 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002688 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002690 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002692 "fd=%d, events=0x%x",
2693 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 return 0; // remove the callback
2695 }
2696
2697 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002698 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2700 if (!(events & ALOOPER_EVENT_INPUT)) {
2701 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002702 "events=0x%x",
2703 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704 return 1;
2705 }
2706
2707 nsecs_t currentTime = now();
2708 bool gotOne = false;
2709 status_t status;
2710 for (;;) {
2711 uint32_t seq;
2712 bool handled;
2713 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2714 if (status) {
2715 break;
2716 }
2717 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2718 gotOne = true;
2719 }
2720 if (gotOne) {
2721 d->runCommandsLockedInterruptible();
2722 if (status == WOULD_BLOCK) {
2723 return 1;
2724 }
2725 }
2726
2727 notify = status != DEAD_OBJECT || !connection->monitor;
2728 if (notify) {
2729 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002730 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002731 }
2732 } else {
2733 // Monitor channels are never explicitly unregistered.
2734 // We do it automatically when the remote endpoint is closed so don't warn
2735 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002736 const bool stillHaveWindowHandle =
2737 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2738 nullptr;
2739 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740 if (notify) {
2741 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002742 "events=0x%x",
2743 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 }
2745 }
2746
2747 // Unregister the channel.
2748 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2749 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002750 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002751}
2752
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002753void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002754 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002755 for (const auto& pair : mConnectionsByFd) {
2756 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 }
2758}
2759
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002760void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002761 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002762 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2763 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2764}
2765
2766void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2767 const CancelationOptions& options,
2768 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2769 for (const auto& it : monitorsByDisplay) {
2770 const std::vector<Monitor>& monitors = it.second;
2771 for (const Monitor& monitor : monitors) {
2772 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002773 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002774 }
2775}
2776
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2778 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002779 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002780 if (connection == nullptr) {
2781 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002783
2784 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785}
2786
2787void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2788 const sp<Connection>& connection, const CancelationOptions& options) {
2789 if (connection->status == Connection::STATUS_BROKEN) {
2790 return;
2791 }
2792
2793 nsecs_t currentTime = now();
2794
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002795 std::vector<EventEntry*> cancelationEvents =
2796 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002798 if (cancelationEvents.empty()) {
2799 return;
2800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002802 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2803 "with reality: %s, mode=%d.",
2804 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2805 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002807
2808 InputTarget target;
2809 sp<InputWindowHandle> windowHandle =
2810 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2811 if (windowHandle != nullptr) {
2812 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2813 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2814 windowInfo->windowXScale, windowInfo->windowYScale);
2815 target.globalScaleFactor = windowInfo->globalScaleFactor;
2816 }
2817 target.inputChannel = connection->inputChannel;
2818 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2819
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002820 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2821 EventEntry* cancelationEventEntry = cancelationEvents[i];
2822 switch (cancelationEventEntry->type) {
2823 case EventEntry::Type::KEY: {
2824 logOutboundKeyDetails("cancel - ",
2825 static_cast<const KeyEntry&>(*cancelationEventEntry));
2826 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002828 case EventEntry::Type::MOTION: {
2829 logOutboundMotionDetails("cancel - ",
2830 static_cast<const MotionEntry&>(*cancelationEventEntry));
2831 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002833 case EventEntry::Type::FOCUS: {
2834 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2835 break;
2836 }
2837 case EventEntry::Type::CONFIGURATION_CHANGED:
2838 case EventEntry::Type::DEVICE_RESET: {
2839 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2840 EventEntry::typeToString(cancelationEventEntry->type));
2841 break;
2842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 }
2844
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002845 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2846 target, InputTarget::FLAG_DISPATCH_AS_IS);
2847
2848 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002850
2851 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852}
2853
Svet Ganov5d3bc372020-01-26 23:11:07 -08002854void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2855 const sp<Connection>& connection) {
2856 if (connection->status == Connection::STATUS_BROKEN) {
2857 return;
2858 }
2859
2860 nsecs_t currentTime = now();
2861
2862 std::vector<EventEntry*> downEvents =
2863 connection->inputState.synthesizePointerDownEvents(currentTime);
2864
2865 if (downEvents.empty()) {
2866 return;
2867 }
2868
2869#if DEBUG_OUTBOUND_EVENT_DETAILS
2870 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2871 connection->getInputChannelName().c_str(), downEvents.size());
2872#endif
2873
2874 InputTarget target;
2875 sp<InputWindowHandle> windowHandle =
2876 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2877 if (windowHandle != nullptr) {
2878 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2879 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2880 windowInfo->windowXScale, windowInfo->windowYScale);
2881 target.globalScaleFactor = windowInfo->globalScaleFactor;
2882 }
2883 target.inputChannel = connection->inputChannel;
2884 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2885
2886 for (EventEntry* downEventEntry : downEvents) {
2887 switch (downEventEntry->type) {
2888 case EventEntry::Type::MOTION: {
2889 logOutboundMotionDetails("down - ",
2890 static_cast<const MotionEntry&>(*downEventEntry));
2891 break;
2892 }
2893
2894 case EventEntry::Type::KEY:
2895 case EventEntry::Type::FOCUS:
2896 case EventEntry::Type::CONFIGURATION_CHANGED:
2897 case EventEntry::Type::DEVICE_RESET: {
2898 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2899 EventEntry::typeToString(downEventEntry->type));
2900 break;
2901 }
2902 }
2903
2904 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2905 target, InputTarget::FLAG_DISPATCH_AS_IS);
2906
2907 downEventEntry->release();
2908 }
2909
2910 startDispatchCycleLocked(currentTime, connection);
2911}
2912
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002913MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002914 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915 ALOG_ASSERT(pointerIds.value != 0);
2916
2917 uint32_t splitPointerIndexMap[MAX_POINTERS];
2918 PointerProperties splitPointerProperties[MAX_POINTERS];
2919 PointerCoords splitPointerCoords[MAX_POINTERS];
2920
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002921 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922 uint32_t splitPointerCount = 0;
2923
2924 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002925 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002927 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 uint32_t pointerId = uint32_t(pointerProperties.id);
2929 if (pointerIds.hasBit(pointerId)) {
2930 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2931 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2932 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002933 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934 splitPointerCount += 1;
2935 }
2936 }
2937
2938 if (splitPointerCount != pointerIds.count()) {
2939 // This is bad. We are missing some of the pointers that we expected to deliver.
2940 // Most likely this indicates that we received an ACTION_MOVE events that has
2941 // different pointer ids than we expected based on the previous ACTION_DOWN
2942 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2943 // in this way.
2944 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002945 "we expected there to be %d pointers. This probably means we received "
2946 "a broken sequence of pointer ids from the input device.",
2947 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002948 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949 }
2950
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002951 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002952 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002953 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2954 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2956 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002957 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958 uint32_t pointerId = uint32_t(pointerProperties.id);
2959 if (pointerIds.hasBit(pointerId)) {
2960 if (pointerIds.count() == 1) {
2961 // The first/last pointer went down/up.
2962 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002963 ? AMOTION_EVENT_ACTION_DOWN
2964 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965 } else {
2966 // A secondary pointer went down/up.
2967 uint32_t splitPointerIndex = 0;
2968 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2969 splitPointerIndex += 1;
2970 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002971 action = maskedAction |
2972 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 }
2974 } else {
2975 // An unrelated pointer changed.
2976 action = AMOTION_EVENT_ACTION_MOVE;
2977 }
2978 }
2979
Garfield Tan1c7bc862020-01-28 13:24:04 -08002980 int32_t newId = mIdGenerator.nextId();
2981 if (ATRACE_ENABLED()) {
2982 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
2983 ") to MotionEvent(id=0x%" PRIx32 ").",
2984 originalMotionEntry.id, newId);
2985 ATRACE_NAME(message.c_str());
2986 }
Garfield Tan00f511d2019-06-12 16:55:40 -07002987 MotionEntry* splitMotionEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002988 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
2989 originalMotionEntry.source, originalMotionEntry.displayId,
2990 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002991 originalMotionEntry.actionButton, originalMotionEntry.flags,
2992 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2993 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2994 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2995 originalMotionEntry.xCursorPosition,
2996 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002997 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002998
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002999 if (originalMotionEntry.injectionState) {
3000 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001 splitMotionEntry->injectionState->refCount += 1;
3002 }
3003
3004 return splitMotionEntry;
3005}
3006
3007void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3008#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003009 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003010#endif
3011
3012 bool needWake;
3013 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003014 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015
Prabir Pradhan42611e02018-11-27 14:04:02 -08003016 ConfigurationChangedEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003017 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003018 needWake = enqueueInboundEventLocked(newEntry);
3019 } // release lock
3020
3021 if (needWake) {
3022 mLooper->wake();
3023 }
3024}
3025
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003026/**
3027 * If one of the meta shortcuts is detected, process them here:
3028 * Meta + Backspace -> generate BACK
3029 * Meta + Enter -> generate HOME
3030 * This will potentially overwrite keyCode and metaState.
3031 */
3032void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003033 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003034 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3035 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3036 if (keyCode == AKEYCODE_DEL) {
3037 newKeyCode = AKEYCODE_BACK;
3038 } else if (keyCode == AKEYCODE_ENTER) {
3039 newKeyCode = AKEYCODE_HOME;
3040 }
3041 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003042 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003043 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003044 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003045 keyCode = newKeyCode;
3046 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3047 }
3048 } else if (action == AKEY_EVENT_ACTION_UP) {
3049 // In order to maintain a consistent stream of up and down events, check to see if the key
3050 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3051 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003052 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003053 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003054 auto replacementIt = mReplacedKeys.find(replacement);
3055 if (replacementIt != mReplacedKeys.end()) {
3056 keyCode = replacementIt->second;
3057 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003058 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3059 }
3060 }
3061}
3062
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3064#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003065 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3066 "policyFlags=0x%x, action=0x%x, "
3067 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3068 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3069 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3070 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071#endif
3072 if (!validateKeyEvent(args->action)) {
3073 return;
3074 }
3075
3076 uint32_t policyFlags = args->policyFlags;
3077 int32_t flags = args->flags;
3078 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003079 // InputDispatcher tracks and generates key repeats on behalf of
3080 // whatever notifies it, so repeatCount should always be set to 0
3081 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3083 policyFlags |= POLICY_FLAG_VIRTUAL;
3084 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 if (policyFlags & POLICY_FLAG_FUNCTION) {
3087 metaState |= AMETA_FUNCTION_ON;
3088 }
3089
3090 policyFlags |= POLICY_FLAG_TRUSTED;
3091
Michael Wright78f24442014-08-06 15:55:28 -07003092 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003093 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003094
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003096 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08003097 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3098 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099
Michael Wright2b3c3302018-03-02 17:19:13 +00003100 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003102 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3103 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003104 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003105 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 bool needWake;
3108 { // acquire lock
3109 mLock.lock();
3110
3111 if (shouldSendKeyToInputFilterLocked(args)) {
3112 mLock.unlock();
3113
3114 policyFlags |= POLICY_FLAG_FILTERED;
3115 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3116 return; // event was consumed by the filter
3117 }
3118
3119 mLock.lock();
3120 }
3121
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003122 KeyEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003123 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003124 args->displayId, policyFlags, args->action, flags, keyCode,
3125 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126
3127 needWake = enqueueInboundEventLocked(newEntry);
3128 mLock.unlock();
3129 } // release lock
3130
3131 if (needWake) {
3132 mLooper->wake();
3133 }
3134}
3135
3136bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3137 return mInputFilterEnabled;
3138}
3139
3140void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3141#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003142 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3143 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003144 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3145 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003146 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003147 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3148 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3149 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3150 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 for (uint32_t i = 0; i < args->pointerCount; i++) {
3152 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003153 "x=%f, y=%f, pressure=%f, size=%f, "
3154 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3155 "orientation=%f",
3156 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3157 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3158 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3159 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3160 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3161 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3162 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3163 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3164 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3165 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166 }
3167#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003168 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3169 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 return;
3171 }
3172
3173 uint32_t policyFlags = args->policyFlags;
3174 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003175
3176 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003177 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003178 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3179 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003180 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003181 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182
3183 bool needWake;
3184 { // acquire lock
3185 mLock.lock();
3186
3187 if (shouldSendMotionToInputFilterLocked(args)) {
3188 mLock.unlock();
3189
3190 MotionEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003191 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3192 args->action, args->actionButton, args->flags, args->edgeFlags,
3193 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3194 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3195 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3196 args->downTime, args->eventTime, args->pointerCount,
3197 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198
3199 policyFlags |= POLICY_FLAG_FILTERED;
3200 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3201 return; // event was consumed by the filter
3202 }
3203
3204 mLock.lock();
3205 }
3206
3207 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003208 MotionEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003209 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003210 args->displayId, policyFlags, args->action, args->actionButton,
3211 args->flags, args->metaState, args->buttonState,
3212 args->classification, args->edgeFlags, args->xPrecision,
3213 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3214 args->downTime, args->pointerCount, args->pointerProperties,
3215 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216
3217 needWake = enqueueInboundEventLocked(newEntry);
3218 mLock.unlock();
3219 } // release lock
3220
3221 if (needWake) {
3222 mLooper->wake();
3223 }
3224}
3225
3226bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003227 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228}
3229
3230void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3231#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003232 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003233 "switchMask=0x%08x",
3234 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235#endif
3236
3237 uint32_t policyFlags = args->policyFlags;
3238 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003239 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240}
3241
3242void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3243#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003244 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3245 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246#endif
3247
3248 bool needWake;
3249 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003250 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251
Prabir Pradhan42611e02018-11-27 14:04:02 -08003252 DeviceResetEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003253 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254 needWake = enqueueInboundEventLocked(newEntry);
3255 } // release lock
3256
3257 if (needWake) {
3258 mLooper->wake();
3259 }
3260}
3261
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003262int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3263 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003264 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265#if DEBUG_INBOUND_EVENT_DETAILS
3266 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003267 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3268 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269#endif
3270
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003271 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272
3273 policyFlags |= POLICY_FLAG_INJECTED;
3274 if (hasInjectionPermission(injectorPid, injectorUid)) {
3275 policyFlags |= POLICY_FLAG_TRUSTED;
3276 }
3277
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003278 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003280 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003281 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3282 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003283 if (!validateKeyEvent(action)) {
3284 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003285 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003287 int32_t flags = incomingKey.getFlags();
3288 int32_t keyCode = incomingKey.getKeyCode();
3289 int32_t metaState = incomingKey.getMetaState();
3290 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003291 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003292 KeyEvent keyEvent;
Garfield Tanfbe732e2020-01-24 11:26:14 -08003293 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003294 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3295 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3296 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3299 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003300 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301
3302 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3303 android::base::Timer t;
3304 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3305 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3306 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3307 std::to_string(t.duration().count()).c_str());
3308 }
3309 }
3310
3311 mLock.lock();
3312 KeyEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003313 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3314 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003315 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3316 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tanfbe732e2020-01-24 11:26:14 -08003317 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 injectedEntries.push(injectedEntry);
3319 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 }
3321
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 case AINPUT_EVENT_TYPE_MOTION: {
3323 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3324 int32_t action = motionEvent->getAction();
3325 size_t pointerCount = motionEvent->getPointerCount();
3326 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3327 int32_t actionButton = motionEvent->getActionButton();
3328 int32_t displayId = motionEvent->getDisplayId();
3329 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3330 return INPUT_EVENT_INJECTION_FAILED;
3331 }
3332
3333 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3334 nsecs_t eventTime = motionEvent->getEventTime();
3335 android::base::Timer t;
3336 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3337 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3338 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3339 std::to_string(t.duration().count()).c_str());
3340 }
3341 }
3342
3343 mLock.lock();
3344 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3345 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3346 MotionEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003347 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3348 motionEvent->getSource(), motionEvent->getDisplayId(),
3349 policyFlags, action, actionButton, motionEvent->getFlags(),
3350 motionEvent->getMetaState(), motionEvent->getButtonState(),
3351 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3352 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003353 motionEvent->getRawXCursorPosition(),
3354 motionEvent->getRawYCursorPosition(),
3355 motionEvent->getDownTime(), uint32_t(pointerCount),
3356 pointerProperties, samplePointerCoords,
3357 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003358 injectedEntries.push(injectedEntry);
3359 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3360 sampleEventTimes += 1;
3361 samplePointerCoords += pointerCount;
3362 MotionEntry* nextInjectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003363 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003364 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003365 motionEvent->getDisplayId(), policyFlags, action,
3366 actionButton, motionEvent->getFlags(),
3367 motionEvent->getMetaState(), motionEvent->getButtonState(),
3368 motionEvent->getClassification(),
3369 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3370 motionEvent->getYPrecision(),
3371 motionEvent->getRawXCursorPosition(),
3372 motionEvent->getRawYCursorPosition(),
3373 motionEvent->getDownTime(), uint32_t(pointerCount),
3374 pointerProperties, samplePointerCoords,
3375 motionEvent->getXOffset(), motionEvent->getYOffset());
3376 injectedEntries.push(nextInjectedEntry);
3377 }
3378 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003381 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003382 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003383 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 }
3385
3386 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3387 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3388 injectionState->injectionIsAsync = true;
3389 }
3390
3391 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003392 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393
3394 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003395 while (!injectedEntries.empty()) {
3396 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3397 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 }
3399
3400 mLock.unlock();
3401
3402 if (needWake) {
3403 mLooper->wake();
3404 }
3405
3406 int32_t injectionResult;
3407 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003408 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409
3410 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3411 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3412 } else {
3413 for (;;) {
3414 injectionResult = injectionState->injectionResult;
3415 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3416 break;
3417 }
3418
3419 nsecs_t remainingTimeout = endTime - now();
3420 if (remainingTimeout <= 0) {
3421#if DEBUG_INJECTION
3422 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003423 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424#endif
3425 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3426 break;
3427 }
3428
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003429 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 }
3431
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003432 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3433 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434 while (injectionState->pendingForegroundDispatches != 0) {
3435#if DEBUG_INJECTION
3436 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003437 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438#endif
3439 nsecs_t remainingTimeout = endTime - now();
3440 if (remainingTimeout <= 0) {
3441#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003442 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3443 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444#endif
3445 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3446 break;
3447 }
3448
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003449 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450 }
3451 }
3452 }
3453
3454 injectionState->release();
3455 } // release lock
3456
3457#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003458 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003459 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460#endif
3461
3462 return injectionResult;
3463}
3464
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003465std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003466 std::array<uint8_t, 32> calculatedHmac;
3467 std::unique_ptr<VerifiedInputEvent> result;
3468 switch (event.getType()) {
3469 case AINPUT_EVENT_TYPE_KEY: {
3470 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3471 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3472 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3473 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3474 break;
3475 }
3476 case AINPUT_EVENT_TYPE_MOTION: {
3477 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3478 VerifiedMotionEvent verifiedMotionEvent =
3479 verifiedMotionEventFromMotionEvent(motionEvent);
3480 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3481 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3482 break;
3483 }
3484 default: {
3485 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3486 return nullptr;
3487 }
3488 }
3489 if (calculatedHmac == INVALID_HMAC) {
3490 return nullptr;
3491 }
3492 if (calculatedHmac != event.getHmac()) {
3493 return nullptr;
3494 }
3495 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003496}
3497
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003499 return injectorUid == 0 ||
3500 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501}
3502
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003503void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 InjectionState* injectionState = entry->injectionState;
3505 if (injectionState) {
3506#if DEBUG_INJECTION
3507 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003508 "injectorPid=%d, injectorUid=%d",
3509 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510#endif
3511
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003512 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 // Log the outcome since the injector did not wait for the injection result.
3514 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003515 case INPUT_EVENT_INJECTION_SUCCEEDED:
3516 ALOGV("Asynchronous input event injection succeeded.");
3517 break;
3518 case INPUT_EVENT_INJECTION_FAILED:
3519 ALOGW("Asynchronous input event injection failed.");
3520 break;
3521 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3522 ALOGW("Asynchronous input event injection permission denied.");
3523 break;
3524 case INPUT_EVENT_INJECTION_TIMED_OUT:
3525 ALOGW("Asynchronous input event injection timed out.");
3526 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528 }
3529
3530 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003531 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 }
3533}
3534
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003535void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 InjectionState* injectionState = entry->injectionState;
3537 if (injectionState) {
3538 injectionState->pendingForegroundDispatches += 1;
3539 }
3540}
3541
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003542void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543 InjectionState* injectionState = entry->injectionState;
3544 if (injectionState) {
3545 injectionState->pendingForegroundDispatches -= 1;
3546
3547 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003548 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549 }
3550 }
3551}
3552
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003553std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3554 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003555 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003556}
3557
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003559 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003560 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003561 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3562 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003563 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003564 return windowHandle;
3565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566 }
3567 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003568 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569}
3570
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003571bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003572 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003573 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3574 for (const sp<InputWindowHandle>& handle : windowHandles) {
3575 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003576 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003577 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003578 ", but it should belong to display %" PRId32,
3579 windowHandle->getName().c_str(), it.first,
3580 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003581 }
3582 return true;
3583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584 }
3585 }
3586 return false;
3587}
3588
Robert Carr5c8a0262018-10-03 16:30:44 -07003589sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3590 size_t count = mInputChannelsByToken.count(token);
3591 if (count == 0) {
3592 return nullptr;
3593 }
3594 return mInputChannelsByToken.at(token);
3595}
3596
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003597void InputDispatcher::updateWindowHandlesForDisplayLocked(
3598 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3599 if (inputWindowHandles.empty()) {
3600 // Remove all handles on a display if there are no windows left.
3601 mWindowHandlesByDisplay.erase(displayId);
3602 return;
3603 }
3604
3605 // Since we compare the pointer of input window handles across window updates, we need
3606 // to make sure the handle object for the same window stays unchanged across updates.
3607 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003608 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003609 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003610 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003611 }
3612
3613 std::vector<sp<InputWindowHandle>> newHandles;
3614 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3615 if (!handle->updateInfo()) {
3616 // handle no longer valid
3617 continue;
3618 }
3619
3620 const InputWindowInfo* info = handle->getInfo();
3621 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3622 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3623 const bool noInputChannel =
3624 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3625 const bool canReceiveInput =
3626 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3627 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3628 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003629 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003630 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003631 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003632 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003633 }
3634
3635 if (info->displayId != displayId) {
3636 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3637 handle->getName().c_str(), displayId, info->displayId);
3638 continue;
3639 }
3640
Robert Carredd13602020-04-13 17:24:34 -07003641 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3642 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003643 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003644 oldHandle->updateFrom(handle);
3645 newHandles.push_back(oldHandle);
3646 } else {
3647 newHandles.push_back(handle);
3648 }
3649 }
3650
3651 // Insert or replace
3652 mWindowHandlesByDisplay[displayId] = newHandles;
3653}
3654
Arthur Hung72d8dc32020-03-28 00:48:39 +00003655void InputDispatcher::setInputWindows(
3656 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3657 { // acquire lock
3658 std::scoped_lock _l(mLock);
3659 for (auto const& i : handlesPerDisplay) {
3660 setInputWindowsLocked(i.second, i.first);
3661 }
3662 }
3663 // Wake up poll loop since it may need to make new input dispatching choices.
3664 mLooper->wake();
3665}
3666
Arthur Hungb92218b2018-08-14 12:00:21 +08003667/**
3668 * Called from InputManagerService, update window handle list by displayId that can receive input.
3669 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3670 * If set an empty list, remove all handles from the specific display.
3671 * For focused handle, check if need to change and send a cancel event to previous one.
3672 * For removed handle, check if need to send a cancel event if already in touch.
3673 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003674void InputDispatcher::setInputWindowsLocked(
3675 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003676 if (DEBUG_FOCUS) {
3677 std::string windowList;
3678 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3679 windowList += iwh->getName() + " ";
3680 }
3681 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683
Arthur Hung72d8dc32020-03-28 00:48:39 +00003684 // Copy old handles for release if they are no longer present.
3685 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686
Arthur Hung72d8dc32020-03-28 00:48:39 +00003687 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003688
Arthur Hung72d8dc32020-03-28 00:48:39 +00003689 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3690 bool foundHoveredWindow = false;
3691 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3692 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3693 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3694 windowHandle->getInfo()->visible) {
3695 newFocusedWindowHandle = windowHandle;
3696 }
3697 if (windowHandle == mLastHoverWindowHandle) {
3698 foundHoveredWindow = true;
3699 }
3700 }
3701
3702 if (!foundHoveredWindow) {
3703 mLastHoverWindowHandle = nullptr;
3704 }
3705
3706 sp<InputWindowHandle> oldFocusedWindowHandle =
3707 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3708
3709 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3710 if (oldFocusedWindowHandle != nullptr) {
3711 if (DEBUG_FOCUS) {
3712 ALOGD("Focus left window: %s in display %" PRId32,
3713 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003714 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003715 sp<InputChannel> focusedInputChannel =
3716 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3717 if (focusedInputChannel != nullptr) {
3718 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3719 "focus left window");
3720 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3721 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003722 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003723 mFocusedWindowHandlesByDisplay.erase(displayId);
3724 }
3725 if (newFocusedWindowHandle != nullptr) {
3726 if (DEBUG_FOCUS) {
3727 ALOGD("Focus entered window: %s in display %" PRId32,
3728 newFocusedWindowHandle->getName().c_str(), displayId);
3729 }
3730 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3731 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 }
3733
Arthur Hung72d8dc32020-03-28 00:48:39 +00003734 if (mFocusedDisplayId == displayId) {
3735 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003739 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3740 mTouchStatesByDisplay.find(displayId);
3741 if (stateIt != mTouchStatesByDisplay.end()) {
3742 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003743 for (size_t i = 0; i < state.windows.size();) {
3744 TouchedWindow& touchedWindow = state.windows[i];
3745 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003746 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003747 ALOGD("Touched window was removed: %s in display %" PRId32,
3748 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003749 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003750 sp<InputChannel> touchedInputChannel =
3751 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3752 if (touchedInputChannel != nullptr) {
3753 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3754 "touched window was removed");
3755 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003757 state.windows.erase(state.windows.begin() + i);
3758 } else {
3759 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 }
3761 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003762 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003763
Arthur Hung72d8dc32020-03-28 00:48:39 +00003764 // Release information for windows that are no longer present.
3765 // This ensures that unused input channels are released promptly.
3766 // Otherwise, they might stick around until the window handle is destroyed
3767 // which might not happen until the next GC.
3768 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3769 if (!hasWindowHandleLocked(oldWindowHandle)) {
3770 if (DEBUG_FOCUS) {
3771 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003772 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003773 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003774 }
chaviw291d88a2019-02-14 10:33:58 -08003775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776}
3777
3778void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003779 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003780 if (DEBUG_FOCUS) {
3781 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3782 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003785 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786
Tiger Huang721e26f2018-07-24 22:26:19 +08003787 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3788 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003789 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003790 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3791 if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003792 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003794 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003796 } else if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003797 resetAnrTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003798 oldFocusedApplicationHandle.clear();
3799 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 } // release lock
3802
3803 // Wake up poll loop since it may need to make new input dispatching choices.
3804 mLooper->wake();
3805}
3806
Tiger Huang721e26f2018-07-24 22:26:19 +08003807/**
3808 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3809 * the display not specified.
3810 *
3811 * We track any unreleased events for each window. If a window loses the ability to receive the
3812 * released event, we will send a cancel event to it. So when the focused display is changed, we
3813 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3814 * display. The display-specified events won't be affected.
3815 */
3816void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003817 if (DEBUG_FOCUS) {
3818 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3819 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003820 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003821 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003822
3823 if (mFocusedDisplayId != displayId) {
3824 sp<InputWindowHandle> oldFocusedWindowHandle =
3825 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3826 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003827 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003828 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003829 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003830 CancelationOptions
3831 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3832 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003833 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003834 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3835 }
3836 }
3837 mFocusedDisplayId = displayId;
3838
3839 // Sanity check
3840 sp<InputWindowHandle> newFocusedWindowHandle =
3841 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003842 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003843
Tiger Huang721e26f2018-07-24 22:26:19 +08003844 if (newFocusedWindowHandle == nullptr) {
3845 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3846 if (!mFocusedWindowHandlesByDisplay.empty()) {
3847 ALOGE("But another display has a focused window:");
3848 for (auto& it : mFocusedWindowHandlesByDisplay) {
3849 const int32_t displayId = it.first;
3850 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003851 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3852 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003853 }
3854 }
3855 }
3856 }
3857
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003858 if (DEBUG_FOCUS) {
3859 logDispatchStateLocked();
3860 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003861 } // release lock
3862
3863 // Wake up poll loop since it may need to make new input dispatching choices.
3864 mLooper->wake();
3865}
3866
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003868 if (DEBUG_FOCUS) {
3869 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871
3872 bool changed;
3873 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003874 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875
3876 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3877 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003878 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 }
3880
3881 if (mDispatchEnabled && !enabled) {
3882 resetAndDropEverythingLocked("dispatcher is being disabled");
3883 }
3884
3885 mDispatchEnabled = enabled;
3886 mDispatchFrozen = frozen;
3887 changed = true;
3888 } else {
3889 changed = false;
3890 }
3891
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003892 if (DEBUG_FOCUS) {
3893 logDispatchStateLocked();
3894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895 } // release lock
3896
3897 if (changed) {
3898 // Wake up poll loop since it may need to make new input dispatching choices.
3899 mLooper->wake();
3900 }
3901}
3902
3903void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003904 if (DEBUG_FOCUS) {
3905 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907
3908 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003909 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910
3911 if (mInputFilterEnabled == enabled) {
3912 return;
3913 }
3914
3915 mInputFilterEnabled = enabled;
3916 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3917 } // release lock
3918
3919 // Wake up poll loop since there might be work to do to drop everything.
3920 mLooper->wake();
3921}
3922
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003923void InputDispatcher::setInTouchMode(bool inTouchMode) {
3924 std::scoped_lock lock(mLock);
3925 mInTouchMode = inTouchMode;
3926}
3927
chaviwfbe5d9c2018-12-26 12:23:37 -08003928bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3929 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003930 if (DEBUG_FOCUS) {
3931 ALOGD("Trivial transfer to same window.");
3932 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003933 return true;
3934 }
3935
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003937 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938
chaviwfbe5d9c2018-12-26 12:23:37 -08003939 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3940 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003941 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003942 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 return false;
3944 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003945 if (DEBUG_FOCUS) {
3946 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3947 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003950 if (DEBUG_FOCUS) {
3951 ALOGD("Cannot transfer focus because windows are on different displays.");
3952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 return false;
3954 }
3955
3956 bool found = false;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003957 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
3958 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003959 for (size_t i = 0; i < state.windows.size(); i++) {
3960 const TouchedWindow& touchedWindow = state.windows[i];
3961 if (touchedWindow.windowHandle == fromWindowHandle) {
3962 int32_t oldTargetFlags = touchedWindow.targetFlags;
3963 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003965 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003967 int32_t newTargetFlags = oldTargetFlags &
3968 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3969 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003970 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971
Jeff Brownf086ddb2014-02-11 14:28:48 -08003972 found = true;
3973 goto Found;
3974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 }
3976 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003977 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003979 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003980 if (DEBUG_FOCUS) {
3981 ALOGD("Focus transfer failed because from window did not have focus.");
3982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 return false;
3984 }
3985
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003986 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3987 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003988 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003989 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003990 CancelationOptions
3991 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3992 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003994 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 }
3996
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003997 if (DEBUG_FOCUS) {
3998 logDispatchStateLocked();
3999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000 } // release lock
4001
4002 // Wake up poll loop since it may need to make new input dispatching choices.
4003 mLooper->wake();
4004 return true;
4005}
4006
4007void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004008 if (DEBUG_FOCUS) {
4009 ALOGD("Resetting and dropping all events (%s).", reason);
4010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011
4012 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4013 synthesizeCancelationEventsForAllConnectionsLocked(options);
4014
4015 resetKeyRepeatLocked();
4016 releasePendingEventLocked();
4017 drainInboundQueueLocked();
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004018 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019
Jeff Brownf086ddb2014-02-11 14:28:48 -08004020 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004022 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023}
4024
4025void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004026 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027 dumpDispatchStateLocked(dump);
4028
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004029 std::istringstream stream(dump);
4030 std::string line;
4031
4032 while (std::getline(stream, line, '\n')) {
4033 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034 }
4035}
4036
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004037void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004038 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4039 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4040 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004041 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042
Tiger Huang721e26f2018-07-24 22:26:19 +08004043 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4044 dump += StringPrintf(INDENT "FocusedApplications:\n");
4045 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4046 const int32_t displayId = it.first;
4047 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004048 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004049 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004050 displayId, applicationHandle->getName().c_str(),
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004051 ns2ms(applicationHandle
4052 ->getDispatchingTimeout(
4053 DEFAULT_INPUT_DISPATCHING_TIMEOUT)
4054 .count()));
Tiger Huang721e26f2018-07-24 22:26:19 +08004055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004057 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004059
4060 if (!mFocusedWindowHandlesByDisplay.empty()) {
4061 dump += StringPrintf(INDENT "FocusedWindows:\n");
4062 for (auto& it : mFocusedWindowHandlesByDisplay) {
4063 const int32_t displayId = it.first;
4064 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004065 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4066 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004067 }
4068 } else {
4069 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004072 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004073 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004074 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4075 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004076 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004077 state.displayId, toString(state.down), toString(state.split),
4078 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004079 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004080 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004081 for (size_t i = 0; i < state.windows.size(); i++) {
4082 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004083 dump += StringPrintf(INDENT4
4084 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4085 i, touchedWindow.windowHandle->getName().c_str(),
4086 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004087 }
4088 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004089 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004090 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004091 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004092 dump += INDENT3 "Portal windows:\n";
4093 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004094 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004095 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4096 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004097 }
4098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099 }
4100 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004101 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102 }
4103
Arthur Hungb92218b2018-08-14 12:00:21 +08004104 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004105 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004106 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004107 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004108 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004109 dump += INDENT2 "Windows:\n";
4110 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004111 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004112 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113
Arthur Hungb92218b2018-08-14 12:00:21 +08004114 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004115 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004116 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4117 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004118 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004119 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004120 i, windowInfo->name.c_str(), windowInfo->displayId,
4121 windowInfo->portalToDisplayId,
4122 toString(windowInfo->paused),
4123 toString(windowInfo->hasFocus),
4124 toString(windowInfo->hasWallpaper),
4125 toString(windowInfo->visible),
4126 toString(windowInfo->canReceiveKeys),
4127 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004128 windowInfo->layoutParamsType, windowInfo->frameLeft,
4129 windowInfo->frameTop, windowInfo->frameRight,
4130 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4131 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004132 dumpRegion(dump, windowInfo->touchableRegion);
4133 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004134 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4135 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004136 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004137 ns2ms(windowInfo->dispatchingTimeout));
Arthur Hungb92218b2018-08-14 12:00:21 +08004138 }
4139 } else {
4140 dump += INDENT2 "Windows: <none>\n";
4141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 }
4143 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004144 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145 }
4146
Michael Wright3dd60e22019-03-27 22:06:44 +00004147 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004148 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004149 const std::vector<Monitor>& monitors = it.second;
4150 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4151 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004152 }
4153 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004154 const std::vector<Monitor>& monitors = it.second;
4155 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4156 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004159 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 }
4161
4162 nsecs_t currentTime = now();
4163
4164 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004165 if (!mRecentQueue.empty()) {
4166 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4167 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004168 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004170 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 }
4172 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004173 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 }
4175
4176 // Dump event currently being dispatched.
4177 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004178 dump += INDENT "PendingEvent:\n";
4179 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004181 dump += StringPrintf(", age=%" PRId64 "ms\n",
4182 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004184 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 }
4186
4187 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004188 if (!mInboundQueue.empty()) {
4189 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4190 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004191 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004193 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 }
4195 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004196 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197 }
4198
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004199 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004200 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004201 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4202 const KeyReplacement& replacement = pair.first;
4203 int32_t newKeyCode = pair.second;
4204 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004205 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004206 }
4207 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004208 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004209 }
4210
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004211 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004212 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004213 for (const auto& pair : mConnectionsByFd) {
4214 const sp<Connection>& connection = pair.second;
4215 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
4216 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
4217 pair.first, connection->getInputChannelName().c_str(),
4218 connection->getWindowName().c_str(), connection->getStatusLabel(),
4219 toString(connection->monitor),
4220 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004222 if (!connection->outboundQueue.empty()) {
4223 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4224 connection->outboundQueue.size());
4225 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 dump.append(INDENT4);
4227 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004228 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4229 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004230 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004231 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 }
4233 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004234 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 }
4236
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004237 if (!connection->waitQueue.empty()) {
4238 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4239 connection->waitQueue.size());
4240 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004241 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004243 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004244 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004245 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004246 ns2ms(currentTime - entry->eventEntry->eventTime),
4247 ns2ms(currentTime - entry->deliveryTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 }
4249 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004250 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 }
4252 }
4253 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004254 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 }
4256
4257 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004258 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4259 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004261 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 }
4263
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004264 dump += INDENT "Configuration:\n";
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004265 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4266 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4267 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268}
4269
Michael Wright3dd60e22019-03-27 22:06:44 +00004270void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4271 const size_t numMonitors = monitors.size();
4272 for (size_t i = 0; i < numMonitors; i++) {
4273 const Monitor& monitor = monitors[i];
4274 const sp<InputChannel>& channel = monitor.inputChannel;
4275 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4276 dump += "\n";
4277 }
4278}
4279
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004280status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004282 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283#endif
4284
4285 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004286 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004287 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004288 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004290 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 return BAD_VALUE;
4292 }
4293
Garfield Tan1c7bc862020-01-28 13:24:04 -08004294 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295
4296 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004297 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004298 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4301 } // release lock
4302
4303 // Wake the looper because some connections have changed.
4304 mLooper->wake();
4305 return OK;
4306}
4307
Michael Wright3dd60e22019-03-27 22:06:44 +00004308status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004309 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004310 { // acquire lock
4311 std::scoped_lock _l(mLock);
4312
4313 if (displayId < 0) {
4314 ALOGW("Attempted to register input monitor without a specified display.");
4315 return BAD_VALUE;
4316 }
4317
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004318 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004319 ALOGW("Attempted to register input monitor without an identifying token.");
4320 return BAD_VALUE;
4321 }
4322
Garfield Tan1c7bc862020-01-28 13:24:04 -08004323 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004324
4325 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004326 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004327 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004328
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004329 auto& monitorsByDisplay =
4330 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004331 monitorsByDisplay[displayId].emplace_back(inputChannel);
4332
4333 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004334 }
4335 // Wake the looper because some connections have changed.
4336 mLooper->wake();
4337 return OK;
4338}
4339
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4341#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004342 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343#endif
4344
4345 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004346 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347
4348 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4349 if (status) {
4350 return status;
4351 }
4352 } // release lock
4353
4354 // Wake the poll loop because removing the connection may have changed the current
4355 // synchronization state.
4356 mLooper->wake();
4357 return OK;
4358}
4359
4360status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004361 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004362 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004363 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004365 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 return BAD_VALUE;
4367 }
4368
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004369 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004370 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004371
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 if (connection->monitor) {
4373 removeMonitorChannelLocked(inputChannel);
4374 }
4375
4376 mLooper->removeFd(inputChannel->getFd());
4377
4378 nsecs_t currentTime = now();
4379 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4380
4381 connection->status = Connection::STATUS_ZOMBIE;
4382 return OK;
4383}
4384
4385void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004386 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4387 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4388}
4389
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004390void InputDispatcher::removeMonitorChannelLocked(
4391 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004392 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004393 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004394 std::vector<Monitor>& monitors = it->second;
4395 const size_t numMonitors = monitors.size();
4396 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004397 if (monitors[i].inputChannel == inputChannel) {
4398 monitors.erase(monitors.begin() + i);
4399 break;
4400 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004401 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004402 if (monitors.empty()) {
4403 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004404 } else {
4405 ++it;
4406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 }
4408}
4409
Michael Wright3dd60e22019-03-27 22:06:44 +00004410status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4411 { // acquire lock
4412 std::scoped_lock _l(mLock);
4413 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4414
4415 if (!foundDisplayId) {
4416 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4417 return BAD_VALUE;
4418 }
4419 int32_t displayId = foundDisplayId.value();
4420
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004421 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4422 mTouchStatesByDisplay.find(displayId);
4423 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004424 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4425 return BAD_VALUE;
4426 }
4427
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004428 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004429 std::optional<int32_t> foundDeviceId;
4430 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004431 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004432 foundDeviceId = state.deviceId;
4433 }
4434 }
4435 if (!foundDeviceId || !state.down) {
4436 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004437 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004438 return BAD_VALUE;
4439 }
4440 int32_t deviceId = foundDeviceId.value();
4441
4442 // Send cancel events to all the input channels we're stealing from.
4443 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004444 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004445 options.deviceId = deviceId;
4446 options.displayId = displayId;
4447 for (const TouchedWindow& window : state.windows) {
4448 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004449 if (channel != nullptr) {
4450 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4451 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004452 }
4453 // Then clear the current touch state so we stop dispatching to them as well.
4454 state.filterNonMonitors();
4455 }
4456 return OK;
4457}
4458
Michael Wright3dd60e22019-03-27 22:06:44 +00004459std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4460 const sp<IBinder>& token) {
4461 for (const auto& it : mGestureMonitorsByDisplay) {
4462 const std::vector<Monitor>& monitors = it.second;
4463 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004464 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004465 return it.first;
4466 }
4467 }
4468 }
4469 return std::nullopt;
4470}
4471
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004472sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004473 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004474 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004475 }
4476
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004477 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004478 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004479 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004480 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481 }
4482 }
Robert Carr4e670e52018-08-15 13:26:12 -07004483
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004484 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485}
4486
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004487void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
4488 removeByValue(mConnectionsByFd, connection);
4489}
4490
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004491void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4492 const sp<Connection>& connection, uint32_t seq,
4493 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004494 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4495 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 commandEntry->connection = connection;
4497 commandEntry->eventTime = currentTime;
4498 commandEntry->seq = seq;
4499 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004500 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501}
4502
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004503void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4504 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004506 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004508 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4509 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004511 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512}
4513
chaviw0c06c6e2019-01-09 13:27:07 -08004514void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004515 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004516 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4517 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004518 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4519 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004520 commandEntry->oldToken = oldToken;
4521 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004522 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004523}
4524
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004525void InputDispatcher::onAnrLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004526 const sp<InputApplicationHandle>& applicationHandle,
4527 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4528 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4530 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4531 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004532 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4533 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4534 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535
4536 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004537 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 struct tm tm;
4539 localtime_r(&t, &tm);
4540 char timestr[64];
4541 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004542 mLastAnrState.clear();
4543 mLastAnrState += INDENT "ANR:\n";
4544 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
4545 mLastAnrState +=
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004546 StringPrintf(INDENT2 "Window: %s\n",
4547 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004548 mLastAnrState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4549 mLastAnrState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4550 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason);
4551 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004553 std::unique_ptr<CommandEntry> commandEntry =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004554 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004556 commandEntry->inputChannel =
4557 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004559 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560}
4561
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004562void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 mLock.unlock();
4564
4565 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4566
4567 mLock.lock();
4568}
4569
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004570void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571 sp<Connection> connection = commandEntry->connection;
4572
4573 if (connection->status != Connection::STATUS_ZOMBIE) {
4574 mLock.unlock();
4575
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004576 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577
4578 mLock.lock();
4579 }
4580}
4581
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004582void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004583 sp<IBinder> oldToken = commandEntry->oldToken;
4584 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004585 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004586 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004587 mLock.lock();
4588}
4589
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004590void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004591 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004592 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593 mLock.unlock();
4594
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004595 const nsecs_t timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004596 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597
4598 mLock.lock();
4599
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004600 resumeAfterTargetsNotReadyTimeoutLocked(timeoutExtension, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601}
4602
4603void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4604 CommandEntry* commandEntry) {
4605 KeyEntry* entry = commandEntry->keyEntry;
4606
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004607 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608
4609 mLock.unlock();
4610
Michael Wright2b3c3302018-03-02 17:19:13 +00004611 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004612 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004613 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004614 : nullptr;
4615 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004616 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4617 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004618 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620
4621 mLock.lock();
4622
4623 if (delay < 0) {
4624 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4625 } else if (!delay) {
4626 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4627 } else {
4628 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4629 entry->interceptKeyWakeupTime = now() + delay;
4630 }
4631 entry->release();
4632}
4633
chaviwfd6d3512019-03-25 13:23:49 -07004634void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4635 mLock.unlock();
4636 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4637 mLock.lock();
4638}
4639
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004640void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004642 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004644 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645
4646 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004647 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004648 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004649 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004651 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004652
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004653 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004654 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004655 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4656 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004657 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004658 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004659
4660 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004661 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004662 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4663 restartEvent =
4664 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004665 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004666 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4667 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4668 handled);
4669 } else {
4670 restartEvent = false;
4671 }
4672
4673 // Dequeue the event and start the next cycle.
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004674 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004675 // contents of the wait queue to have been drained, so we need to double-check
4676 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004677 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4678 if (dispatchEntryIt != connection->waitQueue.end()) {
4679 dispatchEntry = *dispatchEntryIt;
4680 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004681 traceWaitQueueLength(connection);
4682 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004683 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004684 traceOutboundQueueLength(connection);
4685 } else {
4686 releaseDispatchEntry(dispatchEntry);
4687 }
4688 }
4689
4690 // Start the next dispatch cycle for this connection.
4691 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692}
4693
4694bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004695 DispatchEntry* dispatchEntry,
4696 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004697 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004698 if (!handled) {
4699 // Report the key as unhandled, since the fallback was not handled.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004700 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004701 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004702 return false;
4703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004705 // Get the fallback key state.
4706 // Clear it out after dispatching the UP.
4707 int32_t originalKeyCode = keyEntry->keyCode;
4708 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4709 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4710 connection->inputState.removeFallbackKey(originalKeyCode);
4711 }
4712
4713 if (handled || !dispatchEntry->hasForegroundTarget()) {
4714 // If the application handles the original key for which we previously
4715 // generated a fallback or if the window is not a foreground window,
4716 // then cancel the associated fallback key, if any.
4717 if (fallbackKeyCode != -1) {
4718 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004720 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004721 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4722 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4723 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004725 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004726 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727
4728 mLock.unlock();
4729
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004730 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004731 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732
4733 mLock.lock();
4734
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004735 // Cancel the fallback key.
4736 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004738 "application handled the original non-fallback key "
4739 "or is no longer a foreground target, "
4740 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741 options.keyCode = fallbackKeyCode;
4742 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004744 connection->inputState.removeFallbackKey(originalKeyCode);
4745 }
4746 } else {
4747 // If the application did not handle a non-fallback key, first check
4748 // that we are in a good state to perform unhandled key event processing
4749 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004750 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004751 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004753 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004754 "since this is not an initial down. "
4755 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4756 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004758 return false;
4759 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004761 // Dispatch the unhandled key to the policy.
4762#if DEBUG_OUTBOUND_EVENT_DETAILS
4763 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004764 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4765 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004766#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004767 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004768
4769 mLock.unlock();
4770
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004771 bool fallback =
4772 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4773 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004774
4775 mLock.lock();
4776
4777 if (connection->status != Connection::STATUS_NORMAL) {
4778 connection->inputState.removeFallbackKey(originalKeyCode);
4779 return false;
4780 }
4781
4782 // Latch the fallback keycode for this key on an initial down.
4783 // The fallback keycode cannot change at any other point in the lifecycle.
4784 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004786 fallbackKeyCode = event.getKeyCode();
4787 } else {
4788 fallbackKeyCode = AKEYCODE_UNKNOWN;
4789 }
4790 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4791 }
4792
4793 ALOG_ASSERT(fallbackKeyCode != -1);
4794
4795 // Cancel the fallback key if the policy decides not to send it anymore.
4796 // We will continue to dispatch the key to the policy but we will no
4797 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004798 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4799 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004800#if DEBUG_OUTBOUND_EVENT_DETAILS
4801 if (fallback) {
4802 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004803 "as a fallback for %d, but on the DOWN it had requested "
4804 "to send %d instead. Fallback canceled.",
4805 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004806 } else {
4807 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004808 "but on the DOWN it had requested to send %d. "
4809 "Fallback canceled.",
4810 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004811 }
4812#endif
4813
4814 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4815 "canceling fallback, policy no longer desires it");
4816 options.keyCode = fallbackKeyCode;
4817 synthesizeCancelationEventsForConnectionLocked(connection, options);
4818
4819 fallback = false;
4820 fallbackKeyCode = AKEYCODE_UNKNOWN;
4821 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004822 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004823 }
4824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825
4826#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004827 {
4828 std::string msg;
4829 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4830 connection->inputState.getFallbackKeys();
4831 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004832 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004834 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004835 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004836 }
4837#endif
4838
4839 if (fallback) {
4840 // Restart the dispatch cycle using the fallback key.
4841 keyEntry->eventTime = event.getEventTime();
4842 keyEntry->deviceId = event.getDeviceId();
4843 keyEntry->source = event.getSource();
4844 keyEntry->displayId = event.getDisplayId();
4845 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4846 keyEntry->keyCode = fallbackKeyCode;
4847 keyEntry->scanCode = event.getScanCode();
4848 keyEntry->metaState = event.getMetaState();
4849 keyEntry->repeatCount = event.getRepeatCount();
4850 keyEntry->downTime = event.getDownTime();
4851 keyEntry->syntheticRepeat = false;
4852
4853#if DEBUG_OUTBOUND_EVENT_DETAILS
4854 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004855 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4856 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004857#endif
4858 return true; // restart the event
4859 } else {
4860#if DEBUG_OUTBOUND_EVENT_DETAILS
4861 ALOGD("Unhandled key event: No fallback key.");
4862#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004863
4864 // Report the key as unhandled, since there is no fallback key.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004865 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 }
4867 }
4868 return false;
4869}
4870
4871bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004872 DispatchEntry* dispatchEntry,
4873 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874 return false;
4875}
4876
4877void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4878 mLock.unlock();
4879
4880 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4881
4882 mLock.lock();
4883}
4884
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004885KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4886 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004887 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08004888 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
4889 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004890 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891}
4892
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004893void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
4894 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895 // TODO Write some statistics about how long we spend waiting.
4896}
4897
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004898/**
4899 * Report the touch event latency to the statsd server.
4900 * Input events are reported for statistics if:
4901 * - This is a touchscreen event
4902 * - InputFilter is not enabled
4903 * - Event is not injected or synthesized
4904 *
4905 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4906 * from getting aggregated with the "old" data.
4907 */
4908void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4909 REQUIRES(mLock) {
4910 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4911 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4912 if (!reportForStatistics) {
4913 return;
4914 }
4915
4916 if (mTouchStatistics.shouldReport()) {
4917 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4918 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4919 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4920 mTouchStatistics.reset();
4921 }
4922 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4923 mTouchStatistics.addValue(latencyMicros);
4924}
4925
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926void InputDispatcher::traceInboundQueueLengthLocked() {
4927 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004928 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929 }
4930}
4931
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004932void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933 if (ATRACE_ENABLED()) {
4934 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004935 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004936 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004937 }
4938}
4939
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004940void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941 if (ATRACE_ENABLED()) {
4942 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004943 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004944 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945 }
4946}
4947
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004948void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004949 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004951 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952 dumpDispatchStateLocked(dump);
4953
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004954 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004955 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004956 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004957 }
4958}
4959
4960void InputDispatcher::monitor() {
4961 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004962 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004964 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965}
4966
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004967/**
4968 * Wake up the dispatcher and wait until it processes all events and commands.
4969 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4970 * this method can be safely called from any thread, as long as you've ensured that
4971 * the work you are interested in completing has already been queued.
4972 */
4973bool InputDispatcher::waitForIdle() {
4974 /**
4975 * Timeout should represent the longest possible time that a device might spend processing
4976 * events and commands.
4977 */
4978 constexpr std::chrono::duration TIMEOUT = 100ms;
4979 std::unique_lock lock(mLock);
4980 mLooper->wake();
4981 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4982 return result == std::cv_status::no_timeout;
4983}
4984
Garfield Tane84e6f92019-08-29 17:28:41 -07004985} // namespace android::inputdispatcher