blob: 23dec769c8b2ea4e94c319fe590fa92a92795a9d [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 Vishniakoucf179f12020-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 Vishniakou4cb50ca2020-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 Vishniakoucf179f12020-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 Tan6a5a14e2020-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 Vishniakouf0007dd2020-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 Arriagac6ae4bb2020-04-16 18:46:48 -0700373 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500374}
375
Edgar Arriagac6ae4bb2020-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 Arriagac6ae4bb2020-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 Tanff1f1bb2020-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 Vishniakou850ce122020-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));
655 sp<InputWindowHandle> touchedWindowHandle =
656 findTouchedWindowAtLocked(displayId, x, y, nullptr);
657 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 Vishniakou850ce122020-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 Vishniakou850ce122020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-03-24 19:50:03 -0700756 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800757 }
Siarhei Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakouf0007dd2020-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 Tanff1f1bb2020-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 Tanff1f1bb2020-01-28 13:24:04 -0800957 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-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 Vishniakou850ce122020-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 Tanff1f1bb2020-01-28 13:24:04 -08001015 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakou850ce122020-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 Vishniakoucf179f12020-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 Tan6a5a14e2020-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 Vishniakou767917f2020-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 Vishniakou767917f2020-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 Vishniakou4700f822020-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 Vishniakoucf179f12020-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 Vishniakouf0007dd2020-04-13 11:40:37 -07001314 ALOGI("Waiting for application to become ready for input: %s. Reason: %s",
1315 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001316 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 Vishniakou4cb50ca2020-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 Vishniakou4700f822020-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 Vishniakou4cb50ca2020-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 Vishniakou4cb50ca2020-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 Vishniakou767917f2020-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 Vishniakou767917f2020-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 Vishniakou767917f2020-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 Vishniakou767917f2020-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 Vishniakou767917f2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-03-24 19:50:03 -07001507 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-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 Vishniakou33eceeb2020-03-24 19:50:03 -07001512 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001513 }
1514
Siarhei Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-03-24 19:50:03 -07001528 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-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 Vishniakou33eceeb2020-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 Vishniakouf0007dd2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-03-24 19:50:03 -07001628 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 }
1630
Siarhei Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-03-24 19:50:03 -07001653 tempTouchState.getFirstForegroundWindowHandle();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-03-24 19:50:03 -07001728 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001729 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou767917f2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou33eceeb2020-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 Vishniakou767917f2020-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 Vishniakou767917f2020-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 Vishniakou767917f2020-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 Vishniakou767917f2020-03-24 20:49:09 -07001853 tempTouchState.reset();
1854 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1855 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1856 tempTouchState.deviceId = entry.deviceId;
1857 tempTouchState.source = entry.source;
1858 tempTouchState.displayId = displayId;
1859 }
1860 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1861 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1862 // All pointers up or canceled.
1863 tempTouchState.reset();
1864 } 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 Vishniakou767917f2020-03-24 20:49:09 -07001878 for (size_t i = 0; i < tempTouchState.windows.size();) {
1879 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1880 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1881 touchedWindow.pointerIds.clearBit(pointerId);
1882 if (touchedWindow.pointerIds.isEmpty()) {
1883 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1884 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 }
Siarhei Vishniakou767917f2020-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 Vishniakou767917f2020-03-24 20:49:09 -07001890 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001891
Siarhei Vishniakou767917f2020-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) {
1895 if (tempTouchState.displayId >= 0) {
1896 mTouchStatesByDisplay[displayId] = tempTouchState;
1897 } else {
1898 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901
Siarhei Vishniakou767917f2020-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 Carrc9bf1d32020-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;
Chris Yefcdff3e2020-05-10 15:16:04 -07002010 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002011 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 Carrc9bf1d32020-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 Carrc9bf1d32020-04-13 17:21:08 -07002027 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002028 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 Carrc9bf1d32020-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 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002043 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002044 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002045 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002046 return true;
2047 }
2048 }
2049 return false;
2050}
2051
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002052std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
2053 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002054 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07002055 // If the window is paused then keep waiting.
2056 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002057 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002058 }
2059
2060 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07002061 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002062 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002063 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002064 "registered with the input dispatcher. The window may be in the "
2065 "process of being removed.",
2066 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002067 }
2068
2069 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07002070 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002071 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002072 "The window may be in the process of being removed.",
2073 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07002074 }
2075
2076 // If the connection is backed up then keep waiting.
2077 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002078 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002079 "Outbound queue length: %zu. Wait queue length: %zu.",
2080 targetType, connection->outboundQueue.size(),
2081 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07002082 }
2083
2084 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002085 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07002086 // If the event is a key event, then we must wait for all previous events to
2087 // complete before delivering it because previous events may have the
2088 // side-effect of transferring focus to a different window and we want to
2089 // ensure that the following keys are sent to the new window.
2090 //
2091 // Suppose the user touches a button in a window then immediately presses "A".
2092 // If the button causes a pop-up window to appear then we want to ensure that
2093 // the "A" key is delivered to the new pop-up window. This is because users
2094 // often anticipate pending UI changes when typing on a keyboard.
2095 // To obtain this behavior, we must serialize key events with respect to all
2096 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002097 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002098 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002099 "finished processing all of the input events that were previously "
2100 "delivered to it. Outbound queue length: %zu. Wait queue length: "
2101 "%zu.",
2102 targetType, connection->outboundQueue.size(),
2103 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 }
Jeff Brownffb49772014-10-10 19:01:34 -07002105 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 // Touch events can always be sent to a window immediately because the user intended
2107 // to touch whatever was visible at the time. Even if focus changes or a new
2108 // window appears moments later, the touch event was meant to be delivered to
2109 // whatever window happened to be on screen at the time.
2110 //
2111 // Generic motion events, such as trackball or joystick events are a little trickier.
2112 // Like key events, generic motion events are delivered to the focused window.
2113 // Unlike key events, generic motion events don't tend to transfer focus to other
2114 // windows and it is not important for them to be serialized. So we prefer to deliver
2115 // generic motion events as soon as possible to improve efficiency and reduce lag
2116 // through batching.
2117 //
2118 // The one case where we pause input event delivery is when the wait queue is piling
2119 // up with lots of events because the application is not responding.
2120 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002121 if (!connection->waitQueue.empty() &&
2122 currentTime >=
2123 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002124 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002125 "finished processing certain input events that were delivered to "
2126 "it over "
2127 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
2128 "%0.1fms.",
2129 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
2130 connection->waitQueue.size(),
2131 (currentTime - connection->waitQueue.front()->deliveryTime) *
2132 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133 }
2134 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002135 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136}
2137
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002138std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 const sp<InputApplicationHandle>& applicationHandle,
2140 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002141 if (applicationHandle != nullptr) {
2142 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002143 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 } else {
2145 return applicationHandle->getName();
2146 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002147 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002148 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002150 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151 }
2152}
2153
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002154void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002155 if (eventEntry.type == EventEntry::Type::FOCUS) {
2156 // Focus events are passed to apps, but do not represent user activity.
2157 return;
2158 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002159 int32_t displayId = getTargetDisplayId(eventEntry);
2160 sp<InputWindowHandle> focusedWindowHandle =
2161 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2162 if (focusedWindowHandle != nullptr) {
2163 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2165#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002166 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167#endif
2168 return;
2169 }
2170 }
2171
2172 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002173 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002174 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002175 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2176 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002177 return;
2178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002179
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002180 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002181 eventType = USER_ACTIVITY_EVENT_TOUCH;
2182 }
2183 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002185 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002186 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2187 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002188 return;
2189 }
2190 eventType = USER_ACTIVITY_EVENT_BUTTON;
2191 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002193 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002194 case EventEntry::Type::CONFIGURATION_CHANGED:
2195 case EventEntry::Type::DEVICE_RESET: {
2196 LOG_ALWAYS_FATAL("%s events are not user activity",
2197 EventEntry::typeToString(eventEntry.type));
2198 break;
2199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 }
2201
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002202 std::unique_ptr<CommandEntry> commandEntry =
2203 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002204 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002206 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207}
2208
2209void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002210 const sp<Connection>& connection,
2211 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002212 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002213 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002214 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002215 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002216 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002217 ATRACE_NAME(message.c_str());
2218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219#if DEBUG_DISPATCH_CYCLE
2220 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002221 "globalScaleFactor=%f, pointerIds=0x%x %s",
2222 connection->getInputChannelName().c_str(), inputTarget.flags,
2223 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2224 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225#endif
2226
2227 // Skip this event if the connection status is not normal.
2228 // We don't want to enqueue additional outbound events if the connection is broken.
2229 if (connection->status != Connection::STATUS_NORMAL) {
2230#if DEBUG_DISPATCH_CYCLE
2231 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002232 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233#endif
2234 return;
2235 }
2236
2237 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002238 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2239 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2240 "Entry type %s should not have FLAG_SPLIT",
2241 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002243 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002244 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002245 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002246 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 if (!splitMotionEntry) {
2248 return; // split event was dropped
2249 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002250 if (DEBUG_FOCUS) {
2251 ALOGD("channel '%s' ~ Split motion event.",
2252 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002253 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002254 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002255 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 splitMotionEntry->release();
2257 return;
2258 }
2259 }
2260
2261 // Not splitting. Enqueue dispatch entries for the event as is.
2262 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2263}
2264
2265void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002266 const sp<Connection>& connection,
2267 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002268 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002269 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002270 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002271 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002272 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002273 ATRACE_NAME(message.c_str());
2274 }
2275
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002276 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277
2278 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002279 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002280 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002281 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002282 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002283 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002284 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002285 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002286 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002287 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002288 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002289 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002290 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291
2292 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002293 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 startDispatchCycleLocked(currentTime, connection);
2295 }
2296}
2297
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002298void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2299 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002300 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002301 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002302 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002303 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2304 connection->getInputChannelName().c_str(),
2305 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002306 ATRACE_NAME(message.c_str());
2307 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002308 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 if (!(inputTargetFlags & dispatchMode)) {
2310 return;
2311 }
2312 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2313
2314 // This is a new event.
2315 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002316 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002317 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002319 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2320 // different EventEntry than what was passed in.
2321 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002323 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002324 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002325 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002326 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002327 dispatchEntry->resolvedAction = keyEntry.action;
2328 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002330 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2331 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002333 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2334 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002336 return; // skip the inconsistent event
2337 }
2338 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002341 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002342 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002343 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2344 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2345 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2346 static_cast<int32_t>(IdGenerator::Source::OTHER);
2347 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002348 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2349 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2350 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2351 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2352 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2353 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2354 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2355 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2356 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2357 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2358 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002359 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002360 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002361 }
2362 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002363 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2364 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002366 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2367 "event",
2368 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002370 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002373 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002374 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2375 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2376 }
2377 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2378 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002381 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2382 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002384 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2385 "event",
2386 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002388 return; // skip the inconsistent event
2389 }
2390
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002391 dispatchEntry->resolvedEventId =
2392 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2393 ? mIdGenerator.nextId()
2394 : motionEntry.id;
2395 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2396 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2397 ") to MotionEvent(id=0x%" PRIx32 ").",
2398 motionEntry.id, dispatchEntry->resolvedEventId);
2399 ATRACE_NAME(message.c_str());
2400 }
2401
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002402 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002403 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002404
2405 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002407 case EventEntry::Type::FOCUS: {
2408 break;
2409 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002410 case EventEntry::Type::CONFIGURATION_CHANGED:
2411 case EventEntry::Type::DEVICE_RESET: {
2412 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002413 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002414 break;
2415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416 }
2417
2418 // Remember that we are waiting for this dispatch to complete.
2419 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002420 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 }
2422
2423 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002424 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002425 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002426}
2427
Siarhei Vishniakoucf179f12020-04-09 11:16:18 -07002428/**
2429 * This function is purely for debugging. It helps us understand where the user interaction
2430 * was taking place. For example, if user is touching launcher, we will see a log that user
2431 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2432 * We will see both launcher and wallpaper in that list.
2433 * Once the interaction with a particular set of connections starts, no new logs will be printed
2434 * until the set of interacted connections changes.
2435 *
2436 * The following items are skipped, to reduce the logspam:
2437 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2438 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2439 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2440 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2441 * Both of those ACTION_UP events would not be logged
2442 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2443 * will not be logged. This is omitted to reduce the amount of data printed.
2444 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2445 * gesture monitor is the only connection receiving the remainder of the gesture.
2446 */
2447void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2448 const std::vector<InputTarget>& targets) {
2449 // Skip ACTION_UP events, and all events other than keys and motions
2450 if (entry.type == EventEntry::Type::KEY) {
2451 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2452 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2453 return;
2454 }
2455 } else if (entry.type == EventEntry::Type::MOTION) {
2456 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2457 if (motionEntry.action == AMOTION_EVENT_ACTION_UP) {
2458 return;
2459 }
2460 } else {
2461 return; // Not a key or a motion
2462 }
2463
2464 std::unordered_set<sp<IBinder>, IBinderHash> newConnections;
2465 for (const InputTarget& target : targets) {
2466 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2467 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2468 continue; // Skip windows that receive ACTION_OUTSIDE
2469 }
2470
2471 sp<IBinder> token = target.inputChannel->getConnectionToken();
2472 sp<Connection> connection = getConnectionLocked(token); // get connection
2473 if (connection->monitor) {
2474 continue; // We only need to keep track of the non-monitor connections.
2475 }
2476
2477 newConnections.insert(std::move(token));
2478 }
2479 if (newConnections == mInteractionConnections) {
2480 return; // no change
2481 }
2482 mInteractionConnections = newConnections;
2483 std::string windowList;
2484 for (const sp<IBinder>& token : newConnections) {
2485 sp<Connection> connection = getConnectionLocked(token);
2486 windowList += connection->getWindowName() + ", ";
2487 }
2488 std::string message = "Interaction with windows: " + windowList;
2489 if (windowList.empty()) {
2490 message += "<none>";
2491 }
2492 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2493}
2494
chaviwfd6d3512019-03-25 13:23:49 -07002495void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002496 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002497 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002498 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2499 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002500 return;
2501 }
2502
2503 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2504 if (inputWindowHandle == nullptr) {
2505 return;
2506 }
2507
chaviw8c9cf542019-03-25 13:02:48 -07002508 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002509 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002510
2511 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2512
2513 if (!hasFocusChanged) {
2514 return;
2515 }
2516
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002517 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2518 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002519 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002520 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521}
2522
2523void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002524 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002525 if (ATRACE_ENABLED()) {
2526 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002527 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002528 ATRACE_NAME(message.c_str());
2529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002531 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532#endif
2533
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002534 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2535 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536 dispatchEntry->deliveryTime = currentTime;
2537
2538 // Publish the event.
2539 status_t status;
2540 EventEntry* eventEntry = dispatchEntry->eventEntry;
2541 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002542 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002543 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2544 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002546 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002547 status =
2548 connection->inputPublisher
2549 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2550 keyEntry->deviceId, keyEntry->source,
2551 keyEntry->displayId, std::move(hmac),
2552 dispatchEntry->resolvedAction,
2553 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2554 keyEntry->scanCode, keyEntry->metaState,
2555 keyEntry->repeatCount, keyEntry->downTime,
2556 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002557 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558 }
2559
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002560 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002563 PointerCoords scaledCoords[MAX_POINTERS];
2564 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2565
chaviw82357092020-01-28 13:13:06 -08002566 // Set the X and Y offset and X and Y scale depending on the input source.
2567 float xOffset = 0.0f, yOffset = 0.0f;
2568 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002569 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2570 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2571 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002572 xScale = dispatchEntry->windowXScale;
2573 yScale = dispatchEntry->windowYScale;
2574 xOffset = dispatchEntry->xOffset * xScale;
2575 yOffset = dispatchEntry->yOffset * yScale;
2576 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2578 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002579 // Don't apply window scale here since we don't want scale to affect raw
2580 // coordinates. The scale will be sent back to the client and applied
2581 // later when requesting relative coordinates.
2582 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2583 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002584 }
2585 usingCoords = scaledCoords;
2586 }
2587 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002588 // We don't want the dispatch target to know.
2589 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2590 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2591 scaledCoords[i].clear();
2592 }
2593 usingCoords = scaledCoords;
2594 }
2595 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002596
2597 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002598
2599 // Publish the motion event.
2600 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002601 .publishMotionEvent(dispatchEntry->seq,
2602 dispatchEntry->resolvedEventId,
2603 motionEntry->deviceId, motionEntry->source,
2604 motionEntry->displayId, std::move(hmac),
2605 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002606 motionEntry->actionButton,
2607 dispatchEntry->resolvedFlags,
2608 motionEntry->edgeFlags, motionEntry->metaState,
2609 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002610 motionEntry->classification, xScale, yScale,
2611 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002612 motionEntry->yPrecision,
2613 motionEntry->xCursorPosition,
2614 motionEntry->yCursorPosition,
2615 motionEntry->downTime, motionEntry->eventTime,
2616 motionEntry->pointerCount,
2617 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002618 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002619 break;
2620 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002621 case EventEntry::Type::FOCUS: {
2622 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2623 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002624 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002625 focusEntry->hasFocus,
2626 mInTouchMode);
2627 break;
2628 }
2629
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002630 case EventEntry::Type::CONFIGURATION_CHANGED:
2631 case EventEntry::Type::DEVICE_RESET: {
2632 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2633 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002634 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002635 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002636 }
2637
2638 // Check the result.
2639 if (status) {
2640 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002641 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002643 "This is unexpected because the wait queue is empty, so the pipe "
2644 "should be empty and we shouldn't have any problems writing an "
2645 "event to it, status=%d",
2646 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2648 } else {
2649 // Pipe is full and we are waiting for the app to finish process some events
2650 // before sending more events to it.
2651#if DEBUG_DISPATCH_CYCLE
2652 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002653 "waiting for the application to catch up",
2654 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655#endif
2656 connection->inputPublisherBlocked = true;
2657 }
2658 } else {
2659 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002660 "status=%d",
2661 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2663 }
2664 return;
2665 }
2666
2667 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002668 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2669 connection->outboundQueue.end(),
2670 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002671 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002672 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002673 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674 }
2675}
2676
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002677const std::array<uint8_t, 32> InputDispatcher::getSignature(
2678 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2679 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2680 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2681 // Only sign events up and down events as the purely move events
2682 // are tied to their up/down counterparts so signing would be redundant.
2683 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2684 verifiedEvent.actionMasked = actionMasked;
2685 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2686 return mHmacKeyManager.sign(verifiedEvent);
2687 }
2688 return INVALID_HMAC;
2689}
2690
2691const std::array<uint8_t, 32> InputDispatcher::getSignature(
2692 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2693 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2694 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2695 verifiedEvent.action = dispatchEntry.resolvedAction;
2696 return mHmacKeyManager.sign(verifiedEvent);
2697}
2698
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002700 const sp<Connection>& connection, uint32_t seq,
2701 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702#if DEBUG_DISPATCH_CYCLE
2703 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002704 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705#endif
2706
2707 connection->inputPublisherBlocked = false;
2708
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002709 if (connection->status == Connection::STATUS_BROKEN ||
2710 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 return;
2712 }
2713
2714 // Notify other system components and prepare to start the next dispatch cycle.
2715 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2716}
2717
2718void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002719 const sp<Connection>& connection,
2720 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721#if DEBUG_DISPATCH_CYCLE
2722 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002723 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724#endif
2725
2726 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002727 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002728 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002729 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002730 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002731
2732 // The connection appears to be unrecoverably broken.
2733 // Ignore already broken or zombie connections.
2734 if (connection->status == Connection::STATUS_NORMAL) {
2735 connection->status = Connection::STATUS_BROKEN;
2736
2737 if (notify) {
2738 // Notify other system components.
2739 onDispatchCycleBrokenLocked(currentTime, connection);
2740 }
2741 }
2742}
2743
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002744void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2745 while (!queue.empty()) {
2746 DispatchEntry* dispatchEntry = queue.front();
2747 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002748 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749 }
2750}
2751
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002752void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002754 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755 }
2756 delete dispatchEntry;
2757}
2758
2759int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2760 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2761
2762 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002763 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002765 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002767 "fd=%d, events=0x%x",
2768 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 return 0; // remove the callback
2770 }
2771
2772 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002773 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2775 if (!(events & ALOOPER_EVENT_INPUT)) {
2776 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002777 "events=0x%x",
2778 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779 return 1;
2780 }
2781
2782 nsecs_t currentTime = now();
2783 bool gotOne = false;
2784 status_t status;
2785 for (;;) {
2786 uint32_t seq;
2787 bool handled;
2788 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2789 if (status) {
2790 break;
2791 }
2792 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2793 gotOne = true;
2794 }
2795 if (gotOne) {
2796 d->runCommandsLockedInterruptible();
2797 if (status == WOULD_BLOCK) {
2798 return 1;
2799 }
2800 }
2801
2802 notify = status != DEAD_OBJECT || !connection->monitor;
2803 if (notify) {
2804 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002805 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806 }
2807 } else {
2808 // Monitor channels are never explicitly unregistered.
2809 // We do it automatically when the remote endpoint is closed so don't warn
2810 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002811 const bool stillHaveWindowHandle =
2812 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2813 nullptr;
2814 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815 if (notify) {
2816 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002817 "events=0x%x",
2818 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819 }
2820 }
2821
2822 // Unregister the channel.
2823 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2824 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002825 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826}
2827
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002828void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002830 for (const auto& pair : mConnectionsByFd) {
2831 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832 }
2833}
2834
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002835void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002836 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002837 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2838 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2839}
2840
2841void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2842 const CancelationOptions& options,
2843 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2844 for (const auto& it : monitorsByDisplay) {
2845 const std::vector<Monitor>& monitors = it.second;
2846 for (const Monitor& monitor : monitors) {
2847 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002848 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002849 }
2850}
2851
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2853 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002854 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002855 if (connection == nullptr) {
2856 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002857 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002858
2859 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860}
2861
2862void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2863 const sp<Connection>& connection, const CancelationOptions& options) {
2864 if (connection->status == Connection::STATUS_BROKEN) {
2865 return;
2866 }
2867
2868 nsecs_t currentTime = now();
2869
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002870 std::vector<EventEntry*> cancelationEvents =
2871 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002873 if (cancelationEvents.empty()) {
2874 return;
2875 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002877 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2878 "with reality: %s, mode=%d.",
2879 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2880 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002882
2883 InputTarget target;
2884 sp<InputWindowHandle> windowHandle =
2885 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2886 if (windowHandle != nullptr) {
2887 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2888 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2889 windowInfo->windowXScale, windowInfo->windowYScale);
2890 target.globalScaleFactor = windowInfo->globalScaleFactor;
2891 }
2892 target.inputChannel = connection->inputChannel;
2893 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2894
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002895 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2896 EventEntry* cancelationEventEntry = cancelationEvents[i];
2897 switch (cancelationEventEntry->type) {
2898 case EventEntry::Type::KEY: {
2899 logOutboundKeyDetails("cancel - ",
2900 static_cast<const KeyEntry&>(*cancelationEventEntry));
2901 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002903 case EventEntry::Type::MOTION: {
2904 logOutboundMotionDetails("cancel - ",
2905 static_cast<const MotionEntry&>(*cancelationEventEntry));
2906 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002908 case EventEntry::Type::FOCUS: {
2909 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2910 break;
2911 }
2912 case EventEntry::Type::CONFIGURATION_CHANGED:
2913 case EventEntry::Type::DEVICE_RESET: {
2914 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2915 EventEntry::typeToString(cancelationEventEntry->type));
2916 break;
2917 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918 }
2919
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002920 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2921 target, InputTarget::FLAG_DISPATCH_AS_IS);
2922
2923 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002925
2926 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927}
2928
Svet Ganov5d3bc372020-01-26 23:11:07 -08002929void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2930 const sp<Connection>& connection) {
2931 if (connection->status == Connection::STATUS_BROKEN) {
2932 return;
2933 }
2934
2935 nsecs_t currentTime = now();
2936
2937 std::vector<EventEntry*> downEvents =
2938 connection->inputState.synthesizePointerDownEvents(currentTime);
2939
2940 if (downEvents.empty()) {
2941 return;
2942 }
2943
2944#if DEBUG_OUTBOUND_EVENT_DETAILS
2945 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2946 connection->getInputChannelName().c_str(), downEvents.size());
2947#endif
2948
2949 InputTarget target;
2950 sp<InputWindowHandle> windowHandle =
2951 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2952 if (windowHandle != nullptr) {
2953 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2954 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2955 windowInfo->windowXScale, windowInfo->windowYScale);
2956 target.globalScaleFactor = windowInfo->globalScaleFactor;
2957 }
2958 target.inputChannel = connection->inputChannel;
2959 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2960
2961 for (EventEntry* downEventEntry : downEvents) {
2962 switch (downEventEntry->type) {
2963 case EventEntry::Type::MOTION: {
2964 logOutboundMotionDetails("down - ",
2965 static_cast<const MotionEntry&>(*downEventEntry));
2966 break;
2967 }
2968
2969 case EventEntry::Type::KEY:
2970 case EventEntry::Type::FOCUS:
2971 case EventEntry::Type::CONFIGURATION_CHANGED:
2972 case EventEntry::Type::DEVICE_RESET: {
2973 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2974 EventEntry::typeToString(downEventEntry->type));
2975 break;
2976 }
2977 }
2978
2979 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2980 target, InputTarget::FLAG_DISPATCH_AS_IS);
2981
2982 downEventEntry->release();
2983 }
2984
2985 startDispatchCycleLocked(currentTime, connection);
2986}
2987
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002988MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002989 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002990 ALOG_ASSERT(pointerIds.value != 0);
2991
2992 uint32_t splitPointerIndexMap[MAX_POINTERS];
2993 PointerProperties splitPointerProperties[MAX_POINTERS];
2994 PointerCoords splitPointerCoords[MAX_POINTERS];
2995
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002996 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997 uint32_t splitPointerCount = 0;
2998
2999 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003000 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003002 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003 uint32_t pointerId = uint32_t(pointerProperties.id);
3004 if (pointerIds.hasBit(pointerId)) {
3005 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3006 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3007 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003008 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 splitPointerCount += 1;
3010 }
3011 }
3012
3013 if (splitPointerCount != pointerIds.count()) {
3014 // This is bad. We are missing some of the pointers that we expected to deliver.
3015 // Most likely this indicates that we received an ACTION_MOVE events that has
3016 // different pointer ids than we expected based on the previous ACTION_DOWN
3017 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3018 // in this way.
3019 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003020 "we expected there to be %d pointers. This probably means we received "
3021 "a broken sequence of pointer ids from the input device.",
3022 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003023 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024 }
3025
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003026 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003027 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003028 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3029 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3031 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003032 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033 uint32_t pointerId = uint32_t(pointerProperties.id);
3034 if (pointerIds.hasBit(pointerId)) {
3035 if (pointerIds.count() == 1) {
3036 // The first/last pointer went down/up.
3037 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003038 ? AMOTION_EVENT_ACTION_DOWN
3039 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003040 } else {
3041 // A secondary pointer went down/up.
3042 uint32_t splitPointerIndex = 0;
3043 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3044 splitPointerIndex += 1;
3045 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 action = maskedAction |
3047 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048 }
3049 } else {
3050 // An unrelated pointer changed.
3051 action = AMOTION_EVENT_ACTION_MOVE;
3052 }
3053 }
3054
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003055 int32_t newId = mIdGenerator.nextId();
3056 if (ATRACE_ENABLED()) {
3057 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3058 ") to MotionEvent(id=0x%" PRIx32 ").",
3059 originalMotionEntry.id, newId);
3060 ATRACE_NAME(message.c_str());
3061 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003062 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003063 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3064 originalMotionEntry.source, originalMotionEntry.displayId,
3065 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003066 originalMotionEntry.actionButton, originalMotionEntry.flags,
3067 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3068 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3069 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3070 originalMotionEntry.xCursorPosition,
3071 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003072 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003074 if (originalMotionEntry.injectionState) {
3075 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003076 splitMotionEntry->injectionState->refCount += 1;
3077 }
3078
3079 return splitMotionEntry;
3080}
3081
3082void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3083#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003084 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085#endif
3086
3087 bool needWake;
3088 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003089 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090
Prabir Pradhan42611e02018-11-27 14:04:02 -08003091 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003092 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093 needWake = enqueueInboundEventLocked(newEntry);
3094 } // release lock
3095
3096 if (needWake) {
3097 mLooper->wake();
3098 }
3099}
3100
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003101/**
3102 * If one of the meta shortcuts is detected, process them here:
3103 * Meta + Backspace -> generate BACK
3104 * Meta + Enter -> generate HOME
3105 * This will potentially overwrite keyCode and metaState.
3106 */
3107void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003108 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003109 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3110 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3111 if (keyCode == AKEYCODE_DEL) {
3112 newKeyCode = AKEYCODE_BACK;
3113 } else if (keyCode == AKEYCODE_ENTER) {
3114 newKeyCode = AKEYCODE_HOME;
3115 }
3116 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003117 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003118 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003119 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003120 keyCode = newKeyCode;
3121 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3122 }
3123 } else if (action == AKEY_EVENT_ACTION_UP) {
3124 // In order to maintain a consistent stream of up and down events, check to see if the key
3125 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3126 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003127 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003128 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003129 auto replacementIt = mReplacedKeys.find(replacement);
3130 if (replacementIt != mReplacedKeys.end()) {
3131 keyCode = replacementIt->second;
3132 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003133 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3134 }
3135 }
3136}
3137
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3139#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003140 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3141 "policyFlags=0x%x, action=0x%x, "
3142 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3143 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3144 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3145 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146#endif
3147 if (!validateKeyEvent(args->action)) {
3148 return;
3149 }
3150
3151 uint32_t policyFlags = args->policyFlags;
3152 int32_t flags = args->flags;
3153 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003154 // InputDispatcher tracks and generates key repeats on behalf of
3155 // whatever notifies it, so repeatCount should always be set to 0
3156 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3158 policyFlags |= POLICY_FLAG_VIRTUAL;
3159 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 if (policyFlags & POLICY_FLAG_FUNCTION) {
3162 metaState |= AMETA_FUNCTION_ON;
3163 }
3164
3165 policyFlags |= POLICY_FLAG_TRUSTED;
3166
Michael Wright78f24442014-08-06 15:55:28 -07003167 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003168 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003169
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003171 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003172 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3173 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174
Michael Wright2b3c3302018-03-02 17:19:13 +00003175 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003177 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3178 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003179 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 bool needWake;
3183 { // acquire lock
3184 mLock.lock();
3185
3186 if (shouldSendKeyToInputFilterLocked(args)) {
3187 mLock.unlock();
3188
3189 policyFlags |= POLICY_FLAG_FILTERED;
3190 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3191 return; // event was consumed by the filter
3192 }
3193
3194 mLock.lock();
3195 }
3196
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003197 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003198 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003199 args->displayId, policyFlags, args->action, flags, keyCode,
3200 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201
3202 needWake = enqueueInboundEventLocked(newEntry);
3203 mLock.unlock();
3204 } // release lock
3205
3206 if (needWake) {
3207 mLooper->wake();
3208 }
3209}
3210
3211bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3212 return mInputFilterEnabled;
3213}
3214
3215void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3216#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003217 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3218 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003219 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3220 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003221 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003222 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3223 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3224 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3225 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 for (uint32_t i = 0; i < args->pointerCount; i++) {
3227 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003228 "x=%f, y=%f, pressure=%f, size=%f, "
3229 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3230 "orientation=%f",
3231 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3232 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3233 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3234 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3235 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3236 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3237 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3238 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3239 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3240 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 }
3242#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3244 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 return;
3246 }
3247
3248 uint32_t policyFlags = args->policyFlags;
3249 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003250
3251 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003252 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003253 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3254 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003255 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003256 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257
3258 bool needWake;
3259 { // acquire lock
3260 mLock.lock();
3261
3262 if (shouldSendMotionToInputFilterLocked(args)) {
3263 mLock.unlock();
3264
3265 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003266 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3267 args->action, args->actionButton, args->flags, args->edgeFlags,
3268 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3269 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3270 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3271 args->downTime, args->eventTime, args->pointerCount,
3272 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273
3274 policyFlags |= POLICY_FLAG_FILTERED;
3275 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3276 return; // event was consumed by the filter
3277 }
3278
3279 mLock.lock();
3280 }
3281
3282 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003283 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003284 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003285 args->displayId, policyFlags, args->action, args->actionButton,
3286 args->flags, args->metaState, args->buttonState,
3287 args->classification, args->edgeFlags, args->xPrecision,
3288 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3289 args->downTime, args->pointerCount, args->pointerProperties,
3290 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291
3292 needWake = enqueueInboundEventLocked(newEntry);
3293 mLock.unlock();
3294 } // release lock
3295
3296 if (needWake) {
3297 mLooper->wake();
3298 }
3299}
3300
3301bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003302 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303}
3304
3305void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3306#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003307 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003308 "switchMask=0x%08x",
3309 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310#endif
3311
3312 uint32_t policyFlags = args->policyFlags;
3313 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003314 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315}
3316
3317void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3318#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003319 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3320 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321#endif
3322
3323 bool needWake;
3324 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003325 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326
Prabir Pradhan42611e02018-11-27 14:04:02 -08003327 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003328 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329 needWake = enqueueInboundEventLocked(newEntry);
3330 } // release lock
3331
3332 if (needWake) {
3333 mLooper->wake();
3334 }
3335}
3336
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3338 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003339 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340#if DEBUG_INBOUND_EVENT_DETAILS
3341 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003342 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3343 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344#endif
3345
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003346 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347
3348 policyFlags |= POLICY_FLAG_INJECTED;
3349 if (hasInjectionPermission(injectorPid, injectorUid)) {
3350 policyFlags |= POLICY_FLAG_TRUSTED;
3351 }
3352
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003353 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003355 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003356 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3357 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003358 if (!validateKeyEvent(action)) {
3359 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003362 int32_t flags = incomingKey.getFlags();
3363 int32_t keyCode = incomingKey.getKeyCode();
3364 int32_t metaState = incomingKey.getMetaState();
3365 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003367 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003368 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003369 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3370 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3371 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003373 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3374 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003375 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003376
3377 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3378 android::base::Timer t;
3379 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3380 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3381 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3382 std::to_string(t.duration().count()).c_str());
3383 }
3384 }
3385
3386 mLock.lock();
3387 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003388 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3389 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003390 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3391 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003392 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003393 injectedEntries.push(injectedEntry);
3394 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 }
3396
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003397 case AINPUT_EVENT_TYPE_MOTION: {
3398 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3399 int32_t action = motionEvent->getAction();
3400 size_t pointerCount = motionEvent->getPointerCount();
3401 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3402 int32_t actionButton = motionEvent->getActionButton();
3403 int32_t displayId = motionEvent->getDisplayId();
3404 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3405 return INPUT_EVENT_INJECTION_FAILED;
3406 }
3407
3408 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3409 nsecs_t eventTime = motionEvent->getEventTime();
3410 android::base::Timer t;
3411 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3412 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3413 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3414 std::to_string(t.duration().count()).c_str());
3415 }
3416 }
3417
3418 mLock.lock();
3419 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3420 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3421 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003422 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3423 motionEvent->getSource(), motionEvent->getDisplayId(),
3424 policyFlags, action, actionButton, motionEvent->getFlags(),
3425 motionEvent->getMetaState(), motionEvent->getButtonState(),
3426 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3427 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003428 motionEvent->getRawXCursorPosition(),
3429 motionEvent->getRawYCursorPosition(),
3430 motionEvent->getDownTime(), uint32_t(pointerCount),
3431 pointerProperties, samplePointerCoords,
3432 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003433 injectedEntries.push(injectedEntry);
3434 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3435 sampleEventTimes += 1;
3436 samplePointerCoords += pointerCount;
3437 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003438 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003439 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003440 motionEvent->getDisplayId(), policyFlags, action,
3441 actionButton, motionEvent->getFlags(),
3442 motionEvent->getMetaState(), motionEvent->getButtonState(),
3443 motionEvent->getClassification(),
3444 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3445 motionEvent->getYPrecision(),
3446 motionEvent->getRawXCursorPosition(),
3447 motionEvent->getRawYCursorPosition(),
3448 motionEvent->getDownTime(), uint32_t(pointerCount),
3449 pointerProperties, samplePointerCoords,
3450 motionEvent->getXOffset(), motionEvent->getYOffset());
3451 injectedEntries.push(nextInjectedEntry);
3452 }
3453 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003456 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003457 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003458 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459 }
3460
3461 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3462 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3463 injectionState->injectionIsAsync = true;
3464 }
3465
3466 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003467 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468
3469 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003470 while (!injectedEntries.empty()) {
3471 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3472 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473 }
3474
3475 mLock.unlock();
3476
3477 if (needWake) {
3478 mLooper->wake();
3479 }
3480
3481 int32_t injectionResult;
3482 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003483 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484
3485 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3486 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3487 } else {
3488 for (;;) {
3489 injectionResult = injectionState->injectionResult;
3490 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3491 break;
3492 }
3493
3494 nsecs_t remainingTimeout = endTime - now();
3495 if (remainingTimeout <= 0) {
3496#if DEBUG_INJECTION
3497 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003498 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499#endif
3500 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3501 break;
3502 }
3503
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003504 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 }
3506
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003507 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3508 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 while (injectionState->pendingForegroundDispatches != 0) {
3510#if DEBUG_INJECTION
3511 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003512 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513#endif
3514 nsecs_t remainingTimeout = endTime - now();
3515 if (remainingTimeout <= 0) {
3516#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003517 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3518 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519#endif
3520 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3521 break;
3522 }
3523
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003524 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525 }
3526 }
3527 }
3528
3529 injectionState->release();
3530 } // release lock
3531
3532#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003533 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003534 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535#endif
3536
3537 return injectionResult;
3538}
3539
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003540std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003541 std::array<uint8_t, 32> calculatedHmac;
3542 std::unique_ptr<VerifiedInputEvent> result;
3543 switch (event.getType()) {
3544 case AINPUT_EVENT_TYPE_KEY: {
3545 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3546 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3547 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3548 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3549 break;
3550 }
3551 case AINPUT_EVENT_TYPE_MOTION: {
3552 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3553 VerifiedMotionEvent verifiedMotionEvent =
3554 verifiedMotionEventFromMotionEvent(motionEvent);
3555 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3556 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3557 break;
3558 }
3559 default: {
3560 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3561 return nullptr;
3562 }
3563 }
3564 if (calculatedHmac == INVALID_HMAC) {
3565 return nullptr;
3566 }
3567 if (calculatedHmac != event.getHmac()) {
3568 return nullptr;
3569 }
3570 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003571}
3572
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003574 return injectorUid == 0 ||
3575 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576}
3577
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003578void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579 InjectionState* injectionState = entry->injectionState;
3580 if (injectionState) {
3581#if DEBUG_INJECTION
3582 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003583 "injectorPid=%d, injectorUid=%d",
3584 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585#endif
3586
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003587 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 // Log the outcome since the injector did not wait for the injection result.
3589 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003590 case INPUT_EVENT_INJECTION_SUCCEEDED:
3591 ALOGV("Asynchronous input event injection succeeded.");
3592 break;
3593 case INPUT_EVENT_INJECTION_FAILED:
3594 ALOGW("Asynchronous input event injection failed.");
3595 break;
3596 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3597 ALOGW("Asynchronous input event injection permission denied.");
3598 break;
3599 case INPUT_EVENT_INJECTION_TIMED_OUT:
3600 ALOGW("Asynchronous input event injection timed out.");
3601 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 }
3603 }
3604
3605 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003606 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607 }
3608}
3609
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003610void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 InjectionState* injectionState = entry->injectionState;
3612 if (injectionState) {
3613 injectionState->pendingForegroundDispatches += 1;
3614 }
3615}
3616
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003617void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 InjectionState* injectionState = entry->injectionState;
3619 if (injectionState) {
3620 injectionState->pendingForegroundDispatches -= 1;
3621
3622 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003623 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 }
3625 }
3626}
3627
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003628std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3629 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003630 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003631}
3632
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003634 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003635 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003636 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3637 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003638 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003639 return windowHandle;
3640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 }
3642 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003643 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644}
3645
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003646bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003647 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003648 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3649 for (const sp<InputWindowHandle>& handle : windowHandles) {
3650 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003651 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003652 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003653 ", but it should belong to display %" PRId32,
3654 windowHandle->getName().c_str(), it.first,
3655 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003656 }
3657 return true;
3658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 }
3660 }
3661 return false;
3662}
3663
Robert Carr5c8a0262018-10-03 16:30:44 -07003664sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3665 size_t count = mInputChannelsByToken.count(token);
3666 if (count == 0) {
3667 return nullptr;
3668 }
3669 return mInputChannelsByToken.at(token);
3670}
3671
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003672void InputDispatcher::updateWindowHandlesForDisplayLocked(
3673 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3674 if (inputWindowHandles.empty()) {
3675 // Remove all handles on a display if there are no windows left.
3676 mWindowHandlesByDisplay.erase(displayId);
3677 return;
3678 }
3679
3680 // Since we compare the pointer of input window handles across window updates, we need
3681 // to make sure the handle object for the same window stays unchanged across updates.
3682 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003683 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003684 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003685 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003686 }
3687
3688 std::vector<sp<InputWindowHandle>> newHandles;
3689 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3690 if (!handle->updateInfo()) {
3691 // handle no longer valid
3692 continue;
3693 }
3694
3695 const InputWindowInfo* info = handle->getInfo();
3696 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3697 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3698 const bool noInputChannel =
3699 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3700 const bool canReceiveInput =
3701 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3702 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3703 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003704 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003705 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003706 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003707 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003708 }
3709
3710 if (info->displayId != displayId) {
3711 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3712 handle->getName().c_str(), displayId, info->displayId);
3713 continue;
3714 }
3715
Robert Carredd13602020-04-13 17:24:34 -07003716 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3717 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003718 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003719 oldHandle->updateFrom(handle);
3720 newHandles.push_back(oldHandle);
3721 } else {
3722 newHandles.push_back(handle);
3723 }
3724 }
3725
3726 // Insert or replace
3727 mWindowHandlesByDisplay[displayId] = newHandles;
3728}
3729
Arthur Hung72d8dc32020-03-28 00:48:39 +00003730void InputDispatcher::setInputWindows(
3731 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3732 { // acquire lock
3733 std::scoped_lock _l(mLock);
3734 for (auto const& i : handlesPerDisplay) {
3735 setInputWindowsLocked(i.second, i.first);
3736 }
3737 }
3738 // Wake up poll loop since it may need to make new input dispatching choices.
3739 mLooper->wake();
3740}
3741
Arthur Hungb92218b2018-08-14 12:00:21 +08003742/**
3743 * Called from InputManagerService, update window handle list by displayId that can receive input.
3744 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3745 * If set an empty list, remove all handles from the specific display.
3746 * For focused handle, check if need to change and send a cancel event to previous one.
3747 * For removed handle, check if need to send a cancel event if already in touch.
3748 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003749void InputDispatcher::setInputWindowsLocked(
3750 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003751 if (DEBUG_FOCUS) {
3752 std::string windowList;
3753 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3754 windowList += iwh->getName() + " ";
3755 }
3756 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758
Arthur Hung72d8dc32020-03-28 00:48:39 +00003759 // Copy old handles for release if they are no longer present.
3760 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761
Arthur Hung72d8dc32020-03-28 00:48:39 +00003762 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003763
Arthur Hung72d8dc32020-03-28 00:48:39 +00003764 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3765 bool foundHoveredWindow = false;
3766 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3767 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3768 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3769 windowHandle->getInfo()->visible) {
3770 newFocusedWindowHandle = windowHandle;
3771 }
3772 if (windowHandle == mLastHoverWindowHandle) {
3773 foundHoveredWindow = true;
3774 }
3775 }
3776
3777 if (!foundHoveredWindow) {
3778 mLastHoverWindowHandle = nullptr;
3779 }
3780
3781 sp<InputWindowHandle> oldFocusedWindowHandle =
3782 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3783
3784 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3785 if (oldFocusedWindowHandle != nullptr) {
3786 if (DEBUG_FOCUS) {
3787 ALOGD("Focus left window: %s in display %" PRId32,
3788 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003789 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003790 sp<InputChannel> focusedInputChannel =
3791 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3792 if (focusedInputChannel != nullptr) {
3793 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3794 "focus left window");
3795 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3796 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003797 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003798 mFocusedWindowHandlesByDisplay.erase(displayId);
3799 }
3800 if (newFocusedWindowHandle != nullptr) {
3801 if (DEBUG_FOCUS) {
3802 ALOGD("Focus entered window: %s in display %" PRId32,
3803 newFocusedWindowHandle->getName().c_str(), displayId);
3804 }
3805 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3806 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 }
3808
Arthur Hung72d8dc32020-03-28 00:48:39 +00003809 if (mFocusedDisplayId == displayId) {
3810 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003814 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3815 mTouchStatesByDisplay.find(displayId);
3816 if (stateIt != mTouchStatesByDisplay.end()) {
3817 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003818 for (size_t i = 0; i < state.windows.size();) {
3819 TouchedWindow& touchedWindow = state.windows[i];
3820 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003821 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003822 ALOGD("Touched window was removed: %s in display %" PRId32,
3823 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003824 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003825 sp<InputChannel> touchedInputChannel =
3826 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3827 if (touchedInputChannel != nullptr) {
3828 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3829 "touched window was removed");
3830 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003832 state.windows.erase(state.windows.begin() + i);
3833 } else {
3834 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 }
3836 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003837 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003838
Arthur Hung72d8dc32020-03-28 00:48:39 +00003839 // Release information for windows that are no longer present.
3840 // This ensures that unused input channels are released promptly.
3841 // Otherwise, they might stick around until the window handle is destroyed
3842 // which might not happen until the next GC.
3843 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3844 if (!hasWindowHandleLocked(oldWindowHandle)) {
3845 if (DEBUG_FOCUS) {
3846 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003847 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003848 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003849 }
chaviw291d88a2019-02-14 10:33:58 -08003850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851}
3852
3853void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003854 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003855 if (DEBUG_FOCUS) {
3856 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3857 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003860 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861
Tiger Huang721e26f2018-07-24 22:26:19 +08003862 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3863 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003864 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003865 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3866 if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003867 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003869 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003871 } else if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003872 resetAnrTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003873 oldFocusedApplicationHandle.clear();
3874 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 } // release lock
3877
3878 // Wake up poll loop since it may need to make new input dispatching choices.
3879 mLooper->wake();
3880}
3881
Tiger Huang721e26f2018-07-24 22:26:19 +08003882/**
3883 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3884 * the display not specified.
3885 *
3886 * We track any unreleased events for each window. If a window loses the ability to receive the
3887 * released event, we will send a cancel event to it. So when the focused display is changed, we
3888 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3889 * display. The display-specified events won't be affected.
3890 */
3891void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003892 if (DEBUG_FOCUS) {
3893 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3894 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003895 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003896 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003897
3898 if (mFocusedDisplayId != displayId) {
3899 sp<InputWindowHandle> oldFocusedWindowHandle =
3900 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3901 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003902 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003903 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003904 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003905 CancelationOptions
3906 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3907 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003908 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003909 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3910 }
3911 }
3912 mFocusedDisplayId = displayId;
3913
3914 // Sanity check
3915 sp<InputWindowHandle> newFocusedWindowHandle =
3916 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003917 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003918
Tiger Huang721e26f2018-07-24 22:26:19 +08003919 if (newFocusedWindowHandle == nullptr) {
3920 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3921 if (!mFocusedWindowHandlesByDisplay.empty()) {
3922 ALOGE("But another display has a focused window:");
3923 for (auto& it : mFocusedWindowHandlesByDisplay) {
3924 const int32_t displayId = it.first;
3925 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003926 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3927 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003928 }
3929 }
3930 }
3931 }
3932
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003933 if (DEBUG_FOCUS) {
3934 logDispatchStateLocked();
3935 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003936 } // release lock
3937
3938 // Wake up poll loop since it may need to make new input dispatching choices.
3939 mLooper->wake();
3940}
3941
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003943 if (DEBUG_FOCUS) {
3944 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946
3947 bool changed;
3948 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003949 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950
3951 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3952 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003953 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 }
3955
3956 if (mDispatchEnabled && !enabled) {
3957 resetAndDropEverythingLocked("dispatcher is being disabled");
3958 }
3959
3960 mDispatchEnabled = enabled;
3961 mDispatchFrozen = frozen;
3962 changed = true;
3963 } else {
3964 changed = false;
3965 }
3966
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003967 if (DEBUG_FOCUS) {
3968 logDispatchStateLocked();
3969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 } // release lock
3971
3972 if (changed) {
3973 // Wake up poll loop since it may need to make new input dispatching choices.
3974 mLooper->wake();
3975 }
3976}
3977
3978void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003979 if (DEBUG_FOCUS) {
3980 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982
3983 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003984 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985
3986 if (mInputFilterEnabled == enabled) {
3987 return;
3988 }
3989
3990 mInputFilterEnabled = enabled;
3991 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3992 } // release lock
3993
3994 // Wake up poll loop since there might be work to do to drop everything.
3995 mLooper->wake();
3996}
3997
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003998void InputDispatcher::setInTouchMode(bool inTouchMode) {
3999 std::scoped_lock lock(mLock);
4000 mInTouchMode = inTouchMode;
4001}
4002
chaviwfbe5d9c2018-12-26 12:23:37 -08004003bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4004 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004005 if (DEBUG_FOCUS) {
4006 ALOGD("Trivial transfer to same window.");
4007 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004008 return true;
4009 }
4010
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004012 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013
chaviwfbe5d9c2018-12-26 12:23:37 -08004014 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4015 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004016 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004017 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018 return false;
4019 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004020 if (DEBUG_FOCUS) {
4021 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4022 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004025 if (DEBUG_FOCUS) {
4026 ALOGD("Cannot transfer focus because windows are on different displays.");
4027 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028 return false;
4029 }
4030
4031 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004032 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4033 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004034 for (size_t i = 0; i < state.windows.size(); i++) {
4035 const TouchedWindow& touchedWindow = state.windows[i];
4036 if (touchedWindow.windowHandle == fromWindowHandle) {
4037 int32_t oldTargetFlags = touchedWindow.targetFlags;
4038 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004039
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004040 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004042 int32_t newTargetFlags = oldTargetFlags &
4043 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4044 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004045 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046
Jeff Brownf086ddb2014-02-11 14:28:48 -08004047 found = true;
4048 goto Found;
4049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 }
4051 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004052 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004054 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004055 if (DEBUG_FOCUS) {
4056 ALOGD("Focus transfer failed because from window did not have focus.");
4057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 return false;
4059 }
4060
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004061 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4062 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004063 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004064 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004065 CancelationOptions
4066 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4067 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004069 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 }
4071
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004072 if (DEBUG_FOCUS) {
4073 logDispatchStateLocked();
4074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 } // release lock
4076
4077 // Wake up poll loop since it may need to make new input dispatching choices.
4078 mLooper->wake();
4079 return true;
4080}
4081
4082void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004083 if (DEBUG_FOCUS) {
4084 ALOGD("Resetting and dropping all events (%s).", reason);
4085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086
4087 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4088 synthesizeCancelationEventsForAllConnectionsLocked(options);
4089
4090 resetKeyRepeatLocked();
4091 releasePendingEventLocked();
4092 drainInboundQueueLocked();
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004093 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094
Jeff Brownf086ddb2014-02-11 14:28:48 -08004095 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004097 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098}
4099
4100void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004101 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102 dumpDispatchStateLocked(dump);
4103
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004104 std::istringstream stream(dump);
4105 std::string line;
4106
4107 while (std::getline(stream, line, '\n')) {
4108 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 }
4110}
4111
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004112void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004113 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4114 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4115 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004116 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117
Tiger Huang721e26f2018-07-24 22:26:19 +08004118 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4119 dump += StringPrintf(INDENT "FocusedApplications:\n");
4120 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4121 const int32_t displayId = it.first;
4122 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004123 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004124 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004125 displayId, applicationHandle->getName().c_str(),
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004126 ns2ms(applicationHandle
4127 ->getDispatchingTimeout(
4128 DEFAULT_INPUT_DISPATCHING_TIMEOUT)
4129 .count()));
Tiger Huang721e26f2018-07-24 22:26:19 +08004130 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004132 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004134
4135 if (!mFocusedWindowHandlesByDisplay.empty()) {
4136 dump += StringPrintf(INDENT "FocusedWindows:\n");
4137 for (auto& it : mFocusedWindowHandlesByDisplay) {
4138 const int32_t displayId = it.first;
4139 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004140 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4141 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004142 }
4143 } else {
4144 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4145 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004147 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004148 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004149 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4150 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004151 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004152 state.displayId, toString(state.down), toString(state.split),
4153 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004154 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004155 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004156 for (size_t i = 0; i < state.windows.size(); i++) {
4157 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004158 dump += StringPrintf(INDENT4
4159 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4160 i, touchedWindow.windowHandle->getName().c_str(),
4161 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004162 }
4163 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004164 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004165 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004166 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004167 dump += INDENT3 "Portal windows:\n";
4168 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004169 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004170 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4171 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004172 }
4173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 }
4175 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004176 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177 }
4178
Arthur Hungb92218b2018-08-14 12:00:21 +08004179 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004181 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004182 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004183 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004184 dump += INDENT2 "Windows:\n";
4185 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004186 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004187 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188
Arthur Hungb92218b2018-08-14 12:00:21 +08004189 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004190 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004191 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4192 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004193 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004194 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004195 i, windowInfo->name.c_str(), windowInfo->displayId,
4196 windowInfo->portalToDisplayId,
4197 toString(windowInfo->paused),
4198 toString(windowInfo->hasFocus),
4199 toString(windowInfo->hasWallpaper),
4200 toString(windowInfo->visible),
4201 toString(windowInfo->canReceiveKeys),
4202 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004203 windowInfo->layoutParamsType, windowInfo->frameLeft,
4204 windowInfo->frameTop, windowInfo->frameRight,
4205 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4206 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004207 dumpRegion(dump, windowInfo->touchableRegion);
4208 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004209 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4210 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004211 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004212 ns2ms(windowInfo->dispatchingTimeout));
Siarhei Vishniakou67d44502020-04-09 11:09:29 -07004213 dump += StringPrintf(INDENT4 " flags: %s\n",
4214 inputWindowFlagsToString(windowInfo->layoutParamsFlags)
4215 .c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004216 }
4217 } else {
4218 dump += INDENT2 "Windows: <none>\n";
4219 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 }
4221 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004222 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 }
4224
Michael Wright3dd60e22019-03-27 22:06:44 +00004225 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004226 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004227 const std::vector<Monitor>& monitors = it.second;
4228 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4229 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004230 }
4231 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004232 const std::vector<Monitor>& monitors = it.second;
4233 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4234 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004235 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004237 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 }
4239
4240 nsecs_t currentTime = now();
4241
4242 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004243 if (!mRecentQueue.empty()) {
4244 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4245 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004246 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004248 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 }
4250 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004251 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 }
4253
4254 // Dump event currently being dispatched.
4255 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004256 dump += INDENT "PendingEvent:\n";
4257 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004259 dump += StringPrintf(", age=%" PRId64 "ms\n",
4260 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004262 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 }
4264
4265 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004266 if (!mInboundQueue.empty()) {
4267 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4268 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004269 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004271 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 }
4273 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004274 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 }
4276
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004277 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004278 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004279 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4280 const KeyReplacement& replacement = pair.first;
4281 int32_t newKeyCode = pair.second;
4282 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004283 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004284 }
4285 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004286 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004287 }
4288
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004289 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004290 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004291 for (const auto& pair : mConnectionsByFd) {
4292 const sp<Connection>& connection = pair.second;
4293 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
4294 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
4295 pair.first, connection->getInputChannelName().c_str(),
4296 connection->getWindowName().c_str(), connection->getStatusLabel(),
4297 toString(connection->monitor),
4298 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004300 if (!connection->outboundQueue.empty()) {
4301 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4302 connection->outboundQueue.size());
4303 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 dump.append(INDENT4);
4305 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004306 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4307 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004308 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004309 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 }
4311 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004312 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 }
4314
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004315 if (!connection->waitQueue.empty()) {
4316 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4317 connection->waitQueue.size());
4318 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004319 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004321 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004322 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004323 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004324 ns2ms(currentTime - entry->eventEntry->eventTime),
4325 ns2ms(currentTime - entry->deliveryTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326 }
4327 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004328 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 }
4330 }
4331 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004332 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 }
4334
4335 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004336 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4337 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004339 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 }
4341
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004342 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004343 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4344 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4345 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346}
4347
Michael Wright3dd60e22019-03-27 22:06:44 +00004348void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4349 const size_t numMonitors = monitors.size();
4350 for (size_t i = 0; i < numMonitors; i++) {
4351 const Monitor& monitor = monitors[i];
4352 const sp<InputChannel>& channel = monitor.inputChannel;
4353 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4354 dump += "\n";
4355 }
4356}
4357
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004358status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004360 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361#endif
4362
4363 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004364 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004365 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004366 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004368 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 return BAD_VALUE;
4370 }
4371
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004372 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373
4374 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004375 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004376 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4379 } // release lock
4380
4381 // Wake the looper because some connections have changed.
4382 mLooper->wake();
4383 return OK;
4384}
4385
Michael Wright3dd60e22019-03-27 22:06:44 +00004386status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004387 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004388 { // acquire lock
4389 std::scoped_lock _l(mLock);
4390
4391 if (displayId < 0) {
4392 ALOGW("Attempted to register input monitor without a specified display.");
4393 return BAD_VALUE;
4394 }
4395
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004396 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004397 ALOGW("Attempted to register input monitor without an identifying token.");
4398 return BAD_VALUE;
4399 }
4400
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004401 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004402
4403 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004404 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004405 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004406
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004407 auto& monitorsByDisplay =
4408 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004409 monitorsByDisplay[displayId].emplace_back(inputChannel);
4410
4411 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004412 }
4413 // Wake the looper because some connections have changed.
4414 mLooper->wake();
4415 return OK;
4416}
4417
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4419#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004420 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421#endif
4422
4423 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004424 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425
4426 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4427 if (status) {
4428 return status;
4429 }
4430 } // release lock
4431
4432 // Wake the poll loop because removing the connection may have changed the current
4433 // synchronization state.
4434 mLooper->wake();
4435 return OK;
4436}
4437
4438status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004439 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004440 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004441 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004442 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004443 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444 return BAD_VALUE;
4445 }
4446
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004447 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004448 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004449
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 if (connection->monitor) {
4451 removeMonitorChannelLocked(inputChannel);
4452 }
4453
4454 mLooper->removeFd(inputChannel->getFd());
4455
4456 nsecs_t currentTime = now();
4457 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4458
4459 connection->status = Connection::STATUS_ZOMBIE;
4460 return OK;
4461}
4462
4463void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004464 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4465 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4466}
4467
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004468void InputDispatcher::removeMonitorChannelLocked(
4469 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004470 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004471 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004472 std::vector<Monitor>& monitors = it->second;
4473 const size_t numMonitors = monitors.size();
4474 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004475 if (monitors[i].inputChannel == inputChannel) {
4476 monitors.erase(monitors.begin() + i);
4477 break;
4478 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004479 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004480 if (monitors.empty()) {
4481 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004482 } else {
4483 ++it;
4484 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485 }
4486}
4487
Michael Wright3dd60e22019-03-27 22:06:44 +00004488status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4489 { // acquire lock
4490 std::scoped_lock _l(mLock);
4491 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4492
4493 if (!foundDisplayId) {
4494 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4495 return BAD_VALUE;
4496 }
4497 int32_t displayId = foundDisplayId.value();
4498
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004499 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4500 mTouchStatesByDisplay.find(displayId);
4501 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004502 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4503 return BAD_VALUE;
4504 }
4505
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004506 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004507 std::optional<int32_t> foundDeviceId;
4508 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004509 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004510 foundDeviceId = state.deviceId;
4511 }
4512 }
4513 if (!foundDeviceId || !state.down) {
4514 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004515 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004516 return BAD_VALUE;
4517 }
4518 int32_t deviceId = foundDeviceId.value();
4519
4520 // Send cancel events to all the input channels we're stealing from.
4521 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004522 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004523 options.deviceId = deviceId;
4524 options.displayId = displayId;
4525 for (const TouchedWindow& window : state.windows) {
4526 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004527 if (channel != nullptr) {
4528 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4529 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004530 }
4531 // Then clear the current touch state so we stop dispatching to them as well.
4532 state.filterNonMonitors();
4533 }
4534 return OK;
4535}
4536
Michael Wright3dd60e22019-03-27 22:06:44 +00004537std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4538 const sp<IBinder>& token) {
4539 for (const auto& it : mGestureMonitorsByDisplay) {
4540 const std::vector<Monitor>& monitors = it.second;
4541 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004542 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004543 return it.first;
4544 }
4545 }
4546 }
4547 return std::nullopt;
4548}
4549
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004550sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004551 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004552 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004553 }
4554
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004555 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004556 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004557 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004558 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559 }
4560 }
Robert Carr4e670e52018-08-15 13:26:12 -07004561
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004562 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563}
4564
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004565void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
4566 removeByValue(mConnectionsByFd, connection);
4567}
4568
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004569void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4570 const sp<Connection>& connection, uint32_t seq,
4571 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004572 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4573 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574 commandEntry->connection = connection;
4575 commandEntry->eventTime = currentTime;
4576 commandEntry->seq = seq;
4577 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004578 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579}
4580
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004581void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4582 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004584 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004586 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4587 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004589 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004590}
4591
chaviw0c06c6e2019-01-09 13:27:07 -08004592void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004593 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004594 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4595 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004596 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4597 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004598 commandEntry->oldToken = oldToken;
4599 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004600 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004601}
4602
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004603void InputDispatcher::onAnrLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004604 const sp<InputApplicationHandle>& applicationHandle,
4605 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4606 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4608 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4609 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004610 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4611 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4612 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613
4614 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004615 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616 struct tm tm;
4617 localtime_r(&t, &tm);
4618 char timestr[64];
4619 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004620 mLastAnrState.clear();
4621 mLastAnrState += INDENT "ANR:\n";
4622 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
4623 mLastAnrState +=
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004624 StringPrintf(INDENT2 "Window: %s\n",
4625 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004626 mLastAnrState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4627 mLastAnrState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4628 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason);
4629 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004631 std::unique_ptr<CommandEntry> commandEntry =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004632 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004634 commandEntry->inputChannel =
4635 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004637 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638}
4639
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004640void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641 mLock.unlock();
4642
4643 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4644
4645 mLock.lock();
4646}
4647
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004648void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649 sp<Connection> connection = commandEntry->connection;
4650
4651 if (connection->status != Connection::STATUS_ZOMBIE) {
4652 mLock.unlock();
4653
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004654 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655
4656 mLock.lock();
4657 }
4658}
4659
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004660void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004661 sp<IBinder> oldToken = commandEntry->oldToken;
4662 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004663 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004664 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004665 mLock.lock();
4666}
4667
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004668void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004669 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004670 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671 mLock.unlock();
4672
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004673 const nsecs_t timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004674 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675
4676 mLock.lock();
4677
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004678 resumeAfterTargetsNotReadyTimeoutLocked(timeoutExtension, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679}
4680
4681void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4682 CommandEntry* commandEntry) {
4683 KeyEntry* entry = commandEntry->keyEntry;
4684
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004685 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686
4687 mLock.unlock();
4688
Michael Wright2b3c3302018-03-02 17:19:13 +00004689 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004690 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004691 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004692 : nullptr;
4693 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004694 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4695 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004696 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698
4699 mLock.lock();
4700
4701 if (delay < 0) {
4702 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4703 } else if (!delay) {
4704 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4705 } else {
4706 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4707 entry->interceptKeyWakeupTime = now() + delay;
4708 }
4709 entry->release();
4710}
4711
chaviwfd6d3512019-03-25 13:23:49 -07004712void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4713 mLock.unlock();
4714 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4715 mLock.lock();
4716}
4717
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004718void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004720 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004722 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723
4724 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004725 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004726 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004727 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004729 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004730
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004731 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004732 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004733 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4734 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004735 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004736 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004737
4738 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004739 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004740 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4741 restartEvent =
4742 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004743 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004744 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4745 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4746 handled);
4747 } else {
4748 restartEvent = false;
4749 }
4750
4751 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004752 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004753 // contents of the wait queue to have been drained, so we need to double-check
4754 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004755 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4756 if (dispatchEntryIt != connection->waitQueue.end()) {
4757 dispatchEntry = *dispatchEntryIt;
4758 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004759 traceWaitQueueLength(connection);
4760 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004761 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004762 traceOutboundQueueLength(connection);
4763 } else {
4764 releaseDispatchEntry(dispatchEntry);
4765 }
4766 }
4767
4768 // Start the next dispatch cycle for this connection.
4769 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770}
4771
4772bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004773 DispatchEntry* dispatchEntry,
4774 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004775 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004776 if (!handled) {
4777 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004778 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004779 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004780 return false;
4781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004783 // Get the fallback key state.
4784 // Clear it out after dispatching the UP.
4785 int32_t originalKeyCode = keyEntry->keyCode;
4786 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4787 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4788 connection->inputState.removeFallbackKey(originalKeyCode);
4789 }
4790
4791 if (handled || !dispatchEntry->hasForegroundTarget()) {
4792 // If the application handles the original key for which we previously
4793 // generated a fallback or if the window is not a foreground window,
4794 // then cancel the associated fallback key, if any.
4795 if (fallbackKeyCode != -1) {
4796 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004798 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004799 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4800 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4801 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004803 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004804 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805
4806 mLock.unlock();
4807
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004808 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004809 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810
4811 mLock.lock();
4812
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004813 // Cancel the fallback key.
4814 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004816 "application handled the original non-fallback key "
4817 "or is no longer a foreground target, "
4818 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 options.keyCode = fallbackKeyCode;
4820 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004822 connection->inputState.removeFallbackKey(originalKeyCode);
4823 }
4824 } else {
4825 // If the application did not handle a non-fallback key, first check
4826 // that we are in a good state to perform unhandled key event processing
4827 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004828 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004829 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004831 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004832 "since this is not an initial down. "
4833 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4834 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004836 return false;
4837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004839 // Dispatch the unhandled key to the policy.
4840#if DEBUG_OUTBOUND_EVENT_DETAILS
4841 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004842 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4843 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004844#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004845 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004846
4847 mLock.unlock();
4848
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004849 bool fallback =
4850 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4851 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004852
4853 mLock.lock();
4854
4855 if (connection->status != Connection::STATUS_NORMAL) {
4856 connection->inputState.removeFallbackKey(originalKeyCode);
4857 return false;
4858 }
4859
4860 // Latch the fallback keycode for this key on an initial down.
4861 // The fallback keycode cannot change at any other point in the lifecycle.
4862 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004864 fallbackKeyCode = event.getKeyCode();
4865 } else {
4866 fallbackKeyCode = AKEYCODE_UNKNOWN;
4867 }
4868 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4869 }
4870
4871 ALOG_ASSERT(fallbackKeyCode != -1);
4872
4873 // Cancel the fallback key if the policy decides not to send it anymore.
4874 // We will continue to dispatch the key to the policy but we will no
4875 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004876 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4877 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004878#if DEBUG_OUTBOUND_EVENT_DETAILS
4879 if (fallback) {
4880 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004881 "as a fallback for %d, but on the DOWN it had requested "
4882 "to send %d instead. Fallback canceled.",
4883 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004884 } else {
4885 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004886 "but on the DOWN it had requested to send %d. "
4887 "Fallback canceled.",
4888 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004889 }
4890#endif
4891
4892 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4893 "canceling fallback, policy no longer desires it");
4894 options.keyCode = fallbackKeyCode;
4895 synthesizeCancelationEventsForConnectionLocked(connection, options);
4896
4897 fallback = false;
4898 fallbackKeyCode = AKEYCODE_UNKNOWN;
4899 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004900 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004901 }
4902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903
4904#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004905 {
4906 std::string msg;
4907 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4908 connection->inputState.getFallbackKeys();
4909 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004910 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004912 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004913 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004914 }
4915#endif
4916
4917 if (fallback) {
4918 // Restart the dispatch cycle using the fallback key.
4919 keyEntry->eventTime = event.getEventTime();
4920 keyEntry->deviceId = event.getDeviceId();
4921 keyEntry->source = event.getSource();
4922 keyEntry->displayId = event.getDisplayId();
4923 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4924 keyEntry->keyCode = fallbackKeyCode;
4925 keyEntry->scanCode = event.getScanCode();
4926 keyEntry->metaState = event.getMetaState();
4927 keyEntry->repeatCount = event.getRepeatCount();
4928 keyEntry->downTime = event.getDownTime();
4929 keyEntry->syntheticRepeat = false;
4930
4931#if DEBUG_OUTBOUND_EVENT_DETAILS
4932 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004933 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4934 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004935#endif
4936 return true; // restart the event
4937 } else {
4938#if DEBUG_OUTBOUND_EVENT_DETAILS
4939 ALOGD("Unhandled key event: No fallback key.");
4940#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004941
4942 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004943 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 }
4945 }
4946 return false;
4947}
4948
4949bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004950 DispatchEntry* dispatchEntry,
4951 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952 return false;
4953}
4954
4955void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4956 mLock.unlock();
4957
4958 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4959
4960 mLock.lock();
4961}
4962
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004963KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4964 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004965 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004966 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
4967 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004968 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004969}
4970
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004971void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
4972 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973 // TODO Write some statistics about how long we spend waiting.
4974}
4975
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004976/**
4977 * Report the touch event latency to the statsd server.
4978 * Input events are reported for statistics if:
4979 * - This is a touchscreen event
4980 * - InputFilter is not enabled
4981 * - Event is not injected or synthesized
4982 *
4983 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4984 * from getting aggregated with the "old" data.
4985 */
4986void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4987 REQUIRES(mLock) {
4988 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4989 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4990 if (!reportForStatistics) {
4991 return;
4992 }
4993
4994 if (mTouchStatistics.shouldReport()) {
4995 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4996 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4997 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4998 mTouchStatistics.reset();
4999 }
5000 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5001 mTouchStatistics.addValue(latencyMicros);
5002}
5003
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004void InputDispatcher::traceInboundQueueLengthLocked() {
5005 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005006 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007 }
5008}
5009
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005010void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 if (ATRACE_ENABLED()) {
5012 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005013 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005014 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015 }
5016}
5017
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005018void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005019 if (ATRACE_ENABLED()) {
5020 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005021 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005022 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005023 }
5024}
5025
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005026void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005027 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005028
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005029 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030 dumpDispatchStateLocked(dump);
5031
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005032 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005033 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005034 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005035 }
5036}
5037
5038void InputDispatcher::monitor() {
5039 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005040 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005042 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005043}
5044
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005045/**
5046 * Wake up the dispatcher and wait until it processes all events and commands.
5047 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5048 * this method can be safely called from any thread, as long as you've ensured that
5049 * the work you are interested in completing has already been queued.
5050 */
5051bool InputDispatcher::waitForIdle() {
5052 /**
5053 * Timeout should represent the longest possible time that a device might spend processing
5054 * events and commands.
5055 */
5056 constexpr std::chrono::duration TIMEOUT = 100ms;
5057 std::unique_lock lock(mLock);
5058 mLooper->wake();
5059 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5060 return result == std::cv_status::no_timeout;
5061}
5062
Garfield Tane84e6f92019-08-29 17:28:41 -07005063} // namespace android::inputdispatcher