blob: 959eeea41e47f97eec906a6b280bbac1dbf3c940 [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>
Siarhei Vishniakou7394eaa2020-04-09 11:16:18 -070065#include <log/log_event_list.h>
Gang Wang342c9272020-01-13 13:15:04 -050066#include <openssl/hmac.h>
67#include <openssl/rand.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070068#include <powermanager/PowerManager.h>
69#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080070
71#define INDENT " "
72#define INDENT2 " "
73#define INDENT3 " "
74#define INDENT4 " "
75
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080076using android::base::StringPrintf;
77
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Default input dispatching timeout if there is no focused application or paused window
81// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -070082constexpr std::chrono::nanoseconds DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5s;
Michael Wrightd02c5b62014-02-10 15:10:22 -080083
84// Amount of time to allow for all pending events to be processed when an app switch
85// key is on the way. This is used to preempt input dispatch and drop input events
86// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000087constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080088
89// Amount of time to allow for an event to be dispatched (measured since its eventTime)
90// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000091constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
93// Amount of time to allow touch events to be streamed out to a connection before requiring
94// that the first event be finished. This value extends the ANR timeout by the specified
95// amount. For example, if streaming is allowed to get ahead by one second relative to the
96// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000097constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080098
99// 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 +0000100constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
101
102// Log a warning when an interception call takes longer than this to process.
103constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104
105// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
107
Siarhei Vishniakou7394eaa2020-04-09 11:16:18 -0700108// Event log tags. See EventLogTags.logtags for reference
109constexpr int LOGTAG_INPUT_INTERACTION = 62000;
110constexpr int LOGTAG_INPUT_FOCUS = 62001;
111
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112static inline nsecs_t now() {
113 return systemTime(SYSTEM_TIME_MONOTONIC);
114}
115
116static inline const char* toString(bool value) {
117 return value ? "true" : "false";
118}
119
120static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700121 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
122 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123}
124
125static bool isValidKeyAction(int32_t action) {
126 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700127 case AKEY_EVENT_ACTION_DOWN:
128 case AKEY_EVENT_ACTION_UP:
129 return true;
130 default:
131 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 }
133}
134
135static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700136 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137 ALOGE("Key event has invalid action code 0x%x", action);
138 return false;
139 }
140 return true;
141}
142
Michael Wright7b159c92015-05-14 14:48:03 +0100143static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700145 case AMOTION_EVENT_ACTION_DOWN:
146 case AMOTION_EVENT_ACTION_UP:
147 case AMOTION_EVENT_ACTION_CANCEL:
148 case AMOTION_EVENT_ACTION_MOVE:
149 case AMOTION_EVENT_ACTION_OUTSIDE:
150 case AMOTION_EVENT_ACTION_HOVER_ENTER:
151 case AMOTION_EVENT_ACTION_HOVER_MOVE:
152 case AMOTION_EVENT_ACTION_HOVER_EXIT:
153 case AMOTION_EVENT_ACTION_SCROLL:
154 return true;
155 case AMOTION_EVENT_ACTION_POINTER_DOWN:
156 case AMOTION_EVENT_ACTION_POINTER_UP: {
157 int32_t index = getMotionEventActionPointerIndex(action);
158 return index >= 0 && index < pointerCount;
159 }
160 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
161 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
162 return actionButton != 0;
163 default:
164 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 }
166}
167
Michael Wright7b159c92015-05-14 14:48:03 +0100168static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700169 const PointerProperties* pointerProperties) {
170 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800171 ALOGE("Motion event has invalid action code 0x%x", action);
172 return false;
173 }
174 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000175 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 return false;
178 }
179 BitSet32 pointerIdBits;
180 for (size_t i = 0; i < pointerCount; i++) {
181 int32_t id = pointerProperties[i].id;
182 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
184 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 return false;
186 }
187 if (pointerIdBits.hasBit(id)) {
188 ALOGE("Motion event has duplicate pointer id %d", id);
189 return false;
190 }
191 pointerIdBits.markBit(id);
192 }
193 return true;
194}
195
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800196static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800197 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800198 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 return;
200 }
201
202 bool first = true;
203 Region::const_iterator cur = region.begin();
204 Region::const_iterator const tail = region.end();
205 while (cur != tail) {
206 if (first) {
207 first = false;
208 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800209 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800211 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 cur++;
213 }
214}
215
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700216/**
217 * Find the entry in std::unordered_map by key, and return it.
218 * If the entry is not found, return a default constructed entry.
219 *
220 * Useful when the entries are vectors, since an empty vector will be returned
221 * if the entry is not found.
222 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
223 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700224template <typename K, typename V>
225static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700226 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700227 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800228}
229
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700230/**
231 * Find the entry in std::unordered_map by value, and remove it.
232 * If more than one entry has the same value, then all matching
233 * key-value pairs will be removed.
234 *
235 * Return true if at least one value has been removed.
236 */
237template <typename K, typename V>
238static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
239 bool removed = false;
240 for (auto it = map.begin(); it != map.end();) {
241 if (it->second == value) {
242 it = map.erase(it);
243 removed = true;
244 } else {
245 it++;
246 }
247 }
248 return removed;
249}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800250
chaviwaf87b3e2019-10-01 16:59:28 -0700251static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
252 if (first == second) {
253 return true;
254 }
255
256 if (first == nullptr || second == nullptr) {
257 return false;
258 }
259
260 return first->getToken() == second->getToken();
261}
262
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800263static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
264 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
265}
266
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000267static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
268 EventEntry* eventEntry,
269 int32_t inputTargetFlags) {
270 if (inputTarget.useDefaultPointerInfo()) {
271 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
272 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
273 inputTargetFlags, pointerInfo.xOffset,
274 pointerInfo.yOffset, inputTarget.globalScaleFactor,
275 pointerInfo.windowXScale, pointerInfo.windowYScale);
276 }
277
278 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
279 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
280
281 PointerCoords pointerCoords[motionEntry.pointerCount];
282
283 // Use the first pointer information to normalize all other pointers. This could be any pointer
284 // as long as all other pointers are normalized to the same value and the final DispatchEntry
285 // uses the offset and scale for the normalized pointer.
286 const PointerInfo& firstPointerInfo =
287 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
288
289 // Iterate through all pointers in the event to normalize against the first.
290 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
291 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
292 uint32_t pointerId = uint32_t(pointerProperties.id);
293 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
294
295 // The scale factor is the ratio of the current pointers scale to the normalized scale.
296 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
297 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
298
299 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
300 // First apply the current pointers offset to set the window at 0,0
301 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
302 // Next scale the coordinates.
303 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
304 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
305 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
306 -firstPointerInfo.yOffset);
307 }
308
309 MotionEntry* combinedMotionEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800310 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000311 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
312 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
313 motionEntry.metaState, motionEntry.buttonState,
314 motionEntry.classification, motionEntry.edgeFlags,
315 motionEntry.xPrecision, motionEntry.yPrecision,
316 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
317 motionEntry.downTime, motionEntry.pointerCount,
318 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
319 0 /* yOffset */);
320
321 if (motionEntry.injectionState) {
322 combinedMotionEntry->injectionState = motionEntry.injectionState;
323 combinedMotionEntry->injectionState->refCount += 1;
324 }
325
326 std::unique_ptr<DispatchEntry> dispatchEntry =
327 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
328 inputTargetFlags, firstPointerInfo.xOffset,
329 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
330 firstPointerInfo.windowXScale,
331 firstPointerInfo.windowYScale);
332 combinedMotionEntry->release();
333 return dispatchEntry;
334}
335
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -0700336static void addGestureMonitors(const std::vector<Monitor>& monitors,
337 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
338 float yOffset = 0) {
339 if (monitors.empty()) {
340 return;
341 }
342 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
343 for (const Monitor& monitor : monitors) {
344 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
345 }
346}
347
Gang Wang342c9272020-01-13 13:15:04 -0500348static std::array<uint8_t, 128> getRandomKey() {
349 std::array<uint8_t, 128> key;
350 if (RAND_bytes(key.data(), key.size()) != 1) {
351 LOG_ALWAYS_FATAL("Can't generate HMAC key");
352 }
353 return key;
354}
355
356// --- HmacKeyManager ---
357
358HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
359
360std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
361 size_t size;
362 switch (event.type) {
363 case VerifiedInputEvent::Type::KEY: {
364 size = sizeof(VerifiedKeyEvent);
365 break;
366 }
367 case VerifiedInputEvent::Type::MOTION: {
368 size = sizeof(VerifiedMotionEvent);
369 break;
370 }
371 }
Gang Wang342c9272020-01-13 13:15:04 -0500372 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700373 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500374}
375
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700376std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500377 // SHA256 always generates 32-bytes result
378 std::array<uint8_t, 32> hash;
379 unsigned int hashLen = 0;
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700380 uint8_t* result =
381 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500382 if (result == nullptr) {
383 ALOGE("Could not sign the data using HMAC");
384 return INVALID_HMAC;
385 }
386
387 if (hashLen != hash.size()) {
388 ALOGE("HMAC-SHA256 has unexpected length");
389 return INVALID_HMAC;
390 }
391
392 return hash;
393}
394
Michael Wrightd02c5b62014-02-10 15:10:22 -0800395// --- InputDispatcher ---
396
Garfield Tan00f511d2019-06-12 16:55:40 -0700397InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
398 : mPolicy(policy),
399 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700400 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tan1c7bc862020-01-28 13:24:04 -0800401 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700402 mAppSwitchSawKeyDown(false),
403 mAppSwitchDueTime(LONG_LONG_MAX),
404 mNextUnblockedEvent(nullptr),
405 mDispatchEnabled(false),
406 mDispatchFrozen(false),
407 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800408 // mInTouchMode will be initialized by the WindowManager to the default device config.
409 // To avoid leaking stack in case that call never comes, and for tests,
410 // initialize it here anyways.
411 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700412 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
413 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800415 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800416
Yi Kong9b14ac62018-07-17 13:48:38 -0700417 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418
419 policy->getDispatcherConfiguration(&mConfig);
420}
421
422InputDispatcher::~InputDispatcher() {
423 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800424 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800425
426 resetKeyRepeatLocked();
427 releasePendingEventLocked();
428 drainInboundQueueLocked();
429 }
430
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700431 while (!mConnectionsByFd.empty()) {
432 sp<Connection> connection = mConnectionsByFd.begin()->second;
433 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800434 }
435}
436
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700437status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700438 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700439 return ALREADY_EXISTS;
440 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700441 mThread = std::make_unique<InputThread>(
442 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
443 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700444}
445
446status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700447 if (mThread && mThread->isCallingThread()) {
448 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700449 return INVALID_OPERATION;
450 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700451 mThread.reset();
452 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700453}
454
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455void InputDispatcher::dispatchOnce() {
456 nsecs_t nextWakeupTime = LONG_LONG_MAX;
457 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800458 std::scoped_lock _l(mLock);
459 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800460
461 // Run a dispatch loop if there are no pending commands.
462 // The dispatch loop might enqueue commands to run afterwards.
463 if (!haveCommandsLocked()) {
464 dispatchOnceInnerLocked(&nextWakeupTime);
465 }
466
467 // Run all pending commands if there are any.
468 // If any commands were run then force the next poll to wake up immediately.
469 if (runCommandsLockedInterruptible()) {
470 nextWakeupTime = LONG_LONG_MIN;
471 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800472
473 // We are about to enter an infinitely long sleep, because we have no commands or
474 // pending or queued events
475 if (nextWakeupTime == LONG_LONG_MAX) {
476 mDispatcherEnteredIdle.notify_all();
477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478 } // release lock
479
480 // Wait for callback or timeout or wake. (make sure we round up, not down)
481 nsecs_t currentTime = now();
482 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
483 mLooper->pollOnce(timeoutMillis);
484}
485
486void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
487 nsecs_t currentTime = now();
488
Jeff Browndc5992e2014-04-11 01:27:26 -0700489 // Reset the key repeat timer whenever normal dispatch is suspended while the
490 // device is in a non-interactive state. This is to ensure that we abort a key
491 // repeat if the device is just coming out of sleep.
492 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 resetKeyRepeatLocked();
494 }
495
496 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
497 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100498 if (DEBUG_FOCUS) {
499 ALOGD("Dispatch frozen. Waiting some more.");
500 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800501 return;
502 }
503
504 // Optimize latency of app switches.
505 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
506 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
507 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
508 if (mAppSwitchDueTime < *nextWakeupTime) {
509 *nextWakeupTime = mAppSwitchDueTime;
510 }
511
512 // Ready to start a new event.
513 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700514 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700515 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516 if (isAppSwitchDue) {
517 // The inbound queue is empty so the app switch key we were waiting
518 // for will never arrive. Stop waiting for it.
519 resetPendingAppSwitchLocked(false);
520 isAppSwitchDue = false;
521 }
522
523 // Synthesize a key repeat if appropriate.
524 if (mKeyRepeatState.lastKeyEntry) {
525 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
526 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
527 } else {
528 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
529 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
530 }
531 }
532 }
533
534 // Nothing to do if there is no pending event.
535 if (!mPendingEvent) {
536 return;
537 }
538 } else {
539 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700540 mPendingEvent = mInboundQueue.front();
541 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800542 traceInboundQueueLengthLocked();
543 }
544
545 // Poke user activity for this event.
546 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700547 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548 }
549
550 // Get ready to dispatch the event.
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700551 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 }
553
554 // Now we have an event to dispatch.
555 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700556 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700558 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700560 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700562 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 }
564
565 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700566 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 }
568
569 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700570 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700571 ConfigurationChangedEntry* typedEntry =
572 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
573 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700574 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700575 break;
576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700578 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700579 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
580 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700581 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700582 break;
583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800584
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100585 case EventEntry::Type::FOCUS: {
586 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
587 dispatchFocusLocked(currentTime, typedEntry);
588 done = true;
589 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
590 break;
591 }
592
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700593 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700594 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
595 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700596 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700597 resetPendingAppSwitchLocked(true);
598 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700599 } else if (dropReason == DropReason::NOT_DROPPED) {
600 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700601 }
602 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700603 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700604 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700605 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700606 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
607 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700608 }
609 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
610 break;
611 }
612
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700613 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700614 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700615 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
616 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700618 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700619 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700620 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700621 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
622 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700623 }
624 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
625 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 }
628
629 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700630 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700631 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 }
Michael Wright3a981722015-06-10 15:26:13 +0100633 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634
635 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700636 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637 }
638}
639
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700640/**
641 * Return true if the events preceding this incoming motion event should be dropped
642 * Return false otherwise (the default behaviour)
643 */
644bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
645 bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
646 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
647 if (isPointerDownEvent &&
648 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
649 mInputTargetWaitApplicationToken != nullptr) {
650 int32_t displayId = motionEntry.displayId;
651 int32_t x = static_cast<int32_t>(
652 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
653 int32_t y = static_cast<int32_t>(
654 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700655 sp<InputWindowHandle> touchedWindowHandle =
656 findTouchedWindowAtLocked(displayId, x, y, nullptr);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700657 if (touchedWindowHandle != nullptr &&
658 touchedWindowHandle->getApplicationToken() != mInputTargetWaitApplicationToken) {
659 // User touched a different application than the one we are waiting on.
660 // Flag the event, and start pruning the input queue.
661 ALOGI("Pruning input queue because user touched a different application");
662 return true;
663 }
664 }
665 return false;
666}
667
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700669 bool needWake = mInboundQueue.empty();
670 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671 traceInboundQueueLengthLocked();
672
673 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700674 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700675 // Optimize app switch latency.
676 // If the application takes too long to catch up then we drop all events preceding
677 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700678 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700679 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700680 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700681 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700682 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700683 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700685 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700687 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700688 mAppSwitchSawKeyDown = false;
689 needWake = true;
690 }
691 }
692 }
693 break;
694 }
695
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700696 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700697 // Optimize case where the current application is unresponsive and the user
698 // decides to touch a window in a different application.
699 // If the application takes too long to catch up then we drop all events preceding
700 // the touch into the other window.
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700701 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
702 mNextUnblockedEvent = entry;
703 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700705 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100707 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700708 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
709 break;
710 }
711 case EventEntry::Type::CONFIGURATION_CHANGED:
712 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700713 // nothing to do
714 break;
715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 }
717
718 return needWake;
719}
720
721void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
722 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700723 mRecentQueue.push_back(entry);
724 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
725 mRecentQueue.front()->release();
726 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727 }
728}
729
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700730sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700731 int32_t y, TouchState* touchState,
732 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700733 bool addPortalWindows) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700734 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
735 LOG_ALWAYS_FATAL(
736 "Must provide a valid touch state if adding portal windows or outside targets");
737 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800739 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
740 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741 const InputWindowInfo* windowInfo = windowHandle->getInfo();
742 if (windowInfo->displayId == displayId) {
743 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744
745 if (windowInfo->visible) {
746 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700747 bool isTouchModal = (flags &
748 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
749 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800751 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700752 if (portalToDisplayId != ADISPLAY_ID_NONE &&
753 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800754 if (addPortalWindows) {
755 // For the monitoring channels of the display.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700756 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800757 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700758 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700759 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800761 // Found window.
762 return windowHandle;
763 }
764 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800765
766 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700767 touchState->addOrUpdateWindow(windowHandle,
768 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
769 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772 }
773 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700774 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775}
776
Garfield Tane84e6f92019-08-29 17:28:41 -0700777std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -0700778 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000779 std::vector<TouchedMonitor> touchedMonitors;
780
781 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
782 addGestureMonitors(monitors, touchedMonitors);
783 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
784 const InputWindowInfo* windowInfo = portalWindow->getInfo();
785 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700786 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
787 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000788 }
789 return touchedMonitors;
790}
791
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700792void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 const char* reason;
794 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700795 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700797 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700799 reason = "inbound event was dropped because the policy consumed it";
800 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700801 case DropReason::DISABLED:
802 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700803 ALOGI("Dropped event because input dispatch is disabled.");
804 }
805 reason = "inbound event was dropped because input dispatch is disabled";
806 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700807 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700808 ALOGI("Dropped event because of pending overdue app switch.");
809 reason = "inbound event was dropped because of pending overdue app switch";
810 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700811 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 ALOGI("Dropped event because the current application is not responding and the user "
813 "has started interacting with a different application.");
814 reason = "inbound event was dropped because the current application is not responding "
815 "and the user has started interacting with a different application";
816 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700817 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700818 ALOGI("Dropped event because it is stale.");
819 reason = "inbound event was dropped because it is stale";
820 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700821 case DropReason::NOT_DROPPED: {
822 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700823 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825 }
826
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700827 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700828 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
830 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700831 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800832 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700833 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700834 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
835 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700836 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
837 synthesizeCancelationEventsForAllConnectionsLocked(options);
838 } else {
839 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
840 synthesizeCancelationEventsForAllConnectionsLocked(options);
841 }
842 break;
843 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100844 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700845 case EventEntry::Type::CONFIGURATION_CHANGED:
846 case EventEntry::Type::DEVICE_RESET: {
847 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
848 break;
849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850 }
851}
852
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800853static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700854 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
855 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856}
857
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700858bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
859 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
860 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
861 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862}
863
864bool InputDispatcher::isAppSwitchPendingLocked() {
865 return mAppSwitchDueTime != LONG_LONG_MAX;
866}
867
868void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
869 mAppSwitchDueTime = LONG_LONG_MAX;
870
871#if DEBUG_APP_SWITCH
872 if (handled) {
873 ALOGD("App switch has arrived.");
874 } else {
875 ALOGD("App switch was abandoned.");
876 }
877#endif
878}
879
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700881 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882}
883
884bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700885 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 return false;
887 }
888
889 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700890 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700891 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700893 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894
895 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700896 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 return true;
898}
899
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700900void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
901 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902}
903
904void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700905 while (!mInboundQueue.empty()) {
906 EventEntry* entry = mInboundQueue.front();
907 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 releaseInboundEventLocked(entry);
909 }
910 traceInboundQueueLengthLocked();
911}
912
913void InputDispatcher::releasePendingEventLocked() {
914 if (mPendingEvent) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700915 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700917 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800918 }
919}
920
921void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
922 InjectionState* injectionState = entry->injectionState;
923 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
924#if DEBUG_DISPATCH_CYCLE
925 ALOGD("Injected inbound event was dropped.");
926#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800927 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 }
929 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700930 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 }
932 addRecentEventLocked(entry);
933 entry->release();
934}
935
936void InputDispatcher::resetKeyRepeatLocked() {
937 if (mKeyRepeatState.lastKeyEntry) {
938 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700939 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 }
941}
942
Garfield Tane84e6f92019-08-29 17:28:41 -0700943KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
945
946 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700947 uint32_t policyFlags = entry->policyFlags &
948 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 if (entry->refCount == 1) {
950 entry->recycle();
Garfield Tan1c7bc862020-01-28 13:24:04 -0800951 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 entry->eventTime = currentTime;
953 entry->policyFlags = policyFlags;
954 entry->repeatCount += 1;
955 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700956 KeyEntry* newEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -0800957 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800958 entry->displayId, policyFlags, entry->action, entry->flags,
959 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700960 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961
962 mKeyRepeatState.lastKeyEntry = newEntry;
963 entry->release();
964
965 entry = newEntry;
966 }
967 entry->syntheticRepeat = true;
968
969 // Increment reference count since we keep a reference to the event in
970 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
971 entry->refCount += 1;
972
973 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
974 return entry;
975}
976
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
978 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700980 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981#endif
982
983 // Reset key repeating in case a keyboard device was added or removed or something.
984 resetKeyRepeatLocked();
985
986 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700987 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
988 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700990 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 return true;
992}
993
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700994bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700996 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700997 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998#endif
999
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001000 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 options.deviceId = entry->deviceId;
1002 synthesizeCancelationEventsForAllConnectionsLocked(options);
1003 return true;
1004}
1005
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001006void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07001007 if (mPendingEvent != nullptr) {
1008 // Move the pending event to the front of the queue. This will give the chance
1009 // for the pending event to get dispatched to the newly focused window
1010 mInboundQueue.push_front(mPendingEvent);
1011 mPendingEvent = nullptr;
1012 }
1013
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001014 FocusEntry* focusEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08001015 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07001016
1017 // This event should go to the front of the queue, but behind all other focus events
1018 // Find the last focus event, and insert right after it
1019 std::deque<EventEntry*>::reverse_iterator it =
1020 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1021 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1022
1023 // Maintain the order of focus events. Insert the entry after all other focus events.
1024 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001025}
1026
1027void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1028 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1029 if (channel == nullptr) {
1030 return; // Window has gone away
1031 }
1032 InputTarget target;
1033 target.inputChannel = channel;
1034 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1035 entry->dispatchInProgress = true;
Siarhei Vishniakou7394eaa2020-04-09 11:16:18 -07001036 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1037 channel->getName();
1038 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001039 dispatchEventLocked(currentTime, entry, {target});
1040}
1041
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001043 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001045 if (!entry->dispatchInProgress) {
1046 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1047 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1048 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1049 if (mKeyRepeatState.lastKeyEntry &&
1050 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 // We have seen two identical key downs in a row which indicates that the device
1052 // driver is automatically generating key repeats itself. We take note of the
1053 // repeat here, but we disable our own next key repeat timer since it is clear that
1054 // we will not need to synthesize key repeats ourselves.
1055 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1056 resetKeyRepeatLocked();
1057 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1058 } else {
1059 // Not a repeat. Save key down state in case we do see a repeat later.
1060 resetKeyRepeatLocked();
1061 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1062 }
1063 mKeyRepeatState.lastKeyEntry = entry;
1064 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001065 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 resetKeyRepeatLocked();
1067 }
1068
1069 if (entry->repeatCount == 1) {
1070 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1071 } else {
1072 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1073 }
1074
1075 entry->dispatchInProgress = true;
1076
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001077 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078 }
1079
1080 // Handle case where the policy asked us to try again later last time.
1081 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1082 if (currentTime < entry->interceptKeyWakeupTime) {
1083 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1084 *nextWakeupTime = entry->interceptKeyWakeupTime;
1085 }
1086 return false; // wait until next wakeup
1087 }
1088 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1089 entry->interceptKeyWakeupTime = 0;
1090 }
1091
1092 // Give the policy a chance to intercept the key.
1093 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1094 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001095 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001096 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001097 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001098 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001099 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001100 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001101 }
1102 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001103 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104 entry->refCount += 1;
1105 return false; // wait for the command to run
1106 } else {
1107 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1108 }
1109 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001110 if (*dropReason == DropReason::NOT_DROPPED) {
1111 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 }
1113 }
1114
1115 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001116 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001117 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001118 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001119 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001120 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 return true;
1122 }
1123
1124 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001125 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001126 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001127 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1129 return false;
1130 }
1131
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001132 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1134 return true;
1135 }
1136
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001137 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001138 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139
1140 // Dispatch the key.
1141 dispatchEventLocked(currentTime, entry, inputTargets);
1142 return true;
1143}
1144
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001145void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001147 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001148 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1149 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001150 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1151 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1152 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153#endif
1154}
1155
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001156bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1157 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001158 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001160 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 entry->dispatchInProgress = true;
1162
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001163 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 }
1165
1166 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001167 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001168 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001169 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001170 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 return true;
1172 }
1173
1174 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1175
1176 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001177 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178
1179 bool conflictingPointerActions = false;
1180 int32_t injectionResult;
1181 if (isPointerEvent) {
1182 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001183 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001184 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001185 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186 } else {
1187 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001188 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001189 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 }
1191 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1192 return false;
1193 }
1194
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001195 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001196 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1197 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1198 return true;
1199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001201 CancelationOptions::Mode mode(isPointerEvent
1202 ? CancelationOptions::CANCEL_POINTER_EVENTS
1203 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1204 CancelationOptions options(mode, "input event injection failed");
1205 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 return true;
1207 }
1208
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001209 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001210 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001212 if (isPointerEvent) {
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001213 std::unordered_map<int32_t, TouchState>::iterator it =
1214 mTouchStatesByDisplay.find(entry->displayId);
1215 if (it != mTouchStatesByDisplay.end()) {
1216 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001217 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001218 // The event has gone through these portal windows, so we add monitoring targets of
1219 // the corresponding displays as well.
1220 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001221 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001222 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001223 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001224 }
1225 }
1226 }
1227 }
1228
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 // Dispatch the motion.
1230 if (conflictingPointerActions) {
1231 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001232 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 synthesizeCancelationEventsForAllConnectionsLocked(options);
1234 }
1235 dispatchEventLocked(currentTime, entry, inputTargets);
1236 return true;
1237}
1238
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001239void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001241 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001242 ", policyFlags=0x%x, "
1243 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1244 "metaState=0x%x, buttonState=0x%x,"
1245 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001246 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1247 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1248 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001250 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001252 "x=%f, y=%f, pressure=%f, size=%f, "
1253 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1254 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001255 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1256 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1257 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1258 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1259 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1260 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1261 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1262 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1263 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1264 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 }
1266#endif
1267}
1268
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001269void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1270 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001271 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272#if DEBUG_DISPATCH_CYCLE
1273 ALOGD("dispatchEventToCurrentInputTargets");
1274#endif
1275
Siarhei Vishniakou7394eaa2020-04-09 11:16:18 -07001276 updateInteractionTokensLocked(*eventEntry, inputTargets);
1277
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1279
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001280 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001282 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001283 sp<Connection> connection =
1284 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001285 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001286 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001288 if (DEBUG_FOCUS) {
1289 ALOGD("Dropping event delivery to target with channel '%s' because it "
1290 "is no longer registered with the input dispatcher.",
1291 inputTarget.inputChannel->getName().c_str());
1292 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 }
1294 }
1295}
1296
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001297int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001298 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001300 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001301 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001303 if (DEBUG_FOCUS) {
1304 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1307 mInputTargetWaitStartTime = currentTime;
1308 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1309 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001310 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311 }
1312 } else {
1313 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001314 ALOGI("Waiting for application to become ready for input: %s. Reason: %s",
1315 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1316 std::chrono::nanoseconds timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001317 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001319 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001320 timeout =
1321 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 } else {
1323 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1324 }
1325
1326 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1327 mInputTargetWaitStartTime = currentTime;
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001328 mInputTargetWaitTimeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001330 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331
Yi Kong9b14ac62018-07-17 13:48:38 -07001332 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001333 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 }
Robert Carr740167f2018-10-11 19:03:41 -07001335 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1336 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 }
1338 }
1339 }
1340
1341 if (mInputTargetWaitTimeoutExpired) {
1342 return INPUT_EVENT_INJECTION_TIMED_OUT;
1343 }
1344
1345 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001346 onAnrLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001347 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348
1349 // Force poll loop to wake up immediately on next iteration once we get the
1350 // ANR response back from the policy.
1351 *nextWakeupTime = LONG_LONG_MIN;
1352 return INPUT_EVENT_INJECTION_PENDING;
1353 } else {
1354 // Force poll loop to wake up when timeout is due.
1355 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1356 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1357 }
1358 return INPUT_EVENT_INJECTION_PENDING;
1359 }
1360}
1361
Robert Carr803535b2018-08-02 16:38:15 -07001362void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001363 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
1364 TouchState& state = pair.second;
Robert Carr803535b2018-08-02 16:38:15 -07001365 state.removeWindowByToken(token);
1366 }
1367}
1368
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001369void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001370 nsecs_t timeoutExtension, const sp<IBinder>& inputConnectionToken) {
1371 if (timeoutExtension > 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 // Extend the timeout.
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001373 mInputTargetWaitTimeoutTime = now() + timeoutExtension;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374 } else {
1375 // Give up.
1376 mInputTargetWaitTimeoutExpired = true;
1377
1378 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001379 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001380 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001381 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001383 if (connection->status == Connection::STATUS_NORMAL) {
1384 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1385 "application not responding");
1386 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387 }
1388 }
1389 }
1390}
1391
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001392void InputDispatcher::resetAnrTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001393 if (DEBUG_FOCUS) {
1394 ALOGD("Resetting ANR timeouts.");
1395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396
1397 // Reset input target wait timeout.
1398 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001399 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400}
1401
Tiger Huang721e26f2018-07-24 22:26:19 +08001402/**
1403 * Get the display id that the given event should go to. If this event specifies a valid display id,
1404 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1405 * Focused display is the display that the user most recently interacted with.
1406 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001407int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001408 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001409 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001410 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001411 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1412 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001413 break;
1414 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001415 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001416 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1417 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001418 break;
1419 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001420 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001421 case EventEntry::Type::CONFIGURATION_CHANGED:
1422 case EventEntry::Type::DEVICE_RESET: {
1423 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001424 return ADISPLAY_ID_NONE;
1425 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001426 }
1427 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1428}
1429
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001431 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001432 std::vector<InputTarget>& inputTargets,
1433 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001434 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435
Tiger Huang721e26f2018-07-24 22:26:19 +08001436 int32_t displayId = getTargetDisplayId(entry);
1437 sp<InputWindowHandle> focusedWindowHandle =
1438 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1439 sp<InputApplicationHandle> focusedApplicationHandle =
1440 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1441
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 // If there is no currently focused window and no focused application
1443 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001444 if (focusedWindowHandle == nullptr) {
1445 if (focusedApplicationHandle != nullptr) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001446 return handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1447 nullptr, nextWakeupTime,
1448 "Waiting because no window has focus but there is "
1449 "a focused application that may eventually add a "
1450 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 }
1452
Arthur Hung3b413f22018-10-26 18:05:34 +08001453 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001454 "%" PRId32 ".",
1455 displayId);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001456 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457 }
1458
1459 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001460 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001461 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 }
1463
Jeff Brownffb49772014-10-10 19:01:34 -07001464 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001465 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001466 if (!reason.empty()) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001467 return handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1468 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 }
1470
1471 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001472 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001473 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1474 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475
1476 // Done.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001477 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478}
1479
1480int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001481 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001482 std::vector<InputTarget>& inputTargets,
1483 nsecs_t* nextWakeupTime,
1484 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001485 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 enum InjectionPermission {
1487 INJECTION_PERMISSION_UNKNOWN,
1488 INJECTION_PERMISSION_GRANTED,
1489 INJECTION_PERMISSION_DENIED
1490 };
1491
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 // For security reasons, we defer updating the touch state until we are sure that
1493 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001494 int32_t displayId = entry.displayId;
1495 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1497
1498 // Update the touch state as needed based on the properties of the touch event.
1499 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1500 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1501 sp<InputWindowHandle> newHoverWindowHandle;
1502
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001503 // Copy current touch state into tempTouchState.
1504 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1505 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001506 const TouchState* oldState = nullptr;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001507 TouchState tempTouchState;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001508 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1509 mTouchStatesByDisplay.find(displayId);
1510 if (oldStateIt != mTouchStatesByDisplay.end()) {
1511 oldState = &(oldStateIt->second);
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001512 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001513 }
1514
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001515 bool isSplit = tempTouchState.split;
1516 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1517 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1518 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001519 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1520 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1521 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1522 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1523 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001524 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 bool wrongDevice = false;
1526 if (newGesture) {
1527 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001528 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001529 ALOGI("Dropping event because a pointer for a different device is already down "
1530 "in display %" PRId32,
1531 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001532 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1534 switchedDevice = false;
1535 wrongDevice = true;
1536 goto Failed;
1537 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001538 tempTouchState.reset();
1539 tempTouchState.down = down;
1540 tempTouchState.deviceId = entry.deviceId;
1541 tempTouchState.source = entry.source;
1542 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001544 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001545 ALOGI("Dropping move event because a pointer for a different device is already active "
1546 "in display %" PRId32,
1547 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001548 // TODO: test multiple simultaneous input streams.
1549 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1550 switchedDevice = false;
1551 wrongDevice = true;
1552 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 }
1554
1555 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1556 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1557
Garfield Tan00f511d2019-06-12 16:55:40 -07001558 int32_t x;
1559 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001561 // Always dispatch mouse events to cursor position.
1562 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001563 x = int32_t(entry.xCursorPosition);
1564 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001565 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001566 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1567 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001568 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001569 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001570 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001571 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1572 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001573
1574 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001575 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001576 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001579 if (newTouchedWindowHandle != nullptr &&
1580 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001581 // New window supports splitting, but we should never split mouse events.
1582 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 } else if (isSplit) {
1584 // New window does not support splitting but we have already split events.
1585 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001586 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 }
1588
1589 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001590 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001592 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001593 }
1594
1595 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1596 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001597 "(%d, %d) in display %" PRId32 ".",
1598 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001599 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1600 goto Failed;
1601 }
1602
1603 if (newTouchedWindowHandle != nullptr) {
1604 // Set target flags.
1605 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1606 if (isSplit) {
1607 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001609 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1610 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1611 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1612 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1613 }
1614
1615 // Update hover state.
1616 if (isHoverAction) {
1617 newHoverWindowHandle = newTouchedWindowHandle;
1618 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1619 newHoverWindowHandle = mLastHoverWindowHandle;
1620 }
1621
1622 // Update the temporary touch state.
1623 BitSet32 pointerIds;
1624 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001625 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001626 pointerIds.markBit(pointerId);
1627 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001628 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 }
1630
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001631 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 } else {
1633 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1634
1635 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001636 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001637 if (DEBUG_FOCUS) {
1638 ALOGD("Dropping event because the pointer is not down or we previously "
1639 "dropped the pointer down event in display %" PRId32,
1640 displayId);
1641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1643 goto Failed;
1644 }
1645
1646 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001647 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001648 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001649 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1650 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651
1652 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001653 tempTouchState.getFirstForegroundWindowHandle();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001655 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001656 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1657 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001658 if (DEBUG_FOCUS) {
1659 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1660 oldTouchedWindowHandle->getName().c_str(),
1661 newTouchedWindowHandle->getName().c_str(), displayId);
1662 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 // Make a slippery exit from the old window.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001664 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1665 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1666 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667
1668 // Make a slippery entrance into the new window.
1669 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1670 isSplit = true;
1671 }
1672
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001673 int32_t targetFlags =
1674 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 if (isSplit) {
1676 targetFlags |= InputTarget::FLAG_SPLIT;
1677 }
1678 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1679 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1680 }
1681
1682 BitSet32 pointerIds;
1683 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001684 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001686 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687 }
1688 }
1689 }
1690
1691 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1692 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001693 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694#if DEBUG_HOVER
1695 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001696 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697#endif
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001698 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1699 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 }
1701
1702 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001703 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704#if DEBUG_HOVER
1705 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001706 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707#endif
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001708 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1709 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1710 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 }
1712 }
1713
1714 // Check permission to inject into all touched foreground windows and ensure there
1715 // is at least one touched foreground window.
1716 {
1717 bool haveForegroundWindow = false;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001718 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1720 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001721 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1723 injectionPermission = INJECTION_PERMISSION_DENIED;
1724 goto Failed;
1725 }
1726 }
1727 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001728 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001729 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001730 ALOGI("Dropping event because there is no touched foreground window in display "
1731 "%" PRId32 " or gesture monitor to receive it.",
1732 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1734 goto Failed;
1735 }
1736
1737 // Permission granted to injection into all touched foreground windows.
1738 injectionPermission = INJECTION_PERMISSION_GRANTED;
1739 }
1740
1741 // Check whether windows listening for outside touches are owned by the same UID. If it is
1742 // set the policy flag that we will not reveal coordinate information to this window.
1743 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1744 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001745 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001746 if (foregroundWindowHandle) {
1747 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001748 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001749 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1750 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1751 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001752 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1753 InputTarget::FLAG_ZERO_COORDS,
1754 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 }
1757 }
1758 }
1759 }
1760
1761 // Ensure all touched foreground windows are ready for new input.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001762 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001764 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001765 std::string reason =
1766 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1767 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001768 if (!reason.empty()) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001769 return handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1770 touchedWindow.windowHandle, nextWakeupTime,
1771 reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 }
1773 }
1774 }
1775
1776 // If this is the first pointer going down and the touched window has a wallpaper
1777 // then also add the touched wallpaper windows so they are locked in for the duration
1778 // of the touch gesture.
1779 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1780 // engine only supports touch events. We would need to add a mechanism similar
1781 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1782 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1783 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001784 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001785 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001786 const std::vector<sp<InputWindowHandle>> windowHandles =
1787 getWindowHandlesLocked(displayId);
1788 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001790 if (info->displayId == displayId &&
1791 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001792 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001793 .addOrUpdateWindow(windowHandle,
1794 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1795 InputTarget::
1796 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1797 InputTarget::FLAG_DISPATCH_AS_IS,
1798 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 }
1800 }
1801 }
1802 }
1803
1804 // Success! Output targets.
1805 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1806
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001807 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001809 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 }
1811
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001812 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001813 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001814 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001815 }
1816
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 // Drop the outside or hover touch windows since we will not care about them
1818 // in the next iteration.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001819 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820
1821Failed:
1822 // Check injection permission once and for all.
1823 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001824 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 injectionPermission = INJECTION_PERMISSION_GRANTED;
1826 } else {
1827 injectionPermission = INJECTION_PERMISSION_DENIED;
1828 }
1829 }
1830
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001831 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1832 return injectionResult;
1833 }
1834
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001836 if (!wrongDevice) {
1837 if (switchedDevice) {
1838 if (DEBUG_FOCUS) {
1839 ALOGD("Conflicting pointer actions: Switched to a different device.");
1840 }
1841 *outConflictingPointerActions = true;
1842 }
1843
1844 if (isHoverAction) {
1845 // Started hovering, therefore no longer down.
1846 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001847 if (DEBUG_FOCUS) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001848 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1849 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 *outConflictingPointerActions = true;
1852 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001853 tempTouchState.reset();
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001854 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1855 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001856 tempTouchState.deviceId = entry.deviceId;
1857 tempTouchState.source = entry.source;
1858 tempTouchState.displayId = displayId;
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001859 }
1860 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1861 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1862 // All pointers up or canceled.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001863 tempTouchState.reset();
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001864 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1865 // First pointer went down.
1866 if (oldState && oldState->down) {
1867 if (DEBUG_FOCUS) {
1868 ALOGD("Conflicting pointer actions: Down received while already down.");
1869 }
1870 *outConflictingPointerActions = true;
1871 }
1872 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1873 // One pointer went up.
1874 if (isSplit) {
1875 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1876 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001878 for (size_t i = 0; i < tempTouchState.windows.size();) {
1879 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001880 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1881 touchedWindow.pointerIds.clearBit(pointerId);
1882 if (touchedWindow.pointerIds.isEmpty()) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001883 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001884 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001887 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001889 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001890 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001891
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001892 // Save changes unless the action was scroll in which case the temporary touch
1893 // state was only valid for this one action.
1894 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001895 if (tempTouchState.displayId >= 0) {
1896 mTouchStatesByDisplay[displayId] = tempTouchState;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001897 } else {
1898 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001902 // Update hover state.
1903 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 }
1905
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 return injectionResult;
1907}
1908
1909void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001910 int32_t targetFlags, BitSet32 pointerIds,
1911 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001912 std::vector<InputTarget>::iterator it =
1913 std::find_if(inputTargets.begin(), inputTargets.end(),
1914 [&windowHandle](const InputTarget& inputTarget) {
1915 return inputTarget.inputChannel->getConnectionToken() ==
1916 windowHandle->getToken();
1917 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00001918
Chavi Weingarten114b77f2020-01-15 22:35:10 +00001919 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001920
1921 if (it == inputTargets.end()) {
1922 InputTarget inputTarget;
1923 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1924 if (inputChannel == nullptr) {
1925 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1926 return;
1927 }
1928 inputTarget.inputChannel = inputChannel;
1929 inputTarget.flags = targetFlags;
1930 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
1931 inputTargets.push_back(inputTarget);
1932 it = inputTargets.end() - 1;
1933 }
1934
1935 ALOG_ASSERT(it->flags == targetFlags);
1936 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
1937
1938 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
1939 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940}
1941
Michael Wright3dd60e22019-03-27 22:06:44 +00001942void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001943 int32_t displayId, float xOffset,
1944 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001945 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1946 mGlobalMonitorsByDisplay.find(displayId);
1947
1948 if (it != mGlobalMonitorsByDisplay.end()) {
1949 const std::vector<Monitor>& monitors = it->second;
1950 for (const Monitor& monitor : monitors) {
1951 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 }
1954}
1955
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001956void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1957 float yOffset,
1958 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001959 InputTarget target;
1960 target.inputChannel = monitor.inputChannel;
1961 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001962 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00001963 inputTargets.push_back(target);
1964}
1965
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001967 const InjectionState* injectionState) {
1968 if (injectionState &&
1969 (windowHandle == nullptr ||
1970 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1971 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001972 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001974 "owned by uid %d",
1975 injectionState->injectorPid, injectionState->injectorUid,
1976 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 } else {
1978 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001979 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 }
1981 return false;
1982 }
1983 return true;
1984}
1985
Robert Carr9cada032020-04-13 17:21:08 -07001986/**
1987 * Indicate whether one window handle should be considered as obscuring
1988 * another window handle. We only check a few preconditions. Actually
1989 * checking the bounds is left to the caller.
1990 */
1991static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
1992 const sp<InputWindowHandle>& otherHandle) {
1993 // Compare by token so cloned layers aren't counted
1994 if (haveSameToken(windowHandle, otherHandle)) {
1995 return false;
1996 }
1997 auto info = windowHandle->getInfo();
1998 auto otherInfo = otherHandle->getInfo();
1999 if (!otherInfo->visible) {
2000 return false;
2001 } else if (info->ownerPid == otherInfo->ownerPid && otherHandle->getToken() == nullptr) {
2002 // In general, if ownerPid is the same we don't want to generate occlusion
2003 // events. This line is now necessary since we are including all Surfaces
2004 // in occlusion calculation, so if we didn't check PID like this SurfaceView
2005 // would occlude their parents. On the other hand before we started including
2006 // all surfaces in occlusion calculation and had this line, we would count
2007 // windows with an input channel from the same PID as occluding, and so we
2008 // preserve this behavior with the getToken() == null check.
2009 return false;
2010 } else if (otherInfo->isTrustedOverlay()) {
2011 return false;
2012 } else if (otherInfo->displayId != info->displayId) {
2013 return false;
2014 }
2015 return true;
2016}
2017
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002018bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2019 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002021 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2022 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002023 if (windowHandle == otherHandle) {
2024 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002027 if (canBeObscuredBy(windowHandle, otherHandle) &&
2028 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 return true;
2030 }
2031 }
2032 return false;
2033}
2034
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002035bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2036 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002037 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002038 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002039 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002040 if (windowHandle == otherHandle) {
2041 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002042 }
2043
2044 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002045 if (canBeObscuredBy(windowHandle, otherHandle) &&
2046 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002047 return true;
2048 }
2049 }
2050 return false;
2051}
2052
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002053std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
2054 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002055 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07002056 // If the window is paused then keep waiting.
2057 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002058 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002059 }
2060
2061 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07002062 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002063 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002064 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002065 "registered with the input dispatcher. The window may be in the "
2066 "process of being removed.",
2067 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002068 }
2069
2070 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07002071 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002072 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002073 "The window may be in the process of being removed.",
2074 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07002075 }
2076
2077 // If the connection is backed up then keep waiting.
2078 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002079 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002080 "Outbound queue length: %zu. Wait queue length: %zu.",
2081 targetType, connection->outboundQueue.size(),
2082 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07002083 }
2084
2085 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002086 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07002087 // If the event is a key event, then we must wait for all previous events to
2088 // complete before delivering it because previous events may have the
2089 // side-effect of transferring focus to a different window and we want to
2090 // ensure that the following keys are sent to the new window.
2091 //
2092 // Suppose the user touches a button in a window then immediately presses "A".
2093 // If the button causes a pop-up window to appear then we want to ensure that
2094 // the "A" key is delivered to the new pop-up window. This is because users
2095 // often anticipate pending UI changes when typing on a keyboard.
2096 // To obtain this behavior, we must serialize key events with respect to all
2097 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002098 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002099 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002100 "finished processing all of the input events that were previously "
2101 "delivered to it. Outbound queue length: %zu. Wait queue length: "
2102 "%zu.",
2103 targetType, connection->outboundQueue.size(),
2104 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 }
Jeff Brownffb49772014-10-10 19:01:34 -07002106 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 // Touch events can always be sent to a window immediately because the user intended
2108 // to touch whatever was visible at the time. Even if focus changes or a new
2109 // window appears moments later, the touch event was meant to be delivered to
2110 // whatever window happened to be on screen at the time.
2111 //
2112 // Generic motion events, such as trackball or joystick events are a little trickier.
2113 // Like key events, generic motion events are delivered to the focused window.
2114 // Unlike key events, generic motion events don't tend to transfer focus to other
2115 // windows and it is not important for them to be serialized. So we prefer to deliver
2116 // generic motion events as soon as possible to improve efficiency and reduce lag
2117 // through batching.
2118 //
2119 // The one case where we pause input event delivery is when the wait queue is piling
2120 // up with lots of events because the application is not responding.
2121 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002122 if (!connection->waitQueue.empty() &&
2123 currentTime >=
2124 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002125 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002126 "finished processing certain input events that were delivered to "
2127 "it over "
2128 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
2129 "%0.1fms.",
2130 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
2131 connection->waitQueue.size(),
2132 (currentTime - connection->waitQueue.front()->deliveryTime) *
2133 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134 }
2135 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002136 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137}
2138
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002139std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 const sp<InputApplicationHandle>& applicationHandle,
2141 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002142 if (applicationHandle != nullptr) {
2143 if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002144 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145 } else {
2146 return applicationHandle->getName();
2147 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002148 } else if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002149 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002151 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 }
2153}
2154
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002155void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002156 if (eventEntry.type == EventEntry::Type::FOCUS) {
2157 // Focus events are passed to apps, but do not represent user activity.
2158 return;
2159 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002160 int32_t displayId = getTargetDisplayId(eventEntry);
2161 sp<InputWindowHandle> focusedWindowHandle =
2162 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2163 if (focusedWindowHandle != nullptr) {
2164 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2166#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002167 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168#endif
2169 return;
2170 }
2171 }
2172
2173 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002174 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002175 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002176 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2177 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002178 return;
2179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002181 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002182 eventType = USER_ACTIVITY_EVENT_TOUCH;
2183 }
2184 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002186 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002187 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2188 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002189 return;
2190 }
2191 eventType = USER_ACTIVITY_EVENT_BUTTON;
2192 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002194 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002195 case EventEntry::Type::CONFIGURATION_CHANGED:
2196 case EventEntry::Type::DEVICE_RESET: {
2197 LOG_ALWAYS_FATAL("%s events are not user activity",
2198 EventEntry::typeToString(eventEntry.type));
2199 break;
2200 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 }
2202
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002203 std::unique_ptr<CommandEntry> commandEntry =
2204 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002205 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002207 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208}
2209
2210void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002211 const sp<Connection>& connection,
2212 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002213 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002214 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002215 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002216 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002217 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002218 ATRACE_NAME(message.c_str());
2219 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220#if DEBUG_DISPATCH_CYCLE
2221 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002222 "globalScaleFactor=%f, pointerIds=0x%x %s",
2223 connection->getInputChannelName().c_str(), inputTarget.flags,
2224 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2225 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226#endif
2227
2228 // Skip this event if the connection status is not normal.
2229 // We don't want to enqueue additional outbound events if the connection is broken.
2230 if (connection->status != Connection::STATUS_NORMAL) {
2231#if DEBUG_DISPATCH_CYCLE
2232 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002233 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234#endif
2235 return;
2236 }
2237
2238 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002239 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2240 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2241 "Entry type %s should not have FLAG_SPLIT",
2242 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002244 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002245 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002246 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002247 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 if (!splitMotionEntry) {
2249 return; // split event was dropped
2250 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002251 if (DEBUG_FOCUS) {
2252 ALOGD("channel '%s' ~ Split motion event.",
2253 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002254 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002255 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002256 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 splitMotionEntry->release();
2258 return;
2259 }
2260 }
2261
2262 // Not splitting. Enqueue dispatch entries for the event as is.
2263 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2264}
2265
2266void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002267 const sp<Connection>& connection,
2268 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002269 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002270 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002271 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002272 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002273 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002274 ATRACE_NAME(message.c_str());
2275 }
2276
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002277 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278
2279 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002280 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002281 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002282 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002283 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002284 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002285 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002286 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002287 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002288 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002290 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002291 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292
2293 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002294 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 startDispatchCycleLocked(currentTime, connection);
2296 }
2297}
2298
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002299void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2300 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002301 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002302 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002303 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002304 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2305 connection->getInputChannelName().c_str(),
2306 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002307 ATRACE_NAME(message.c_str());
2308 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002309 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 if (!(inputTargetFlags & dispatchMode)) {
2311 return;
2312 }
2313 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2314
2315 // This is a new event.
2316 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002317 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002318 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002320 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2321 // different EventEntry than what was passed in.
2322 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002324 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002325 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002326 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002327 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002328 dispatchEntry->resolvedAction = keyEntry.action;
2329 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002331 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2332 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002334 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2335 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002337 return; // skip the inconsistent event
2338 }
2339 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002342 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002343 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002344 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2345 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2346 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2347 static_cast<int32_t>(IdGenerator::Source::OTHER);
2348 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002349 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2350 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2351 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2352 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2353 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2354 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2355 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2356 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2357 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2358 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2359 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002360 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002361 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002362 }
2363 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002364 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2365 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002367 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2368 "event",
2369 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002371 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002374 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002375 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2376 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2377 }
2378 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2379 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002382 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2383 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002385 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2386 "event",
2387 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002389 return; // skip the inconsistent event
2390 }
2391
Garfield Tan1c7bc862020-01-28 13:24:04 -08002392 dispatchEntry->resolvedEventId =
2393 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2394 ? mIdGenerator.nextId()
2395 : motionEntry.id;
2396 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2397 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2398 ") to MotionEvent(id=0x%" PRIx32 ").",
2399 motionEntry.id, dispatchEntry->resolvedEventId);
2400 ATRACE_NAME(message.c_str());
2401 }
2402
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002403 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002404 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002405
2406 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002408 case EventEntry::Type::FOCUS: {
2409 break;
2410 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002411 case EventEntry::Type::CONFIGURATION_CHANGED:
2412 case EventEntry::Type::DEVICE_RESET: {
2413 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002414 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002415 break;
2416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 }
2418
2419 // Remember that we are waiting for this dispatch to complete.
2420 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002421 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 }
2423
2424 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002425 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002426 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002427}
2428
Siarhei Vishniakou7394eaa2020-04-09 11:16:18 -07002429/**
2430 * This function is purely for debugging. It helps us understand where the user interaction
2431 * was taking place. For example, if user is touching launcher, we will see a log that user
2432 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2433 * We will see both launcher and wallpaper in that list.
2434 * Once the interaction with a particular set of connections starts, no new logs will be printed
2435 * until the set of interacted connections changes.
2436 *
2437 * The following items are skipped, to reduce the logspam:
2438 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2439 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2440 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2441 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2442 * Both of those ACTION_UP events would not be logged
2443 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2444 * will not be logged. This is omitted to reduce the amount of data printed.
2445 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2446 * gesture monitor is the only connection receiving the remainder of the gesture.
2447 */
2448void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2449 const std::vector<InputTarget>& targets) {
2450 // Skip ACTION_UP events, and all events other than keys and motions
2451 if (entry.type == EventEntry::Type::KEY) {
2452 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2453 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2454 return;
2455 }
2456 } else if (entry.type == EventEntry::Type::MOTION) {
2457 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2458 if (motionEntry.action == AMOTION_EVENT_ACTION_UP) {
2459 return;
2460 }
2461 } else {
2462 return; // Not a key or a motion
2463 }
2464
2465 std::unordered_set<sp<IBinder>, IBinderHash> newConnections;
2466 for (const InputTarget& target : targets) {
2467 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2468 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2469 continue; // Skip windows that receive ACTION_OUTSIDE
2470 }
2471
2472 sp<IBinder> token = target.inputChannel->getConnectionToken();
2473 sp<Connection> connection = getConnectionLocked(token); // get connection
2474 if (connection->monitor) {
2475 continue; // We only need to keep track of the non-monitor connections.
2476 }
2477
2478 newConnections.insert(std::move(token));
2479 }
2480 if (newConnections == mInteractionConnections) {
2481 return; // no change
2482 }
2483 mInteractionConnections = newConnections;
2484 std::string windowList;
2485 for (const sp<IBinder>& token : newConnections) {
2486 sp<Connection> connection = getConnectionLocked(token);
2487 windowList += connection->getWindowName() + ", ";
2488 }
2489 std::string message = "Interaction with windows: " + windowList;
2490 if (windowList.empty()) {
2491 message += "<none>";
2492 }
2493 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2494}
2495
chaviwfd6d3512019-03-25 13:23:49 -07002496void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002497 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002498 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002499 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2500 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002501 return;
2502 }
2503
2504 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2505 if (inputWindowHandle == nullptr) {
2506 return;
2507 }
2508
chaviw8c9cf542019-03-25 13:02:48 -07002509 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002510 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002511
2512 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2513
2514 if (!hasFocusChanged) {
2515 return;
2516 }
2517
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002518 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2519 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002520 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002521 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522}
2523
2524void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002525 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002526 if (ATRACE_ENABLED()) {
2527 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002528 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002529 ATRACE_NAME(message.c_str());
2530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002532 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533#endif
2534
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002535 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2536 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537 dispatchEntry->deliveryTime = currentTime;
2538
2539 // Publish the event.
2540 status_t status;
2541 EventEntry* eventEntry = dispatchEntry->eventEntry;
2542 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002543 case EventEntry::Type::KEY: {
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002544 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2545 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002547 // Publish the key event.
Garfield Tan1c7bc862020-01-28 13:24:04 -08002548 status =
2549 connection->inputPublisher
2550 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2551 keyEntry->deviceId, keyEntry->source,
2552 keyEntry->displayId, std::move(hmac),
2553 dispatchEntry->resolvedAction,
2554 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2555 keyEntry->scanCode, keyEntry->metaState,
2556 keyEntry->repeatCount, keyEntry->downTime,
2557 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002558 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 }
2560
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002561 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002562 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002564 PointerCoords scaledCoords[MAX_POINTERS];
2565 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2566
chaviw82357092020-01-28 13:13:06 -08002567 // Set the X and Y offset and X and Y scale depending on the input source.
2568 float xOffset = 0.0f, yOffset = 0.0f;
2569 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002570 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2571 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2572 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002573 xScale = dispatchEntry->windowXScale;
2574 yScale = dispatchEntry->windowYScale;
2575 xOffset = dispatchEntry->xOffset * xScale;
2576 yOffset = dispatchEntry->yOffset * yScale;
2577 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002578 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2579 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002580 // Don't apply window scale here since we don't want scale to affect raw
2581 // coordinates. The scale will be sent back to the client and applied
2582 // later when requesting relative coordinates.
2583 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2584 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002585 }
2586 usingCoords = scaledCoords;
2587 }
2588 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002589 // We don't want the dispatch target to know.
2590 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2591 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2592 scaledCoords[i].clear();
2593 }
2594 usingCoords = scaledCoords;
2595 }
2596 }
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002597
2598 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002599
2600 // Publish the motion event.
2601 status = connection->inputPublisher
Garfield Tan1c7bc862020-01-28 13:24:04 -08002602 .publishMotionEvent(dispatchEntry->seq,
2603 dispatchEntry->resolvedEventId,
2604 motionEntry->deviceId, motionEntry->source,
2605 motionEntry->displayId, std::move(hmac),
2606 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002607 motionEntry->actionButton,
2608 dispatchEntry->resolvedFlags,
2609 motionEntry->edgeFlags, motionEntry->metaState,
2610 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002611 motionEntry->classification, xScale, yScale,
2612 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002613 motionEntry->yPrecision,
2614 motionEntry->xCursorPosition,
2615 motionEntry->yCursorPosition,
2616 motionEntry->downTime, motionEntry->eventTime,
2617 motionEntry->pointerCount,
2618 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002619 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002620 break;
2621 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002622 case EventEntry::Type::FOCUS: {
2623 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2624 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tan1c7bc862020-01-28 13:24:04 -08002625 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002626 focusEntry->hasFocus,
2627 mInTouchMode);
2628 break;
2629 }
2630
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002631 case EventEntry::Type::CONFIGURATION_CHANGED:
2632 case EventEntry::Type::DEVICE_RESET: {
2633 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2634 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002635 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002636 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 }
2638
2639 // Check the result.
2640 if (status) {
2641 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002642 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002644 "This is unexpected because the wait queue is empty, so the pipe "
2645 "should be empty and we shouldn't have any problems writing an "
2646 "event to it, status=%d",
2647 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2649 } else {
2650 // Pipe is full and we are waiting for the app to finish process some events
2651 // before sending more events to it.
2652#if DEBUG_DISPATCH_CYCLE
2653 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002654 "waiting for the application to catch up",
2655 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656#endif
2657 connection->inputPublisherBlocked = true;
2658 }
2659 } else {
2660 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002661 "status=%d",
2662 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2664 }
2665 return;
2666 }
2667
2668 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002669 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2670 connection->outboundQueue.end(),
2671 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002672 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002673 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002674 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675 }
2676}
2677
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002678const std::array<uint8_t, 32> InputDispatcher::getSignature(
2679 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2680 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2681 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2682 // Only sign events up and down events as the purely move events
2683 // are tied to their up/down counterparts so signing would be redundant.
2684 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2685 verifiedEvent.actionMasked = actionMasked;
2686 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2687 return mHmacKeyManager.sign(verifiedEvent);
2688 }
2689 return INVALID_HMAC;
2690}
2691
2692const std::array<uint8_t, 32> InputDispatcher::getSignature(
2693 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2694 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2695 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2696 verifiedEvent.action = dispatchEntry.resolvedAction;
2697 return mHmacKeyManager.sign(verifiedEvent);
2698}
2699
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002701 const sp<Connection>& connection, uint32_t seq,
2702 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703#if DEBUG_DISPATCH_CYCLE
2704 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002705 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706#endif
2707
2708 connection->inputPublisherBlocked = false;
2709
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002710 if (connection->status == Connection::STATUS_BROKEN ||
2711 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 return;
2713 }
2714
2715 // Notify other system components and prepare to start the next dispatch cycle.
2716 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2717}
2718
2719void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002720 const sp<Connection>& connection,
2721 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722#if DEBUG_DISPATCH_CYCLE
2723 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002724 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725#endif
2726
2727 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002728 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002729 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002730 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002731 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732
2733 // The connection appears to be unrecoverably broken.
2734 // Ignore already broken or zombie connections.
2735 if (connection->status == Connection::STATUS_NORMAL) {
2736 connection->status = Connection::STATUS_BROKEN;
2737
2738 if (notify) {
2739 // Notify other system components.
2740 onDispatchCycleBrokenLocked(currentTime, connection);
2741 }
2742 }
2743}
2744
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002745void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2746 while (!queue.empty()) {
2747 DispatchEntry* dispatchEntry = queue.front();
2748 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002749 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 }
2751}
2752
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002753void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002754 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002755 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756 }
2757 delete dispatchEntry;
2758}
2759
2760int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2761 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2762
2763 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002764 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002766 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002767 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002768 "fd=%d, events=0x%x",
2769 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770 return 0; // remove the callback
2771 }
2772
2773 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002774 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2776 if (!(events & ALOOPER_EVENT_INPUT)) {
2777 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002778 "events=0x%x",
2779 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 return 1;
2781 }
2782
2783 nsecs_t currentTime = now();
2784 bool gotOne = false;
2785 status_t status;
2786 for (;;) {
2787 uint32_t seq;
2788 bool handled;
2789 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2790 if (status) {
2791 break;
2792 }
2793 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2794 gotOne = true;
2795 }
2796 if (gotOne) {
2797 d->runCommandsLockedInterruptible();
2798 if (status == WOULD_BLOCK) {
2799 return 1;
2800 }
2801 }
2802
2803 notify = status != DEAD_OBJECT || !connection->monitor;
2804 if (notify) {
2805 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002806 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 }
2808 } else {
2809 // Monitor channels are never explicitly unregistered.
2810 // We do it automatically when the remote endpoint is closed so don't warn
2811 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002812 const bool stillHaveWindowHandle =
2813 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2814 nullptr;
2815 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816 if (notify) {
2817 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002818 "events=0x%x",
2819 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 }
2821 }
2822
2823 // Unregister the channel.
2824 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2825 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002826 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827}
2828
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002829void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002831 for (const auto& pair : mConnectionsByFd) {
2832 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833 }
2834}
2835
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002836void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002837 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002838 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2839 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2840}
2841
2842void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2843 const CancelationOptions& options,
2844 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2845 for (const auto& it : monitorsByDisplay) {
2846 const std::vector<Monitor>& monitors = it.second;
2847 for (const Monitor& monitor : monitors) {
2848 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002849 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002850 }
2851}
2852
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2854 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002855 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002856 if (connection == nullptr) {
2857 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002859
2860 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861}
2862
2863void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2864 const sp<Connection>& connection, const CancelationOptions& options) {
2865 if (connection->status == Connection::STATUS_BROKEN) {
2866 return;
2867 }
2868
2869 nsecs_t currentTime = now();
2870
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002871 std::vector<EventEntry*> cancelationEvents =
2872 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002874 if (cancelationEvents.empty()) {
2875 return;
2876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002878 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2879 "with reality: %s, mode=%d.",
2880 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2881 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002883
2884 InputTarget target;
2885 sp<InputWindowHandle> windowHandle =
2886 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2887 if (windowHandle != nullptr) {
2888 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2889 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2890 windowInfo->windowXScale, windowInfo->windowYScale);
2891 target.globalScaleFactor = windowInfo->globalScaleFactor;
2892 }
2893 target.inputChannel = connection->inputChannel;
2894 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2895
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002896 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2897 EventEntry* cancelationEventEntry = cancelationEvents[i];
2898 switch (cancelationEventEntry->type) {
2899 case EventEntry::Type::KEY: {
2900 logOutboundKeyDetails("cancel - ",
2901 static_cast<const KeyEntry&>(*cancelationEventEntry));
2902 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002904 case EventEntry::Type::MOTION: {
2905 logOutboundMotionDetails("cancel - ",
2906 static_cast<const MotionEntry&>(*cancelationEventEntry));
2907 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002909 case EventEntry::Type::FOCUS: {
2910 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2911 break;
2912 }
2913 case EventEntry::Type::CONFIGURATION_CHANGED:
2914 case EventEntry::Type::DEVICE_RESET: {
2915 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2916 EventEntry::typeToString(cancelationEventEntry->type));
2917 break;
2918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919 }
2920
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002921 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2922 target, InputTarget::FLAG_DISPATCH_AS_IS);
2923
2924 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002926
2927 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928}
2929
Svet Ganov5d3bc372020-01-26 23:11:07 -08002930void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2931 const sp<Connection>& connection) {
2932 if (connection->status == Connection::STATUS_BROKEN) {
2933 return;
2934 }
2935
2936 nsecs_t currentTime = now();
2937
2938 std::vector<EventEntry*> downEvents =
2939 connection->inputState.synthesizePointerDownEvents(currentTime);
2940
2941 if (downEvents.empty()) {
2942 return;
2943 }
2944
2945#if DEBUG_OUTBOUND_EVENT_DETAILS
2946 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2947 connection->getInputChannelName().c_str(), downEvents.size());
2948#endif
2949
2950 InputTarget target;
2951 sp<InputWindowHandle> windowHandle =
2952 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2953 if (windowHandle != nullptr) {
2954 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2955 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2956 windowInfo->windowXScale, windowInfo->windowYScale);
2957 target.globalScaleFactor = windowInfo->globalScaleFactor;
2958 }
2959 target.inputChannel = connection->inputChannel;
2960 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2961
2962 for (EventEntry* downEventEntry : downEvents) {
2963 switch (downEventEntry->type) {
2964 case EventEntry::Type::MOTION: {
2965 logOutboundMotionDetails("down - ",
2966 static_cast<const MotionEntry&>(*downEventEntry));
2967 break;
2968 }
2969
2970 case EventEntry::Type::KEY:
2971 case EventEntry::Type::FOCUS:
2972 case EventEntry::Type::CONFIGURATION_CHANGED:
2973 case EventEntry::Type::DEVICE_RESET: {
2974 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2975 EventEntry::typeToString(downEventEntry->type));
2976 break;
2977 }
2978 }
2979
2980 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2981 target, InputTarget::FLAG_DISPATCH_AS_IS);
2982
2983 downEventEntry->release();
2984 }
2985
2986 startDispatchCycleLocked(currentTime, connection);
2987}
2988
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002989MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002990 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002991 ALOG_ASSERT(pointerIds.value != 0);
2992
2993 uint32_t splitPointerIndexMap[MAX_POINTERS];
2994 PointerProperties splitPointerProperties[MAX_POINTERS];
2995 PointerCoords splitPointerCoords[MAX_POINTERS];
2996
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002997 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002998 uint32_t splitPointerCount = 0;
2999
3000 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003001 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003003 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004 uint32_t pointerId = uint32_t(pointerProperties.id);
3005 if (pointerIds.hasBit(pointerId)) {
3006 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3007 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3008 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003009 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003010 splitPointerCount += 1;
3011 }
3012 }
3013
3014 if (splitPointerCount != pointerIds.count()) {
3015 // This is bad. We are missing some of the pointers that we expected to deliver.
3016 // Most likely this indicates that we received an ACTION_MOVE events that has
3017 // different pointer ids than we expected based on the previous ACTION_DOWN
3018 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3019 // in this way.
3020 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003021 "we expected there to be %d pointers. This probably means we received "
3022 "a broken sequence of pointer ids from the input device.",
3023 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003024 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025 }
3026
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003027 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003029 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3030 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3032 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003033 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034 uint32_t pointerId = uint32_t(pointerProperties.id);
3035 if (pointerIds.hasBit(pointerId)) {
3036 if (pointerIds.count() == 1) {
3037 // The first/last pointer went down/up.
3038 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003039 ? AMOTION_EVENT_ACTION_DOWN
3040 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041 } else {
3042 // A secondary pointer went down/up.
3043 uint32_t splitPointerIndex = 0;
3044 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3045 splitPointerIndex += 1;
3046 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003047 action = maskedAction |
3048 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049 }
3050 } else {
3051 // An unrelated pointer changed.
3052 action = AMOTION_EVENT_ACTION_MOVE;
3053 }
3054 }
3055
Garfield Tan1c7bc862020-01-28 13:24:04 -08003056 int32_t newId = mIdGenerator.nextId();
3057 if (ATRACE_ENABLED()) {
3058 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3059 ") to MotionEvent(id=0x%" PRIx32 ").",
3060 originalMotionEntry.id, newId);
3061 ATRACE_NAME(message.c_str());
3062 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003063 MotionEntry* splitMotionEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08003064 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3065 originalMotionEntry.source, originalMotionEntry.displayId,
3066 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003067 originalMotionEntry.actionButton, originalMotionEntry.flags,
3068 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3069 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3070 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3071 originalMotionEntry.xCursorPosition,
3072 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003073 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003075 if (originalMotionEntry.injectionState) {
3076 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077 splitMotionEntry->injectionState->refCount += 1;
3078 }
3079
3080 return splitMotionEntry;
3081}
3082
3083void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3084#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003085 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086#endif
3087
3088 bool needWake;
3089 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003090 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091
Prabir Pradhan42611e02018-11-27 14:04:02 -08003092 ConfigurationChangedEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003093 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094 needWake = enqueueInboundEventLocked(newEntry);
3095 } // release lock
3096
3097 if (needWake) {
3098 mLooper->wake();
3099 }
3100}
3101
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003102/**
3103 * If one of the meta shortcuts is detected, process them here:
3104 * Meta + Backspace -> generate BACK
3105 * Meta + Enter -> generate HOME
3106 * This will potentially overwrite keyCode and metaState.
3107 */
3108void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003109 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003110 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3111 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3112 if (keyCode == AKEYCODE_DEL) {
3113 newKeyCode = AKEYCODE_BACK;
3114 } else if (keyCode == AKEYCODE_ENTER) {
3115 newKeyCode = AKEYCODE_HOME;
3116 }
3117 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003118 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003119 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003120 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003121 keyCode = newKeyCode;
3122 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3123 }
3124 } else if (action == AKEY_EVENT_ACTION_UP) {
3125 // In order to maintain a consistent stream of up and down events, check to see if the key
3126 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3127 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003128 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003129 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003130 auto replacementIt = mReplacedKeys.find(replacement);
3131 if (replacementIt != mReplacedKeys.end()) {
3132 keyCode = replacementIt->second;
3133 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003134 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3135 }
3136 }
3137}
3138
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3140#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003141 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3142 "policyFlags=0x%x, action=0x%x, "
3143 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3144 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3145 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3146 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147#endif
3148 if (!validateKeyEvent(args->action)) {
3149 return;
3150 }
3151
3152 uint32_t policyFlags = args->policyFlags;
3153 int32_t flags = args->flags;
3154 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003155 // InputDispatcher tracks and generates key repeats on behalf of
3156 // whatever notifies it, so repeatCount should always be set to 0
3157 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3159 policyFlags |= POLICY_FLAG_VIRTUAL;
3160 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 if (policyFlags & POLICY_FLAG_FUNCTION) {
3163 metaState |= AMETA_FUNCTION_ON;
3164 }
3165
3166 policyFlags |= POLICY_FLAG_TRUSTED;
3167
Michael Wright78f24442014-08-06 15:55:28 -07003168 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003169 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003170
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003172 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08003173 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3174 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175
Michael Wright2b3c3302018-03-02 17:19:13 +00003176 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003178 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3179 ALOGW("Excessive delay in interceptKeyBeforeQueueing; 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
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 bool needWake;
3184 { // acquire lock
3185 mLock.lock();
3186
3187 if (shouldSendKeyToInputFilterLocked(args)) {
3188 mLock.unlock();
3189
3190 policyFlags |= POLICY_FLAG_FILTERED;
3191 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3192 return; // event was consumed by the filter
3193 }
3194
3195 mLock.lock();
3196 }
3197
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003198 KeyEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003199 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003200 args->displayId, policyFlags, args->action, flags, keyCode,
3201 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202
3203 needWake = enqueueInboundEventLocked(newEntry);
3204 mLock.unlock();
3205 } // release lock
3206
3207 if (needWake) {
3208 mLooper->wake();
3209 }
3210}
3211
3212bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3213 return mInputFilterEnabled;
3214}
3215
3216void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3217#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003218 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3219 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003220 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3221 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003222 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003223 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3224 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3225 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3226 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 for (uint32_t i = 0; i < args->pointerCount; i++) {
3228 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 "x=%f, y=%f, pressure=%f, size=%f, "
3230 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3231 "orientation=%f",
3232 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3233 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3234 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3235 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3236 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3237 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3238 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3239 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3240 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3241 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 }
3243#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003244 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3245 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 return;
3247 }
3248
3249 uint32_t policyFlags = args->policyFlags;
3250 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003251
3252 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003253 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003254 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3255 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003256 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003257 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258
3259 bool needWake;
3260 { // acquire lock
3261 mLock.lock();
3262
3263 if (shouldSendMotionToInputFilterLocked(args)) {
3264 mLock.unlock();
3265
3266 MotionEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003267 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3268 args->action, args->actionButton, args->flags, args->edgeFlags,
3269 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3270 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3271 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3272 args->downTime, args->eventTime, args->pointerCount,
3273 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274
3275 policyFlags |= POLICY_FLAG_FILTERED;
3276 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3277 return; // event was consumed by the filter
3278 }
3279
3280 mLock.lock();
3281 }
3282
3283 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003284 MotionEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003285 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003286 args->displayId, policyFlags, args->action, args->actionButton,
3287 args->flags, args->metaState, args->buttonState,
3288 args->classification, args->edgeFlags, args->xPrecision,
3289 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3290 args->downTime, args->pointerCount, args->pointerProperties,
3291 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292
3293 needWake = enqueueInboundEventLocked(newEntry);
3294 mLock.unlock();
3295 } // release lock
3296
3297 if (needWake) {
3298 mLooper->wake();
3299 }
3300}
3301
3302bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003303 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304}
3305
3306void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3307#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003308 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003309 "switchMask=0x%08x",
3310 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311#endif
3312
3313 uint32_t policyFlags = args->policyFlags;
3314 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003315 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316}
3317
3318void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3319#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003320 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3321 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322#endif
3323
3324 bool needWake;
3325 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003326 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327
Prabir Pradhan42611e02018-11-27 14:04:02 -08003328 DeviceResetEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003329 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330 needWake = enqueueInboundEventLocked(newEntry);
3331 } // release lock
3332
3333 if (needWake) {
3334 mLooper->wake();
3335 }
3336}
3337
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3339 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003340 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341#if DEBUG_INBOUND_EVENT_DETAILS
3342 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003343 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3344 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345#endif
3346
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003347 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348
3349 policyFlags |= POLICY_FLAG_INJECTED;
3350 if (hasInjectionPermission(injectorPid, injectorUid)) {
3351 policyFlags |= POLICY_FLAG_TRUSTED;
3352 }
3353
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003354 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003356 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003357 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3358 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003359 if (!validateKeyEvent(action)) {
3360 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003363 int32_t flags = incomingKey.getFlags();
3364 int32_t keyCode = incomingKey.getKeyCode();
3365 int32_t metaState = incomingKey.getMetaState();
3366 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003368 KeyEvent keyEvent;
Garfield Tanfbe732e2020-01-24 11:26:14 -08003369 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003370 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3371 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3372 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003374 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3375 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003376 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003377
3378 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3379 android::base::Timer t;
3380 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3381 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3382 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3383 std::to_string(t.duration().count()).c_str());
3384 }
3385 }
3386
3387 mLock.lock();
3388 KeyEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003389 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3390 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003391 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3392 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tanfbe732e2020-01-24 11:26:14 -08003393 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003394 injectedEntries.push(injectedEntry);
3395 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 }
3397
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003398 case AINPUT_EVENT_TYPE_MOTION: {
3399 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3400 int32_t action = motionEvent->getAction();
3401 size_t pointerCount = motionEvent->getPointerCount();
3402 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3403 int32_t actionButton = motionEvent->getActionButton();
3404 int32_t displayId = motionEvent->getDisplayId();
3405 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3406 return INPUT_EVENT_INJECTION_FAILED;
3407 }
3408
3409 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3410 nsecs_t eventTime = motionEvent->getEventTime();
3411 android::base::Timer t;
3412 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3413 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3414 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3415 std::to_string(t.duration().count()).c_str());
3416 }
3417 }
3418
3419 mLock.lock();
3420 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3421 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3422 MotionEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003423 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3424 motionEvent->getSource(), motionEvent->getDisplayId(),
3425 policyFlags, action, actionButton, motionEvent->getFlags(),
3426 motionEvent->getMetaState(), motionEvent->getButtonState(),
3427 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3428 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003429 motionEvent->getRawXCursorPosition(),
3430 motionEvent->getRawYCursorPosition(),
3431 motionEvent->getDownTime(), uint32_t(pointerCount),
3432 pointerProperties, samplePointerCoords,
3433 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003434 injectedEntries.push(injectedEntry);
3435 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3436 sampleEventTimes += 1;
3437 samplePointerCoords += pointerCount;
3438 MotionEntry* nextInjectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003439 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003440 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003441 motionEvent->getDisplayId(), policyFlags, action,
3442 actionButton, motionEvent->getFlags(),
3443 motionEvent->getMetaState(), motionEvent->getButtonState(),
3444 motionEvent->getClassification(),
3445 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3446 motionEvent->getYPrecision(),
3447 motionEvent->getRawXCursorPosition(),
3448 motionEvent->getRawYCursorPosition(),
3449 motionEvent->getDownTime(), uint32_t(pointerCount),
3450 pointerProperties, samplePointerCoords,
3451 motionEvent->getXOffset(), motionEvent->getYOffset());
3452 injectedEntries.push(nextInjectedEntry);
3453 }
3454 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003457 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003458 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003459 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460 }
3461
3462 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3463 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3464 injectionState->injectionIsAsync = true;
3465 }
3466
3467 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003468 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469
3470 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003471 while (!injectedEntries.empty()) {
3472 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3473 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 }
3475
3476 mLock.unlock();
3477
3478 if (needWake) {
3479 mLooper->wake();
3480 }
3481
3482 int32_t injectionResult;
3483 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003484 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485
3486 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3487 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3488 } else {
3489 for (;;) {
3490 injectionResult = injectionState->injectionResult;
3491 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3492 break;
3493 }
3494
3495 nsecs_t remainingTimeout = endTime - now();
3496 if (remainingTimeout <= 0) {
3497#if DEBUG_INJECTION
3498 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003499 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500#endif
3501 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3502 break;
3503 }
3504
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003505 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506 }
3507
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003508 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3509 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510 while (injectionState->pendingForegroundDispatches != 0) {
3511#if DEBUG_INJECTION
3512 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003513 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514#endif
3515 nsecs_t remainingTimeout = endTime - now();
3516 if (remainingTimeout <= 0) {
3517#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003518 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3519 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520#endif
3521 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3522 break;
3523 }
3524
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003525 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 }
3527 }
3528 }
3529
3530 injectionState->release();
3531 } // release lock
3532
3533#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003534 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003535 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536#endif
3537
3538 return injectionResult;
3539}
3540
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003541std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003542 std::array<uint8_t, 32> calculatedHmac;
3543 std::unique_ptr<VerifiedInputEvent> result;
3544 switch (event.getType()) {
3545 case AINPUT_EVENT_TYPE_KEY: {
3546 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3547 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3548 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3549 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3550 break;
3551 }
3552 case AINPUT_EVENT_TYPE_MOTION: {
3553 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3554 VerifiedMotionEvent verifiedMotionEvent =
3555 verifiedMotionEventFromMotionEvent(motionEvent);
3556 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3557 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3558 break;
3559 }
3560 default: {
3561 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3562 return nullptr;
3563 }
3564 }
3565 if (calculatedHmac == INVALID_HMAC) {
3566 return nullptr;
3567 }
3568 if (calculatedHmac != event.getHmac()) {
3569 return nullptr;
3570 }
3571 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003572}
3573
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003575 return injectorUid == 0 ||
3576 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577}
3578
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003579void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 InjectionState* injectionState = entry->injectionState;
3581 if (injectionState) {
3582#if DEBUG_INJECTION
3583 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003584 "injectorPid=%d, injectorUid=%d",
3585 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586#endif
3587
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003588 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 // Log the outcome since the injector did not wait for the injection result.
3590 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003591 case INPUT_EVENT_INJECTION_SUCCEEDED:
3592 ALOGV("Asynchronous input event injection succeeded.");
3593 break;
3594 case INPUT_EVENT_INJECTION_FAILED:
3595 ALOGW("Asynchronous input event injection failed.");
3596 break;
3597 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3598 ALOGW("Asynchronous input event injection permission denied.");
3599 break;
3600 case INPUT_EVENT_INJECTION_TIMED_OUT:
3601 ALOGW("Asynchronous input event injection timed out.");
3602 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 }
3604 }
3605
3606 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003607 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 }
3609}
3610
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003611void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 InjectionState* injectionState = entry->injectionState;
3613 if (injectionState) {
3614 injectionState->pendingForegroundDispatches += 1;
3615 }
3616}
3617
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003618void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 InjectionState* injectionState = entry->injectionState;
3620 if (injectionState) {
3621 injectionState->pendingForegroundDispatches -= 1;
3622
3623 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003624 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625 }
3626 }
3627}
3628
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003629std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3630 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003631 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003632}
3633
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003635 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003636 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003637 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3638 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003639 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003640 return windowHandle;
3641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 }
3643 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003644 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645}
3646
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003647bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003648 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003649 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3650 for (const sp<InputWindowHandle>& handle : windowHandles) {
3651 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003652 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003653 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003654 ", but it should belong to display %" PRId32,
3655 windowHandle->getName().c_str(), it.first,
3656 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003657 }
3658 return true;
3659 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 }
3661 }
3662 return false;
3663}
3664
Robert Carr5c8a0262018-10-03 16:30:44 -07003665sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3666 size_t count = mInputChannelsByToken.count(token);
3667 if (count == 0) {
3668 return nullptr;
3669 }
3670 return mInputChannelsByToken.at(token);
3671}
3672
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003673void InputDispatcher::updateWindowHandlesForDisplayLocked(
3674 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3675 if (inputWindowHandles.empty()) {
3676 // Remove all handles on a display if there are no windows left.
3677 mWindowHandlesByDisplay.erase(displayId);
3678 return;
3679 }
3680
3681 // Since we compare the pointer of input window handles across window updates, we need
3682 // to make sure the handle object for the same window stays unchanged across updates.
3683 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003684 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003685 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003686 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003687 }
3688
3689 std::vector<sp<InputWindowHandle>> newHandles;
3690 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3691 if (!handle->updateInfo()) {
3692 // handle no longer valid
3693 continue;
3694 }
3695
3696 const InputWindowInfo* info = handle->getInfo();
3697 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3698 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3699 const bool noInputChannel =
3700 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3701 const bool canReceiveInput =
3702 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3703 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3704 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003705 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003706 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003707 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003708 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003709 }
3710
3711 if (info->displayId != displayId) {
3712 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3713 handle->getName().c_str(), displayId, info->displayId);
3714 continue;
3715 }
3716
Robert Carredd13602020-04-13 17:24:34 -07003717 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3718 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003719 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003720 oldHandle->updateFrom(handle);
3721 newHandles.push_back(oldHandle);
3722 } else {
3723 newHandles.push_back(handle);
3724 }
3725 }
3726
3727 // Insert or replace
3728 mWindowHandlesByDisplay[displayId] = newHandles;
3729}
3730
Arthur Hung72d8dc32020-03-28 00:48:39 +00003731void InputDispatcher::setInputWindows(
3732 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3733 { // acquire lock
3734 std::scoped_lock _l(mLock);
3735 for (auto const& i : handlesPerDisplay) {
3736 setInputWindowsLocked(i.second, i.first);
3737 }
3738 }
3739 // Wake up poll loop since it may need to make new input dispatching choices.
3740 mLooper->wake();
3741}
3742
Arthur Hungb92218b2018-08-14 12:00:21 +08003743/**
3744 * Called from InputManagerService, update window handle list by displayId that can receive input.
3745 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3746 * If set an empty list, remove all handles from the specific display.
3747 * For focused handle, check if need to change and send a cancel event to previous one.
3748 * For removed handle, check if need to send a cancel event if already in touch.
3749 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003750void InputDispatcher::setInputWindowsLocked(
3751 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003752 if (DEBUG_FOCUS) {
3753 std::string windowList;
3754 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3755 windowList += iwh->getName() + " ";
3756 }
3757 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759
Arthur Hung72d8dc32020-03-28 00:48:39 +00003760 // Copy old handles for release if they are no longer present.
3761 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762
Arthur Hung72d8dc32020-03-28 00:48:39 +00003763 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003764
Arthur Hung72d8dc32020-03-28 00:48:39 +00003765 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3766 bool foundHoveredWindow = false;
3767 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3768 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3769 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3770 windowHandle->getInfo()->visible) {
3771 newFocusedWindowHandle = windowHandle;
3772 }
3773 if (windowHandle == mLastHoverWindowHandle) {
3774 foundHoveredWindow = true;
3775 }
3776 }
3777
3778 if (!foundHoveredWindow) {
3779 mLastHoverWindowHandle = nullptr;
3780 }
3781
3782 sp<InputWindowHandle> oldFocusedWindowHandle =
3783 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3784
3785 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3786 if (oldFocusedWindowHandle != nullptr) {
3787 if (DEBUG_FOCUS) {
3788 ALOGD("Focus left window: %s in display %" PRId32,
3789 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003790 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003791 sp<InputChannel> focusedInputChannel =
3792 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3793 if (focusedInputChannel != nullptr) {
3794 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3795 "focus left window");
3796 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3797 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003798 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003799 mFocusedWindowHandlesByDisplay.erase(displayId);
3800 }
3801 if (newFocusedWindowHandle != nullptr) {
3802 if (DEBUG_FOCUS) {
3803 ALOGD("Focus entered window: %s in display %" PRId32,
3804 newFocusedWindowHandle->getName().c_str(), displayId);
3805 }
3806 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3807 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808 }
3809
Arthur Hung72d8dc32020-03-28 00:48:39 +00003810 if (mFocusedDisplayId == displayId) {
3811 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003815 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3816 mTouchStatesByDisplay.find(displayId);
3817 if (stateIt != mTouchStatesByDisplay.end()) {
3818 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003819 for (size_t i = 0; i < state.windows.size();) {
3820 TouchedWindow& touchedWindow = state.windows[i];
3821 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003822 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003823 ALOGD("Touched window was removed: %s in display %" PRId32,
3824 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003825 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003826 sp<InputChannel> touchedInputChannel =
3827 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3828 if (touchedInputChannel != nullptr) {
3829 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3830 "touched window was removed");
3831 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003833 state.windows.erase(state.windows.begin() + i);
3834 } else {
3835 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836 }
3837 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003838 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003839
Arthur Hung72d8dc32020-03-28 00:48:39 +00003840 // Release information for windows that are no longer present.
3841 // This ensures that unused input channels are released promptly.
3842 // Otherwise, they might stick around until the window handle is destroyed
3843 // which might not happen until the next GC.
3844 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3845 if (!hasWindowHandleLocked(oldWindowHandle)) {
3846 if (DEBUG_FOCUS) {
3847 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003848 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003849 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003850 }
chaviw291d88a2019-02-14 10:33:58 -08003851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852}
3853
3854void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003855 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003856 if (DEBUG_FOCUS) {
3857 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3858 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003860 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003861 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862
Tiger Huang721e26f2018-07-24 22:26:19 +08003863 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3864 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003865 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003866 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3867 if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003868 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003870 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003872 } else if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003873 resetAnrTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003874 oldFocusedApplicationHandle.clear();
3875 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 } // release lock
3878
3879 // Wake up poll loop since it may need to make new input dispatching choices.
3880 mLooper->wake();
3881}
3882
Tiger Huang721e26f2018-07-24 22:26:19 +08003883/**
3884 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3885 * the display not specified.
3886 *
3887 * We track any unreleased events for each window. If a window loses the ability to receive the
3888 * released event, we will send a cancel event to it. So when the focused display is changed, we
3889 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3890 * display. The display-specified events won't be affected.
3891 */
3892void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003893 if (DEBUG_FOCUS) {
3894 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3895 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003896 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003897 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003898
3899 if (mFocusedDisplayId != displayId) {
3900 sp<InputWindowHandle> oldFocusedWindowHandle =
3901 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3902 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003903 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003904 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003905 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003906 CancelationOptions
3907 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3908 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003909 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003910 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3911 }
3912 }
3913 mFocusedDisplayId = displayId;
3914
3915 // Sanity check
3916 sp<InputWindowHandle> newFocusedWindowHandle =
3917 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003918 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003919
Tiger Huang721e26f2018-07-24 22:26:19 +08003920 if (newFocusedWindowHandle == nullptr) {
3921 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3922 if (!mFocusedWindowHandlesByDisplay.empty()) {
3923 ALOGE("But another display has a focused window:");
3924 for (auto& it : mFocusedWindowHandlesByDisplay) {
3925 const int32_t displayId = it.first;
3926 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003927 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3928 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003929 }
3930 }
3931 }
3932 }
3933
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003934 if (DEBUG_FOCUS) {
3935 logDispatchStateLocked();
3936 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003937 } // release lock
3938
3939 // Wake up poll loop since it may need to make new input dispatching choices.
3940 mLooper->wake();
3941}
3942
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003944 if (DEBUG_FOCUS) {
3945 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947
3948 bool changed;
3949 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003950 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951
3952 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3953 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003954 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955 }
3956
3957 if (mDispatchEnabled && !enabled) {
3958 resetAndDropEverythingLocked("dispatcher is being disabled");
3959 }
3960
3961 mDispatchEnabled = enabled;
3962 mDispatchFrozen = frozen;
3963 changed = true;
3964 } else {
3965 changed = false;
3966 }
3967
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003968 if (DEBUG_FOCUS) {
3969 logDispatchStateLocked();
3970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 } // release lock
3972
3973 if (changed) {
3974 // Wake up poll loop since it may need to make new input dispatching choices.
3975 mLooper->wake();
3976 }
3977}
3978
3979void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003980 if (DEBUG_FOCUS) {
3981 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983
3984 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003985 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986
3987 if (mInputFilterEnabled == enabled) {
3988 return;
3989 }
3990
3991 mInputFilterEnabled = enabled;
3992 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3993 } // release lock
3994
3995 // Wake up poll loop since there might be work to do to drop everything.
3996 mLooper->wake();
3997}
3998
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003999void InputDispatcher::setInTouchMode(bool inTouchMode) {
4000 std::scoped_lock lock(mLock);
4001 mInTouchMode = inTouchMode;
4002}
4003
chaviwfbe5d9c2018-12-26 12:23:37 -08004004bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4005 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004006 if (DEBUG_FOCUS) {
4007 ALOGD("Trivial transfer to same window.");
4008 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004009 return true;
4010 }
4011
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004013 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014
chaviwfbe5d9c2018-12-26 12:23:37 -08004015 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4016 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004017 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004018 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019 return false;
4020 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004021 if (DEBUG_FOCUS) {
4022 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4023 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4024 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004026 if (DEBUG_FOCUS) {
4027 ALOGD("Cannot transfer focus because windows are on different displays.");
4028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 return false;
4030 }
4031
4032 bool found = false;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004033 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4034 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004035 for (size_t i = 0; i < state.windows.size(); i++) {
4036 const TouchedWindow& touchedWindow = state.windows[i];
4037 if (touchedWindow.windowHandle == fromWindowHandle) {
4038 int32_t oldTargetFlags = touchedWindow.targetFlags;
4039 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004040
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004041 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004043 int32_t newTargetFlags = oldTargetFlags &
4044 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4045 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004046 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047
Jeff Brownf086ddb2014-02-11 14:28:48 -08004048 found = true;
4049 goto Found;
4050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 }
4052 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004053 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004055 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004056 if (DEBUG_FOCUS) {
4057 ALOGD("Focus transfer failed because from window did not have focus.");
4058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059 return false;
4060 }
4061
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004062 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4063 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004064 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004065 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004066 CancelationOptions
4067 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4068 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004070 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 }
4072
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004073 if (DEBUG_FOCUS) {
4074 logDispatchStateLocked();
4075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 } // release lock
4077
4078 // Wake up poll loop since it may need to make new input dispatching choices.
4079 mLooper->wake();
4080 return true;
4081}
4082
4083void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004084 if (DEBUG_FOCUS) {
4085 ALOGD("Resetting and dropping all events (%s).", reason);
4086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087
4088 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4089 synthesizeCancelationEventsForAllConnectionsLocked(options);
4090
4091 resetKeyRepeatLocked();
4092 releasePendingEventLocked();
4093 drainInboundQueueLocked();
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004094 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095
Jeff Brownf086ddb2014-02-11 14:28:48 -08004096 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004098 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099}
4100
4101void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004102 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 dumpDispatchStateLocked(dump);
4104
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004105 std::istringstream stream(dump);
4106 std::string line;
4107
4108 while (std::getline(stream, line, '\n')) {
4109 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 }
4111}
4112
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004113void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004114 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4115 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4116 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004117 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118
Tiger Huang721e26f2018-07-24 22:26:19 +08004119 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4120 dump += StringPrintf(INDENT "FocusedApplications:\n");
4121 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4122 const int32_t displayId = it.first;
4123 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004124 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004125 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004126 displayId, applicationHandle->getName().c_str(),
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004127 ns2ms(applicationHandle
4128 ->getDispatchingTimeout(
4129 DEFAULT_INPUT_DISPATCHING_TIMEOUT)
4130 .count()));
Tiger Huang721e26f2018-07-24 22:26:19 +08004131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004133 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004135
4136 if (!mFocusedWindowHandlesByDisplay.empty()) {
4137 dump += StringPrintf(INDENT "FocusedWindows:\n");
4138 for (auto& it : mFocusedWindowHandlesByDisplay) {
4139 const int32_t displayId = it.first;
4140 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004141 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4142 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004143 }
4144 } else {
4145 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004148 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004149 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004150 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4151 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004152 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004153 state.displayId, toString(state.down), toString(state.split),
4154 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004155 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004156 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004157 for (size_t i = 0; i < state.windows.size(); i++) {
4158 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004159 dump += StringPrintf(INDENT4
4160 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4161 i, touchedWindow.windowHandle->getName().c_str(),
4162 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004163 }
4164 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004165 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004166 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004167 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004168 dump += INDENT3 "Portal windows:\n";
4169 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004170 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004171 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4172 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004173 }
4174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 }
4176 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004177 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 }
4179
Arthur Hungb92218b2018-08-14 12:00:21 +08004180 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004181 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004182 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004183 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004184 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004185 dump += INDENT2 "Windows:\n";
4186 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004187 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004188 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189
Arthur Hungb92218b2018-08-14 12:00:21 +08004190 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004191 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004192 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4193 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004194 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004195 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 i, windowInfo->name.c_str(), windowInfo->displayId,
4197 windowInfo->portalToDisplayId,
4198 toString(windowInfo->paused),
4199 toString(windowInfo->hasFocus),
4200 toString(windowInfo->hasWallpaper),
4201 toString(windowInfo->visible),
4202 toString(windowInfo->canReceiveKeys),
4203 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004204 windowInfo->layoutParamsType, windowInfo->frameLeft,
4205 windowInfo->frameTop, windowInfo->frameRight,
4206 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4207 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004208 dumpRegion(dump, windowInfo->touchableRegion);
4209 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004210 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4211 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004212 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004213 ns2ms(windowInfo->dispatchingTimeout));
Arthur Hungb92218b2018-08-14 12:00:21 +08004214 }
4215 } else {
4216 dump += INDENT2 "Windows: <none>\n";
4217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 }
4219 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004220 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 }
4222
Michael Wright3dd60e22019-03-27 22:06:44 +00004223 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004225 const std::vector<Monitor>& monitors = it.second;
4226 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4227 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004228 }
4229 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004230 const std::vector<Monitor>& monitors = it.second;
4231 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4232 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004235 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 }
4237
4238 nsecs_t currentTime = now();
4239
4240 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004241 if (!mRecentQueue.empty()) {
4242 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4243 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004244 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004246 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 }
4248 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004249 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 }
4251
4252 // Dump event currently being dispatched.
4253 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004254 dump += INDENT "PendingEvent:\n";
4255 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004257 dump += StringPrintf(", age=%" PRId64 "ms\n",
4258 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004260 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 }
4262
4263 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004264 if (!mInboundQueue.empty()) {
4265 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4266 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004267 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004269 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 }
4271 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004272 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 }
4274
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004275 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004276 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004277 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4278 const KeyReplacement& replacement = pair.first;
4279 int32_t newKeyCode = pair.second;
4280 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004281 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004282 }
4283 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004284 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004285 }
4286
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004287 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004288 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004289 for (const auto& pair : mConnectionsByFd) {
4290 const sp<Connection>& connection = pair.second;
4291 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
4292 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
4293 pair.first, connection->getInputChannelName().c_str(),
4294 connection->getWindowName().c_str(), connection->getStatusLabel(),
4295 toString(connection->monitor),
4296 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004298 if (!connection->outboundQueue.empty()) {
4299 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4300 connection->outboundQueue.size());
4301 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 dump.append(INDENT4);
4303 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004304 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4305 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004306 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004307 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 }
4309 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004310 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 }
4312
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004313 if (!connection->waitQueue.empty()) {
4314 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4315 connection->waitQueue.size());
4316 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004317 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004319 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004320 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004321 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004322 ns2ms(currentTime - entry->eventEntry->eventTime),
4323 ns2ms(currentTime - entry->deliveryTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 }
4325 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004326 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
4328 }
4329 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004330 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 }
4332
4333 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004334 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4335 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004337 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 }
4339
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004340 dump += INDENT "Configuration:\n";
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004341 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4342 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4343 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344}
4345
Michael Wright3dd60e22019-03-27 22:06:44 +00004346void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4347 const size_t numMonitors = monitors.size();
4348 for (size_t i = 0; i < numMonitors; i++) {
4349 const Monitor& monitor = monitors[i];
4350 const sp<InputChannel>& channel = monitor.inputChannel;
4351 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4352 dump += "\n";
4353 }
4354}
4355
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004356status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004358 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359#endif
4360
4361 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004362 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004363 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004364 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004366 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 return BAD_VALUE;
4368 }
4369
Garfield Tan1c7bc862020-01-28 13:24:04 -08004370 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371
4372 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004373 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004374 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4377 } // release lock
4378
4379 // Wake the looper because some connections have changed.
4380 mLooper->wake();
4381 return OK;
4382}
4383
Michael Wright3dd60e22019-03-27 22:06:44 +00004384status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004385 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004386 { // acquire lock
4387 std::scoped_lock _l(mLock);
4388
4389 if (displayId < 0) {
4390 ALOGW("Attempted to register input monitor without a specified display.");
4391 return BAD_VALUE;
4392 }
4393
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004394 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004395 ALOGW("Attempted to register input monitor without an identifying token.");
4396 return BAD_VALUE;
4397 }
4398
Garfield Tan1c7bc862020-01-28 13:24:04 -08004399 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004400
4401 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004402 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004403 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004404
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004405 auto& monitorsByDisplay =
4406 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004407 monitorsByDisplay[displayId].emplace_back(inputChannel);
4408
4409 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004410 }
4411 // Wake the looper because some connections have changed.
4412 mLooper->wake();
4413 return OK;
4414}
4415
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4417#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004418 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419#endif
4420
4421 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004422 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423
4424 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4425 if (status) {
4426 return status;
4427 }
4428 } // release lock
4429
4430 // Wake the poll loop because removing the connection may have changed the current
4431 // synchronization state.
4432 mLooper->wake();
4433 return OK;
4434}
4435
4436status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004437 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004438 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004439 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004440 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004441 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004442 return BAD_VALUE;
4443 }
4444
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004445 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004446 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004447
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448 if (connection->monitor) {
4449 removeMonitorChannelLocked(inputChannel);
4450 }
4451
4452 mLooper->removeFd(inputChannel->getFd());
4453
4454 nsecs_t currentTime = now();
4455 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4456
4457 connection->status = Connection::STATUS_ZOMBIE;
4458 return OK;
4459}
4460
4461void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004462 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4463 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4464}
4465
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004466void InputDispatcher::removeMonitorChannelLocked(
4467 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004468 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004469 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004470 std::vector<Monitor>& monitors = it->second;
4471 const size_t numMonitors = monitors.size();
4472 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004473 if (monitors[i].inputChannel == inputChannel) {
4474 monitors.erase(monitors.begin() + i);
4475 break;
4476 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004477 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004478 if (monitors.empty()) {
4479 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004480 } else {
4481 ++it;
4482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483 }
4484}
4485
Michael Wright3dd60e22019-03-27 22:06:44 +00004486status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4487 { // acquire lock
4488 std::scoped_lock _l(mLock);
4489 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4490
4491 if (!foundDisplayId) {
4492 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4493 return BAD_VALUE;
4494 }
4495 int32_t displayId = foundDisplayId.value();
4496
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004497 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4498 mTouchStatesByDisplay.find(displayId);
4499 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004500 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4501 return BAD_VALUE;
4502 }
4503
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004504 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004505 std::optional<int32_t> foundDeviceId;
4506 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004507 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004508 foundDeviceId = state.deviceId;
4509 }
4510 }
4511 if (!foundDeviceId || !state.down) {
4512 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004513 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004514 return BAD_VALUE;
4515 }
4516 int32_t deviceId = foundDeviceId.value();
4517
4518 // Send cancel events to all the input channels we're stealing from.
4519 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004520 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004521 options.deviceId = deviceId;
4522 options.displayId = displayId;
4523 for (const TouchedWindow& window : state.windows) {
4524 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004525 if (channel != nullptr) {
4526 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4527 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004528 }
4529 // Then clear the current touch state so we stop dispatching to them as well.
4530 state.filterNonMonitors();
4531 }
4532 return OK;
4533}
4534
Michael Wright3dd60e22019-03-27 22:06:44 +00004535std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4536 const sp<IBinder>& token) {
4537 for (const auto& it : mGestureMonitorsByDisplay) {
4538 const std::vector<Monitor>& monitors = it.second;
4539 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004540 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004541 return it.first;
4542 }
4543 }
4544 }
4545 return std::nullopt;
4546}
4547
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004548sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004549 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004550 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004551 }
4552
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004553 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004554 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004555 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004556 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 }
4558 }
Robert Carr4e670e52018-08-15 13:26:12 -07004559
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004560 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561}
4562
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004563void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
4564 removeByValue(mConnectionsByFd, connection);
4565}
4566
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004567void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4568 const sp<Connection>& connection, uint32_t seq,
4569 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004570 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4571 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572 commandEntry->connection = connection;
4573 commandEntry->eventTime = currentTime;
4574 commandEntry->seq = seq;
4575 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004576 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577}
4578
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004579void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4580 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004582 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004584 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4585 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004586 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004587 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588}
4589
chaviw0c06c6e2019-01-09 13:27:07 -08004590void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004591 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004592 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4593 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004594 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4595 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004596 commandEntry->oldToken = oldToken;
4597 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004598 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004599}
4600
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004601void InputDispatcher::onAnrLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004602 const sp<InputApplicationHandle>& applicationHandle,
4603 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4604 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4606 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4607 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004608 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4609 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4610 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611
4612 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004613 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614 struct tm tm;
4615 localtime_r(&t, &tm);
4616 char timestr[64];
4617 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004618 mLastAnrState.clear();
4619 mLastAnrState += INDENT "ANR:\n";
4620 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
4621 mLastAnrState +=
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004622 StringPrintf(INDENT2 "Window: %s\n",
4623 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004624 mLastAnrState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4625 mLastAnrState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4626 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason);
4627 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004629 std::unique_ptr<CommandEntry> commandEntry =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004630 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004632 commandEntry->inputChannel =
4633 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004635 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636}
4637
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004638void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639 mLock.unlock();
4640
4641 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4642
4643 mLock.lock();
4644}
4645
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004646void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647 sp<Connection> connection = commandEntry->connection;
4648
4649 if (connection->status != Connection::STATUS_ZOMBIE) {
4650 mLock.unlock();
4651
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004652 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653
4654 mLock.lock();
4655 }
4656}
4657
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004658void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004659 sp<IBinder> oldToken = commandEntry->oldToken;
4660 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004661 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004662 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004663 mLock.lock();
4664}
4665
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004666void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004667 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004668 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669 mLock.unlock();
4670
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004671 const nsecs_t timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004672 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673
4674 mLock.lock();
4675
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004676 resumeAfterTargetsNotReadyTimeoutLocked(timeoutExtension, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004677}
4678
4679void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4680 CommandEntry* commandEntry) {
4681 KeyEntry* entry = commandEntry->keyEntry;
4682
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004683 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684
4685 mLock.unlock();
4686
Michael Wright2b3c3302018-03-02 17:19:13 +00004687 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004688 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004689 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004690 : nullptr;
4691 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004692 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4693 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004694 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004695 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696
4697 mLock.lock();
4698
4699 if (delay < 0) {
4700 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4701 } else if (!delay) {
4702 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4703 } else {
4704 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4705 entry->interceptKeyWakeupTime = now() + delay;
4706 }
4707 entry->release();
4708}
4709
chaviwfd6d3512019-03-25 13:23:49 -07004710void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4711 mLock.unlock();
4712 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4713 mLock.lock();
4714}
4715
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004716void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004718 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004720 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721
4722 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004723 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004724 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004725 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004727 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004728
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004729 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004730 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004731 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4732 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004733 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004734 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004735
4736 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004737 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004738 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4739 restartEvent =
4740 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004741 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004742 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4743 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4744 handled);
4745 } else {
4746 restartEvent = false;
4747 }
4748
4749 // Dequeue the event and start the next cycle.
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004750 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004751 // contents of the wait queue to have been drained, so we need to double-check
4752 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004753 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4754 if (dispatchEntryIt != connection->waitQueue.end()) {
4755 dispatchEntry = *dispatchEntryIt;
4756 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004757 traceWaitQueueLength(connection);
4758 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004759 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004760 traceOutboundQueueLength(connection);
4761 } else {
4762 releaseDispatchEntry(dispatchEntry);
4763 }
4764 }
4765
4766 // Start the next dispatch cycle for this connection.
4767 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768}
4769
4770bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004771 DispatchEntry* dispatchEntry,
4772 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004773 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004774 if (!handled) {
4775 // Report the key as unhandled, since the fallback was not handled.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004776 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004777 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004778 return false;
4779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004781 // Get the fallback key state.
4782 // Clear it out after dispatching the UP.
4783 int32_t originalKeyCode = keyEntry->keyCode;
4784 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4785 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4786 connection->inputState.removeFallbackKey(originalKeyCode);
4787 }
4788
4789 if (handled || !dispatchEntry->hasForegroundTarget()) {
4790 // If the application handles the original key for which we previously
4791 // generated a fallback or if the window is not a foreground window,
4792 // then cancel the associated fallback key, if any.
4793 if (fallbackKeyCode != -1) {
4794 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004796 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004797 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4798 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4799 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004801 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004802 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803
4804 mLock.unlock();
4805
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004806 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004807 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808
4809 mLock.lock();
4810
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004811 // Cancel the fallback key.
4812 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004814 "application handled the original non-fallback key "
4815 "or is no longer a foreground target, "
4816 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817 options.keyCode = fallbackKeyCode;
4818 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004820 connection->inputState.removeFallbackKey(originalKeyCode);
4821 }
4822 } else {
4823 // If the application did not handle a non-fallback key, first check
4824 // that we are in a good state to perform unhandled key event processing
4825 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004826 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004827 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004829 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004830 "since this is not an initial down. "
4831 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4832 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004834 return false;
4835 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004837 // Dispatch the unhandled key to the policy.
4838#if DEBUG_OUTBOUND_EVENT_DETAILS
4839 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004840 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4841 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004842#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004843 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004844
4845 mLock.unlock();
4846
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004847 bool fallback =
4848 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4849 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004850
4851 mLock.lock();
4852
4853 if (connection->status != Connection::STATUS_NORMAL) {
4854 connection->inputState.removeFallbackKey(originalKeyCode);
4855 return false;
4856 }
4857
4858 // Latch the fallback keycode for this key on an initial down.
4859 // The fallback keycode cannot change at any other point in the lifecycle.
4860 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004862 fallbackKeyCode = event.getKeyCode();
4863 } else {
4864 fallbackKeyCode = AKEYCODE_UNKNOWN;
4865 }
4866 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4867 }
4868
4869 ALOG_ASSERT(fallbackKeyCode != -1);
4870
4871 // Cancel the fallback key if the policy decides not to send it anymore.
4872 // We will continue to dispatch the key to the policy but we will no
4873 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004874 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4875 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004876#if DEBUG_OUTBOUND_EVENT_DETAILS
4877 if (fallback) {
4878 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004879 "as a fallback for %d, but on the DOWN it had requested "
4880 "to send %d instead. Fallback canceled.",
4881 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004882 } else {
4883 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004884 "but on the DOWN it had requested to send %d. "
4885 "Fallback canceled.",
4886 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004887 }
4888#endif
4889
4890 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4891 "canceling fallback, policy no longer desires it");
4892 options.keyCode = fallbackKeyCode;
4893 synthesizeCancelationEventsForConnectionLocked(connection, options);
4894
4895 fallback = false;
4896 fallbackKeyCode = AKEYCODE_UNKNOWN;
4897 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004898 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004899 }
4900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901
4902#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004903 {
4904 std::string msg;
4905 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4906 connection->inputState.getFallbackKeys();
4907 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004908 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004910 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004911 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004912 }
4913#endif
4914
4915 if (fallback) {
4916 // Restart the dispatch cycle using the fallback key.
4917 keyEntry->eventTime = event.getEventTime();
4918 keyEntry->deviceId = event.getDeviceId();
4919 keyEntry->source = event.getSource();
4920 keyEntry->displayId = event.getDisplayId();
4921 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4922 keyEntry->keyCode = fallbackKeyCode;
4923 keyEntry->scanCode = event.getScanCode();
4924 keyEntry->metaState = event.getMetaState();
4925 keyEntry->repeatCount = event.getRepeatCount();
4926 keyEntry->downTime = event.getDownTime();
4927 keyEntry->syntheticRepeat = false;
4928
4929#if DEBUG_OUTBOUND_EVENT_DETAILS
4930 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004931 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4932 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004933#endif
4934 return true; // restart the event
4935 } else {
4936#if DEBUG_OUTBOUND_EVENT_DETAILS
4937 ALOGD("Unhandled key event: No fallback key.");
4938#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004939
4940 // Report the key as unhandled, since there is no fallback key.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004941 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942 }
4943 }
4944 return false;
4945}
4946
4947bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004948 DispatchEntry* dispatchEntry,
4949 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950 return false;
4951}
4952
4953void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4954 mLock.unlock();
4955
4956 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4957
4958 mLock.lock();
4959}
4960
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004961KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4962 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004963 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08004964 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
4965 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004966 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967}
4968
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004969void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
4970 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971 // TODO Write some statistics about how long we spend waiting.
4972}
4973
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004974/**
4975 * Report the touch event latency to the statsd server.
4976 * Input events are reported for statistics if:
4977 * - This is a touchscreen event
4978 * - InputFilter is not enabled
4979 * - Event is not injected or synthesized
4980 *
4981 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4982 * from getting aggregated with the "old" data.
4983 */
4984void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4985 REQUIRES(mLock) {
4986 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4987 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4988 if (!reportForStatistics) {
4989 return;
4990 }
4991
4992 if (mTouchStatistics.shouldReport()) {
4993 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4994 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4995 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4996 mTouchStatistics.reset();
4997 }
4998 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4999 mTouchStatistics.addValue(latencyMicros);
5000}
5001
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002void InputDispatcher::traceInboundQueueLengthLocked() {
5003 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005004 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005005 }
5006}
5007
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005008void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009 if (ATRACE_ENABLED()) {
5010 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005011 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005012 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013 }
5014}
5015
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005016void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005017 if (ATRACE_ENABLED()) {
5018 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005019 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005020 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021 }
5022}
5023
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005024void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005025 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005026
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005027 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005028 dumpDispatchStateLocked(dump);
5029
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005030 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005031 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005032 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005033 }
5034}
5035
5036void InputDispatcher::monitor() {
5037 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005038 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005040 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041}
5042
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005043/**
5044 * Wake up the dispatcher and wait until it processes all events and commands.
5045 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5046 * this method can be safely called from any thread, as long as you've ensured that
5047 * the work you are interested in completing has already been queued.
5048 */
5049bool InputDispatcher::waitForIdle() {
5050 /**
5051 * Timeout should represent the longest possible time that a device might spend processing
5052 * events and commands.
5053 */
5054 constexpr std::chrono::duration TIMEOUT = 100ms;
5055 std::unique_lock lock(mLock);
5056 mLooper->wake();
5057 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5058 return result == std::cv_status::no_timeout;
5059}
5060
Garfield Tane84e6f92019-08-29 17:28:41 -07005061} // namespace android::inputdispatcher