blob: 056a72597c69cec3d6a67dedc039ee6188438990 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Garfield Tane84e6f92019-08-29 17:28:41 -070048#include "Connection.h"
49
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <errno.h>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080051#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <limits.h>
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -050053#include <statslog.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080055#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056#include <unistd.h>
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -070057#include <queue>
58#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070059
Michael Wright2b3c3302018-03-02 17:19:13 +000060#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070062#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080063#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <log/log.h>
Gang Wang342c9272020-01-13 13:15:04 -050065#include <openssl/hmac.h>
66#include <openssl/rand.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070067#include <powermanager/PowerManager.h>
68#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080069
70#define INDENT " "
71#define INDENT2 " "
72#define INDENT3 " "
73#define INDENT4 " "
74
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080075using android::base::StringPrintf;
76
Garfield Tane84e6f92019-08-29 17:28:41 -070077namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
79// Default input dispatching timeout if there is no focused application or paused window
80// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070081constexpr std::chrono::nanoseconds DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5s;
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Amount of time to allow for all pending events to be processed when an app switch
84// key is on the way. This is used to preempt input dispatch and drop input events
85// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000086constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow for an event to be dispatched (measured since its eventTime)
89// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92// Amount of time to allow touch events to be streamed out to a connection before requiring
93// that the first event be finished. This value extends the ANR timeout by the specified
94// amount. For example, if streaming is allowed to get ahead by one second relative to the
95// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000096constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
98// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000099constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
100
101// Log a warning when an interception call takes longer than this to process.
102constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
104// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107static inline nsecs_t now() {
108 return systemTime(SYSTEM_TIME_MONOTONIC);
109}
110
111static inline const char* toString(bool value) {
112 return value ? "true" : "false";
113}
114
115static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700116 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
117 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118}
119
120static bool isValidKeyAction(int32_t action) {
121 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700122 case AKEY_EVENT_ACTION_DOWN:
123 case AKEY_EVENT_ACTION_UP:
124 return true;
125 default:
126 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127 }
128}
129
130static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 ALOGE("Key event has invalid action code 0x%x", action);
133 return false;
134 }
135 return true;
136}
137
Michael Wright7b159c92015-05-14 14:48:03 +0100138static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 case AMOTION_EVENT_ACTION_DOWN:
141 case AMOTION_EVENT_ACTION_UP:
142 case AMOTION_EVENT_ACTION_CANCEL:
143 case AMOTION_EVENT_ACTION_MOVE:
144 case AMOTION_EVENT_ACTION_OUTSIDE:
145 case AMOTION_EVENT_ACTION_HOVER_ENTER:
146 case AMOTION_EVENT_ACTION_HOVER_MOVE:
147 case AMOTION_EVENT_ACTION_HOVER_EXIT:
148 case AMOTION_EVENT_ACTION_SCROLL:
149 return true;
150 case AMOTION_EVENT_ACTION_POINTER_DOWN:
151 case AMOTION_EVENT_ACTION_POINTER_UP: {
152 int32_t index = getMotionEventActionPointerIndex(action);
153 return index >= 0 && index < pointerCount;
154 }
155 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
156 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
157 return actionButton != 0;
158 default:
159 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160 }
161}
162
Michael Wright7b159c92015-05-14 14:48:03 +0100163static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 const PointerProperties* pointerProperties) {
165 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 ALOGE("Motion event has invalid action code 0x%x", action);
167 return false;
168 }
169 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000170 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700171 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 return false;
173 }
174 BitSet32 pointerIdBits;
175 for (size_t i = 0; i < pointerCount; i++) {
176 int32_t id = pointerProperties[i].id;
177 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
179 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 return false;
181 }
182 if (pointerIdBits.hasBit(id)) {
183 ALOGE("Motion event has duplicate pointer id %d", id);
184 return false;
185 }
186 pointerIdBits.markBit(id);
187 }
188 return true;
189}
190
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800191static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800193 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 return;
195 }
196
197 bool first = true;
198 Region::const_iterator cur = region.begin();
199 Region::const_iterator const tail = region.end();
200 while (cur != tail) {
201 if (first) {
202 first = false;
203 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800204 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800206 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 cur++;
208 }
209}
210
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700211/**
212 * Find the entry in std::unordered_map by key, and return it.
213 * If the entry is not found, return a default constructed entry.
214 *
215 * Useful when the entries are vectors, since an empty vector will be returned
216 * if the entry is not found.
217 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
218 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700219template <typename K, typename V>
220static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700221 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700222 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800223}
224
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700225/**
226 * Find the entry in std::unordered_map by value, and remove it.
227 * If more than one entry has the same value, then all matching
228 * key-value pairs will be removed.
229 *
230 * Return true if at least one value has been removed.
231 */
232template <typename K, typename V>
233static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
234 bool removed = false;
235 for (auto it = map.begin(); it != map.end();) {
236 if (it->second == value) {
237 it = map.erase(it);
238 removed = true;
239 } else {
240 it++;
241 }
242 }
243 return removed;
244}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245
chaviwaf87b3e2019-10-01 16:59:28 -0700246static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
247 if (first == second) {
248 return true;
249 }
250
251 if (first == nullptr || second == nullptr) {
252 return false;
253 }
254
255 return first->getToken() == second->getToken();
256}
257
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800258static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
259 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
260}
261
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000262static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
263 EventEntry* eventEntry,
264 int32_t inputTargetFlags) {
265 if (inputTarget.useDefaultPointerInfo()) {
266 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
267 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
268 inputTargetFlags, pointerInfo.xOffset,
269 pointerInfo.yOffset, inputTarget.globalScaleFactor,
270 pointerInfo.windowXScale, pointerInfo.windowYScale);
271 }
272
273 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
274 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
275
276 PointerCoords pointerCoords[motionEntry.pointerCount];
277
278 // Use the first pointer information to normalize all other pointers. This could be any pointer
279 // as long as all other pointers are normalized to the same value and the final DispatchEntry
280 // uses the offset and scale for the normalized pointer.
281 const PointerInfo& firstPointerInfo =
282 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
283
284 // Iterate through all pointers in the event to normalize against the first.
285 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
286 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
287 uint32_t pointerId = uint32_t(pointerProperties.id);
288 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
289
290 // The scale factor is the ratio of the current pointers scale to the normalized scale.
291 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
292 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
293
294 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
295 // First apply the current pointers offset to set the window at 0,0
296 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
297 // Next scale the coordinates.
298 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
299 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
300 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
301 -firstPointerInfo.yOffset);
302 }
303
304 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800305 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000306 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
307 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
308 motionEntry.metaState, motionEntry.buttonState,
309 motionEntry.classification, motionEntry.edgeFlags,
310 motionEntry.xPrecision, motionEntry.yPrecision,
311 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
312 motionEntry.downTime, motionEntry.pointerCount,
313 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
314 0 /* yOffset */);
315
316 if (motionEntry.injectionState) {
317 combinedMotionEntry->injectionState = motionEntry.injectionState;
318 combinedMotionEntry->injectionState->refCount += 1;
319 }
320
321 std::unique_ptr<DispatchEntry> dispatchEntry =
322 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
323 inputTargetFlags, firstPointerInfo.xOffset,
324 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
325 firstPointerInfo.windowXScale,
326 firstPointerInfo.windowYScale);
327 combinedMotionEntry->release();
328 return dispatchEntry;
329}
330
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700331static void addGestureMonitors(const std::vector<Monitor>& monitors,
332 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
333 float yOffset = 0) {
334 if (monitors.empty()) {
335 return;
336 }
337 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
338 for (const Monitor& monitor : monitors) {
339 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
340 }
341}
342
Gang Wang342c9272020-01-13 13:15:04 -0500343static std::array<uint8_t, 128> getRandomKey() {
344 std::array<uint8_t, 128> key;
345 if (RAND_bytes(key.data(), key.size()) != 1) {
346 LOG_ALWAYS_FATAL("Can't generate HMAC key");
347 }
348 return key;
349}
350
351// --- HmacKeyManager ---
352
353HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
354
355std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
356 size_t size;
357 switch (event.type) {
358 case VerifiedInputEvent::Type::KEY: {
359 size = sizeof(VerifiedKeyEvent);
360 break;
361 }
362 case VerifiedInputEvent::Type::MOTION: {
363 size = sizeof(VerifiedMotionEvent);
364 break;
365 }
366 }
Gang Wang342c9272020-01-13 13:15:04 -0500367 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700368 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500369}
370
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700371std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500372 // SHA256 always generates 32-bytes result
373 std::array<uint8_t, 32> hash;
374 unsigned int hashLen = 0;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700375 uint8_t* result =
376 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500377 if (result == nullptr) {
378 ALOGE("Could not sign the data using HMAC");
379 return INVALID_HMAC;
380 }
381
382 if (hashLen != hash.size()) {
383 ALOGE("HMAC-SHA256 has unexpected length");
384 return INVALID_HMAC;
385 }
386
387 return hash;
388}
389
Michael Wrightd02c5b62014-02-10 15:10:22 -0800390// --- InputDispatcher ---
391
Garfield Tan00f511d2019-06-12 16:55:40 -0700392InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
393 : mPolicy(policy),
394 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700395 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800396 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700397 mAppSwitchSawKeyDown(false),
398 mAppSwitchDueTime(LONG_LONG_MAX),
399 mNextUnblockedEvent(nullptr),
400 mDispatchEnabled(false),
401 mDispatchFrozen(false),
402 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800403 // mInTouchMode will be initialized by the WindowManager to the default device config.
404 // To avoid leaking stack in case that call never comes, and for tests,
405 // initialize it here anyways.
406 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700407 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
408 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800410 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411
Yi Kong9b14ac62018-07-17 13:48:38 -0700412 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413
414 policy->getDispatcherConfiguration(&mConfig);
415}
416
417InputDispatcher::~InputDispatcher() {
418 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800419 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800420
421 resetKeyRepeatLocked();
422 releasePendingEventLocked();
423 drainInboundQueueLocked();
424 }
425
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700426 while (!mConnectionsByFd.empty()) {
427 sp<Connection> connection = mConnectionsByFd.begin()->second;
428 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800429 }
430}
431
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700432status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700433 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700434 return ALREADY_EXISTS;
435 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700436 mThread = std::make_unique<InputThread>(
437 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
438 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700439}
440
441status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700442 if (mThread && mThread->isCallingThread()) {
443 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700444 return INVALID_OPERATION;
445 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700446 mThread.reset();
447 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700448}
449
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450void InputDispatcher::dispatchOnce() {
451 nsecs_t nextWakeupTime = LONG_LONG_MAX;
452 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800453 std::scoped_lock _l(mLock);
454 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455
456 // Run a dispatch loop if there are no pending commands.
457 // The dispatch loop might enqueue commands to run afterwards.
458 if (!haveCommandsLocked()) {
459 dispatchOnceInnerLocked(&nextWakeupTime);
460 }
461
462 // Run all pending commands if there are any.
463 // If any commands were run then force the next poll to wake up immediately.
464 if (runCommandsLockedInterruptible()) {
465 nextWakeupTime = LONG_LONG_MIN;
466 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800467
468 // We are about to enter an infinitely long sleep, because we have no commands or
469 // pending or queued events
470 if (nextWakeupTime == LONG_LONG_MAX) {
471 mDispatcherEnteredIdle.notify_all();
472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800473 } // release lock
474
475 // Wait for callback or timeout or wake. (make sure we round up, not down)
476 nsecs_t currentTime = now();
477 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
478 mLooper->pollOnce(timeoutMillis);
479}
480
481void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
482 nsecs_t currentTime = now();
483
Jeff Browndc5992e2014-04-11 01:27:26 -0700484 // Reset the key repeat timer whenever normal dispatch is suspended while the
485 // device is in a non-interactive state. This is to ensure that we abort a key
486 // repeat if the device is just coming out of sleep.
487 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488 resetKeyRepeatLocked();
489 }
490
491 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
492 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100493 if (DEBUG_FOCUS) {
494 ALOGD("Dispatch frozen. Waiting some more.");
495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496 return;
497 }
498
499 // Optimize latency of app switches.
500 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
501 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
502 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
503 if (mAppSwitchDueTime < *nextWakeupTime) {
504 *nextWakeupTime = mAppSwitchDueTime;
505 }
506
507 // Ready to start a new event.
508 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700509 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700510 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 if (isAppSwitchDue) {
512 // The inbound queue is empty so the app switch key we were waiting
513 // for will never arrive. Stop waiting for it.
514 resetPendingAppSwitchLocked(false);
515 isAppSwitchDue = false;
516 }
517
518 // Synthesize a key repeat if appropriate.
519 if (mKeyRepeatState.lastKeyEntry) {
520 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
521 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
522 } else {
523 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
524 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
525 }
526 }
527 }
528
529 // Nothing to do if there is no pending event.
530 if (!mPendingEvent) {
531 return;
532 }
533 } else {
534 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700535 mPendingEvent = mInboundQueue.front();
536 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537 traceInboundQueueLengthLocked();
538 }
539
540 // Poke user activity for this event.
541 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700542 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 }
544
545 // Get ready to dispatch the event.
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700546 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547 }
548
549 // Now we have an event to dispatch.
550 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700551 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700553 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700555 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700557 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 }
559
560 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700561 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 }
563
564 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700565 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700566 ConfigurationChangedEntry* typedEntry =
567 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
568 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700569 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700570 break;
571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700573 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700574 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
575 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700576 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700577 break;
578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100580 case EventEntry::Type::FOCUS: {
581 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
582 dispatchFocusLocked(currentTime, typedEntry);
583 done = true;
584 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
585 break;
586 }
587
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700588 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700589 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
590 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700591 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700592 resetPendingAppSwitchLocked(true);
593 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700594 } else if (dropReason == DropReason::NOT_DROPPED) {
595 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700596 }
597 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700598 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700599 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700600 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700601 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
602 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700603 }
604 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
605 break;
606 }
607
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700608 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700609 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700610 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
611 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700613 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700614 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700615 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700616 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
617 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700618 }
619 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
620 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 }
623
624 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700625 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700626 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 }
Michael Wright3a981722015-06-10 15:26:13 +0100628 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629
630 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700631 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 }
633}
634
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700635/**
636 * Return true if the events preceding this incoming motion event should be dropped
637 * Return false otherwise (the default behaviour)
638 */
639bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
640 bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
641 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
642 if (isPointerDownEvent &&
643 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
644 mInputTargetWaitApplicationToken != nullptr) {
645 int32_t displayId = motionEntry.displayId;
646 int32_t x = static_cast<int32_t>(
647 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
648 int32_t y = static_cast<int32_t>(
649 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
650 sp<InputWindowHandle> touchedWindowHandle =
651 findTouchedWindowAtLocked(displayId, x, y, nullptr);
652 if (touchedWindowHandle != nullptr &&
653 touchedWindowHandle->getApplicationToken() != mInputTargetWaitApplicationToken) {
654 // User touched a different application than the one we are waiting on.
655 // Flag the event, and start pruning the input queue.
656 ALOGI("Pruning input queue because user touched a different application");
657 return true;
658 }
659 }
660 return false;
661}
662
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700664 bool needWake = mInboundQueue.empty();
665 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666 traceInboundQueueLengthLocked();
667
668 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700669 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700670 // Optimize app switch latency.
671 // If the application takes too long to catch up then we drop all events preceding
672 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700673 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700674 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700675 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700676 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700677 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700678 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700682 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700683 mAppSwitchSawKeyDown = false;
684 needWake = true;
685 }
686 }
687 }
688 break;
689 }
690
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700691 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700692 // Optimize case where the current application is unresponsive and the user
693 // decides to touch a window in a different application.
694 // If the application takes too long to catch up then we drop all events preceding
695 // the touch into the other window.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700696 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
697 mNextUnblockedEvent = entry;
698 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700700 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100702 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700703 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
704 break;
705 }
706 case EventEntry::Type::CONFIGURATION_CHANGED:
707 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700708 // nothing to do
709 break;
710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711 }
712
713 return needWake;
714}
715
716void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
717 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700718 mRecentQueue.push_back(entry);
719 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
720 mRecentQueue.front()->release();
721 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722 }
723}
724
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700725sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700726 int32_t y, TouchState* touchState,
727 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700728 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700729 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
730 LOG_ALWAYS_FATAL(
731 "Must provide a valid touch state if adding portal windows or outside targets");
732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800734 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
735 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736 const InputWindowInfo* windowInfo = windowHandle->getInfo();
737 if (windowInfo->displayId == displayId) {
738 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739
740 if (windowInfo->visible) {
741 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700742 bool isTouchModal = (flags &
743 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
744 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800746 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700747 if (portalToDisplayId != ADISPLAY_ID_NONE &&
748 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800749 if (addPortalWindows) {
750 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700751 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800752 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700753 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700754 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 // Found window.
757 return windowHandle;
758 }
759 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800760
761 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700762 touchState->addOrUpdateWindow(windowHandle,
763 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
764 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800767 }
768 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700769 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770}
771
Garfield Tane84e6f92019-08-29 17:28:41 -0700772std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700773 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000774 std::vector<TouchedMonitor> touchedMonitors;
775
776 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
777 addGestureMonitors(monitors, touchedMonitors);
778 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
779 const InputWindowInfo* windowInfo = portalWindow->getInfo();
780 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700781 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
782 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000783 }
784 return touchedMonitors;
785}
786
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700787void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 const char* reason;
789 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700790 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700792 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700794 reason = "inbound event was dropped because the policy consumed it";
795 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700796 case DropReason::DISABLED:
797 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700798 ALOGI("Dropped event because input dispatch is disabled.");
799 }
800 reason = "inbound event was dropped because input dispatch is disabled";
801 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700802 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700803 ALOGI("Dropped event because of pending overdue app switch.");
804 reason = "inbound event was dropped because of pending overdue app switch";
805 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700806 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700807 ALOGI("Dropped event because the current application is not responding and the user "
808 "has started interacting with a different application.");
809 reason = "inbound event was dropped because the current application is not responding "
810 "and the user has started interacting with a different application";
811 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700812 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700813 ALOGI("Dropped event because it is stale.");
814 reason = "inbound event was dropped because it is stale";
815 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700816 case DropReason::NOT_DROPPED: {
817 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700818 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820 }
821
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700822 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700823 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
825 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700826 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700828 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700829 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
830 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700831 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
832 synthesizeCancelationEventsForAllConnectionsLocked(options);
833 } else {
834 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
835 synthesizeCancelationEventsForAllConnectionsLocked(options);
836 }
837 break;
838 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100839 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700840 case EventEntry::Type::CONFIGURATION_CHANGED:
841 case EventEntry::Type::DEVICE_RESET: {
842 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
843 break;
844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 }
846}
847
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800848static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700849 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
850 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851}
852
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700853bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
854 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
855 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
856 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857}
858
859bool InputDispatcher::isAppSwitchPendingLocked() {
860 return mAppSwitchDueTime != LONG_LONG_MAX;
861}
862
863void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
864 mAppSwitchDueTime = LONG_LONG_MAX;
865
866#if DEBUG_APP_SWITCH
867 if (handled) {
868 ALOGD("App switch has arrived.");
869 } else {
870 ALOGD("App switch was abandoned.");
871 }
872#endif
873}
874
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700876 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877}
878
879bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700880 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 return false;
882 }
883
884 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700885 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700886 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700888 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889
890 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700891 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 return true;
893}
894
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700895void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
896 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897}
898
899void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700900 while (!mInboundQueue.empty()) {
901 EventEntry* entry = mInboundQueue.front();
902 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903 releaseInboundEventLocked(entry);
904 }
905 traceInboundQueueLengthLocked();
906}
907
908void InputDispatcher::releasePendingEventLocked() {
909 if (mPendingEvent) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700910 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700912 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913 }
914}
915
916void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
917 InjectionState* injectionState = entry->injectionState;
918 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
919#if DEBUG_DISPATCH_CYCLE
920 ALOGD("Injected inbound event was dropped.");
921#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800922 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 }
924 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700925 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 }
927 addRecentEventLocked(entry);
928 entry->release();
929}
930
931void InputDispatcher::resetKeyRepeatLocked() {
932 if (mKeyRepeatState.lastKeyEntry) {
933 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700934 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 }
936}
937
Garfield Tane84e6f92019-08-29 17:28:41 -0700938KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
940
941 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700942 uint32_t policyFlags = entry->policyFlags &
943 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944 if (entry->refCount == 1) {
945 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800946 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 entry->eventTime = currentTime;
948 entry->policyFlags = policyFlags;
949 entry->repeatCount += 1;
950 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700951 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800952 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800953 entry->displayId, policyFlags, entry->action, entry->flags,
954 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700955 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956
957 mKeyRepeatState.lastKeyEntry = newEntry;
958 entry->release();
959
960 entry = newEntry;
961 }
962 entry->syntheticRepeat = true;
963
964 // Increment reference count since we keep a reference to the event in
965 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
966 entry->refCount += 1;
967
968 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
969 return entry;
970}
971
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700972bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
973 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700975 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976#endif
977
978 // Reset key repeating in case a keyboard device was added or removed or something.
979 resetKeyRepeatLocked();
980
981 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700982 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
983 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700985 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 return true;
987}
988
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700991 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700992 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993#endif
994
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700995 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 options.deviceId = entry->deviceId;
997 synthesizeCancelationEventsForAllConnectionsLocked(options);
998 return true;
999}
1000
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001001void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001002 if (mPendingEvent != nullptr) {
1003 // Move the pending event to the front of the queue. This will give the chance
1004 // for the pending event to get dispatched to the newly focused window
1005 mInboundQueue.push_front(mPendingEvent);
1006 mPendingEvent = nullptr;
1007 }
1008
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001009 FocusEntry* focusEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001010 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001011
1012 // This event should go to the front of the queue, but behind all other focus events
1013 // Find the last focus event, and insert right after it
1014 std::deque<EventEntry*>::reverse_iterator it =
1015 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1016 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1017
1018 // Maintain the order of focus events. Insert the entry after all other focus events.
1019 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001020}
1021
1022void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1023 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1024 if (channel == nullptr) {
1025 return; // Window has gone away
1026 }
1027 InputTarget target;
1028 target.inputChannel = channel;
1029 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1030 entry->dispatchInProgress = true;
1031
1032 dispatchEventLocked(currentTime, entry, {target});
1033}
1034
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001036 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001038 if (!entry->dispatchInProgress) {
1039 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1040 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1041 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1042 if (mKeyRepeatState.lastKeyEntry &&
1043 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 // We have seen two identical key downs in a row which indicates that the device
1045 // driver is automatically generating key repeats itself. We take note of the
1046 // repeat here, but we disable our own next key repeat timer since it is clear that
1047 // we will not need to synthesize key repeats ourselves.
1048 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1049 resetKeyRepeatLocked();
1050 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1051 } else {
1052 // Not a repeat. Save key down state in case we do see a repeat later.
1053 resetKeyRepeatLocked();
1054 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1055 }
1056 mKeyRepeatState.lastKeyEntry = entry;
1057 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001058 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 resetKeyRepeatLocked();
1060 }
1061
1062 if (entry->repeatCount == 1) {
1063 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1064 } else {
1065 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1066 }
1067
1068 entry->dispatchInProgress = true;
1069
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001070 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 }
1072
1073 // Handle case where the policy asked us to try again later last time.
1074 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1075 if (currentTime < entry->interceptKeyWakeupTime) {
1076 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1077 *nextWakeupTime = entry->interceptKeyWakeupTime;
1078 }
1079 return false; // wait until next wakeup
1080 }
1081 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1082 entry->interceptKeyWakeupTime = 0;
1083 }
1084
1085 // Give the policy a chance to intercept the key.
1086 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1087 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001088 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001089 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001090 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001091 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001092 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 }
1095 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001096 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 entry->refCount += 1;
1098 return false; // wait for the command to run
1099 } else {
1100 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1101 }
1102 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 if (*dropReason == DropReason::NOT_DROPPED) {
1104 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105 }
1106 }
1107
1108 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001109 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001110 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001111 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001112 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001113 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114 return true;
1115 }
1116
1117 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001118 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001119 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001120 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1122 return false;
1123 }
1124
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001125 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1127 return true;
1128 }
1129
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001130 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001131 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132
1133 // Dispatch the key.
1134 dispatchEventLocked(currentTime, entry, inputTargets);
1135 return true;
1136}
1137
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001138void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001140 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001141 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1142 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001143 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1144 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1145 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146#endif
1147}
1148
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001149bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1150 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001151 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001153 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 entry->dispatchInProgress = true;
1155
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001156 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 }
1158
1159 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001160 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001161 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001162 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001163 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 return true;
1165 }
1166
1167 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1168
1169 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001170 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171
1172 bool conflictingPointerActions = false;
1173 int32_t injectionResult;
1174 if (isPointerEvent) {
1175 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001176 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001177 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001178 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 } else {
1180 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001181 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001182 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 }
1184 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1185 return false;
1186 }
1187
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001188 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001189 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1190 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1191 return true;
1192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001194 CancelationOptions::Mode mode(isPointerEvent
1195 ? CancelationOptions::CANCEL_POINTER_EVENTS
1196 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1197 CancelationOptions options(mode, "input event injection failed");
1198 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 return true;
1200 }
1201
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001202 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001203 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001205 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001206 std::unordered_map<int32_t, TouchState>::iterator it =
1207 mTouchStatesByDisplay.find(entry->displayId);
1208 if (it != mTouchStatesByDisplay.end()) {
1209 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001210 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001211 // The event has gone through these portal windows, so we add monitoring targets of
1212 // the corresponding displays as well.
1213 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001214 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001215 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001216 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001217 }
1218 }
1219 }
1220 }
1221
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 // Dispatch the motion.
1223 if (conflictingPointerActions) {
1224 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001225 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 synthesizeCancelationEventsForAllConnectionsLocked(options);
1227 }
1228 dispatchEventLocked(currentTime, entry, inputTargets);
1229 return true;
1230}
1231
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001232void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001234 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001235 ", policyFlags=0x%x, "
1236 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1237 "metaState=0x%x, buttonState=0x%x,"
1238 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001239 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1240 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1241 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001243 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001245 "x=%f, y=%f, pressure=%f, size=%f, "
1246 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1247 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001248 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1249 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1250 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1251 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1252 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1253 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1254 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1255 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1256 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1257 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 }
1259#endif
1260}
1261
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001262void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1263 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001264 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265#if DEBUG_DISPATCH_CYCLE
1266 ALOGD("dispatchEventToCurrentInputTargets");
1267#endif
1268
1269 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1270
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001271 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001273 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001274 sp<Connection> connection =
1275 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001276 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001277 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001279 if (DEBUG_FOCUS) {
1280 ALOGD("Dropping event delivery to target with channel '%s' because it "
1281 "is no longer registered with the input dispatcher.",
1282 inputTarget.inputChannel->getName().c_str());
1283 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 }
1285 }
1286}
1287
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001288int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001289 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001291 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001292 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001294 if (DEBUG_FOCUS) {
1295 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1298 mInputTargetWaitStartTime = currentTime;
1299 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1300 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001301 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 }
1303 } else {
1304 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001305 ALOGI("Waiting for application to become ready for input: %s. Reason: %s",
1306 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001307 std::chrono::nanoseconds timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001308 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001310 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001311 timeout =
1312 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 } else {
1314 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1315 }
1316
1317 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1318 mInputTargetWaitStartTime = currentTime;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001319 mInputTargetWaitTimeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001321 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322
Yi Kong9b14ac62018-07-17 13:48:38 -07001323 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001324 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 }
Robert Carr740167f2018-10-11 19:03:41 -07001326 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1327 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 }
1329 }
1330 }
1331
1332 if (mInputTargetWaitTimeoutExpired) {
1333 return INPUT_EVENT_INJECTION_TIMED_OUT;
1334 }
1335
1336 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001337 onAnrLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001338 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339
1340 // Force poll loop to wake up immediately on next iteration once we get the
1341 // ANR response back from the policy.
1342 *nextWakeupTime = LONG_LONG_MIN;
1343 return INPUT_EVENT_INJECTION_PENDING;
1344 } else {
1345 // Force poll loop to wake up when timeout is due.
1346 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1347 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1348 }
1349 return INPUT_EVENT_INJECTION_PENDING;
1350 }
1351}
1352
Robert Carr803535b2018-08-02 16:38:15 -07001353void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001354 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
1355 TouchState& state = pair.second;
Robert Carr803535b2018-08-02 16:38:15 -07001356 state.removeWindowByToken(token);
1357 }
1358}
1359
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001360void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001361 nsecs_t timeoutExtension, const sp<IBinder>& inputConnectionToken) {
1362 if (timeoutExtension > 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 // Extend the timeout.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001364 mInputTargetWaitTimeoutTime = now() + timeoutExtension;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 } else {
1366 // Give up.
1367 mInputTargetWaitTimeoutExpired = true;
1368
1369 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001370 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001371 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001372 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001374 if (connection->status == Connection::STATUS_NORMAL) {
1375 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1376 "application not responding");
1377 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 }
1379 }
1380 }
1381}
1382
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001383void InputDispatcher::resetAnrTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001384 if (DEBUG_FOCUS) {
1385 ALOGD("Resetting ANR timeouts.");
1386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387
1388 // Reset input target wait timeout.
1389 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001390 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391}
1392
Tiger Huang721e26f2018-07-24 22:26:19 +08001393/**
1394 * Get the display id that the given event should go to. If this event specifies a valid display id,
1395 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1396 * Focused display is the display that the user most recently interacted with.
1397 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001399 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001401 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001402 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1403 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001404 break;
1405 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001406 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001407 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1408 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001409 break;
1410 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001411 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001412 case EventEntry::Type::CONFIGURATION_CHANGED:
1413 case EventEntry::Type::DEVICE_RESET: {
1414 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001415 return ADISPLAY_ID_NONE;
1416 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001417 }
1418 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1419}
1420
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001422 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001423 std::vector<InputTarget>& inputTargets,
1424 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001425 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426
Tiger Huang721e26f2018-07-24 22:26:19 +08001427 int32_t displayId = getTargetDisplayId(entry);
1428 sp<InputWindowHandle> focusedWindowHandle =
1429 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1430 sp<InputApplicationHandle> focusedApplicationHandle =
1431 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1432
Michael Wrightd02c5b62014-02-10 15:10:22 -08001433 // If there is no currently focused window and no focused application
1434 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001435 if (focusedWindowHandle == nullptr) {
1436 if (focusedApplicationHandle != nullptr) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001437 return handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1438 nullptr, nextWakeupTime,
1439 "Waiting because no window has focus but there is "
1440 "a focused application that may eventually add a "
1441 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 }
1443
Arthur Hung3b413f22018-10-26 18:05:34 +08001444 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001445 "%" PRId32 ".",
1446 displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001447 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 }
1449
1450 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001451 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001452 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 }
1454
Jeff Brownffb49772014-10-10 19:01:34 -07001455 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001456 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001457 if (!reason.empty()) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001458 return handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1459 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 }
1461
1462 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001463 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001464 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1465 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466
1467 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001468 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469}
1470
1471int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001472 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001473 std::vector<InputTarget>& inputTargets,
1474 nsecs_t* nextWakeupTime,
1475 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001476 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477 enum InjectionPermission {
1478 INJECTION_PERMISSION_UNKNOWN,
1479 INJECTION_PERMISSION_GRANTED,
1480 INJECTION_PERMISSION_DENIED
1481 };
1482
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483 // For security reasons, we defer updating the touch state until we are sure that
1484 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001485 int32_t displayId = entry.displayId;
1486 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1488
1489 // Update the touch state as needed based on the properties of the touch event.
1490 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1491 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1492 sp<InputWindowHandle> newHoverWindowHandle;
1493
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001494 // Copy current touch state into tempTouchState.
1495 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1496 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001497 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001498 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001499 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1500 mTouchStatesByDisplay.find(displayId);
1501 if (oldStateIt != mTouchStatesByDisplay.end()) {
1502 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001503 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001504 }
1505
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001506 bool isSplit = tempTouchState.split;
1507 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1508 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1509 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001510 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1511 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1512 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1513 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1514 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001515 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 bool wrongDevice = false;
1517 if (newGesture) {
1518 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001519 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001520 ALOGI("Dropping event because a pointer for a different device is already down "
1521 "in display %" PRId32,
1522 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001523 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1525 switchedDevice = false;
1526 wrongDevice = true;
1527 goto Failed;
1528 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001529 tempTouchState.reset();
1530 tempTouchState.down = down;
1531 tempTouchState.deviceId = entry.deviceId;
1532 tempTouchState.source = entry.source;
1533 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001535 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001536 ALOGI("Dropping move event because a pointer for a different device is already active "
1537 "in display %" PRId32,
1538 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001539 // TODO: test multiple simultaneous input streams.
1540 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1541 switchedDevice = false;
1542 wrongDevice = true;
1543 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 }
1545
1546 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1547 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1548
Garfield Tan00f511d2019-06-12 16:55:40 -07001549 int32_t x;
1550 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001552 // Always dispatch mouse events to cursor position.
1553 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001554 x = int32_t(entry.xCursorPosition);
1555 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001556 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001557 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1558 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001559 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001560 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001561 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001562 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1563 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001564
1565 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001566 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001567 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001570 if (newTouchedWindowHandle != nullptr &&
1571 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001572 // New window supports splitting, but we should never split mouse events.
1573 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 } else if (isSplit) {
1575 // New window does not support splitting but we have already split events.
1576 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001577 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 }
1579
1580 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001581 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001583 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001584 }
1585
1586 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1587 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001588 "(%d, %d) in display %" PRId32 ".",
1589 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001590 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1591 goto Failed;
1592 }
1593
1594 if (newTouchedWindowHandle != nullptr) {
1595 // Set target flags.
1596 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1597 if (isSplit) {
1598 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001600 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1601 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1602 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1603 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1604 }
1605
1606 // Update hover state.
1607 if (isHoverAction) {
1608 newHoverWindowHandle = newTouchedWindowHandle;
1609 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1610 newHoverWindowHandle = mLastHoverWindowHandle;
1611 }
1612
1613 // Update the temporary touch state.
1614 BitSet32 pointerIds;
1615 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001616 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001617 pointerIds.markBit(pointerId);
1618 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001619 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 }
1621
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001622 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 } else {
1624 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1625
1626 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001627 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001628 if (DEBUG_FOCUS) {
1629 ALOGD("Dropping event because the pointer is not down or we previously "
1630 "dropped the pointer down event in display %" PRId32,
1631 displayId);
1632 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1634 goto Failed;
1635 }
1636
1637 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001638 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001639 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001640 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1641 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642
1643 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001644 tempTouchState.getFirstForegroundWindowHandle();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001646 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001647 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1648 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001649 if (DEBUG_FOCUS) {
1650 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1651 oldTouchedWindowHandle->getName().c_str(),
1652 newTouchedWindowHandle->getName().c_str(), displayId);
1653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001655 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1656 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1657 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658
1659 // Make a slippery entrance into the new window.
1660 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1661 isSplit = true;
1662 }
1663
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001664 int32_t targetFlags =
1665 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 if (isSplit) {
1667 targetFlags |= InputTarget::FLAG_SPLIT;
1668 }
1669 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1670 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1671 }
1672
1673 BitSet32 pointerIds;
1674 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001675 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001677 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 }
1679 }
1680 }
1681
1682 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1683 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001684 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685#if DEBUG_HOVER
1686 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001687 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001689 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1690 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691 }
1692
1693 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001694 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695#if DEBUG_HOVER
1696 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001697 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001699 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1700 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1701 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702 }
1703 }
1704
1705 // Check permission to inject into all touched foreground windows and ensure there
1706 // is at least one touched foreground window.
1707 {
1708 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001709 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1711 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001712 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1714 injectionPermission = INJECTION_PERMISSION_DENIED;
1715 goto Failed;
1716 }
1717 }
1718 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001719 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001720 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001721 ALOGI("Dropping event because there is no touched foreground window in display "
1722 "%" PRId32 " or gesture monitor to receive it.",
1723 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1725 goto Failed;
1726 }
1727
1728 // Permission granted to injection into all touched foreground windows.
1729 injectionPermission = INJECTION_PERMISSION_GRANTED;
1730 }
1731
1732 // Check whether windows listening for outside touches are owned by the same UID. If it is
1733 // set the policy flag that we will not reveal coordinate information to this window.
1734 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1735 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001736 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001737 if (foregroundWindowHandle) {
1738 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001739 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001740 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1741 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1742 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001743 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1744 InputTarget::FLAG_ZERO_COORDS,
1745 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001746 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 }
1748 }
1749 }
1750 }
1751
1752 // Ensure all touched foreground windows are ready for new input.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001753 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001755 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001756 std::string reason =
1757 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1758 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001759 if (!reason.empty()) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001760 return handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1761 touchedWindow.windowHandle, nextWakeupTime,
1762 reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 }
1764 }
1765 }
1766
1767 // If this is the first pointer going down and the touched window has a wallpaper
1768 // then also add the touched wallpaper windows so they are locked in for the duration
1769 // of the touch gesture.
1770 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1771 // engine only supports touch events. We would need to add a mechanism similar
1772 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1773 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1774 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001775 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001776 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001777 const std::vector<sp<InputWindowHandle>> windowHandles =
1778 getWindowHandlesLocked(displayId);
1779 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001781 if (info->displayId == displayId &&
1782 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001783 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001784 .addOrUpdateWindow(windowHandle,
1785 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1786 InputTarget::
1787 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1788 InputTarget::FLAG_DISPATCH_AS_IS,
1789 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790 }
1791 }
1792 }
1793 }
1794
1795 // Success! Output targets.
1796 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1797
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001798 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001800 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 }
1802
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001803 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001804 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001805 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001806 }
1807
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 // Drop the outside or hover touch windows since we will not care about them
1809 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001810 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811
1812Failed:
1813 // Check injection permission once and for all.
1814 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001815 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 injectionPermission = INJECTION_PERMISSION_GRANTED;
1817 } else {
1818 injectionPermission = INJECTION_PERMISSION_DENIED;
1819 }
1820 }
1821
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001822 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1823 return injectionResult;
1824 }
1825
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001827 if (!wrongDevice) {
1828 if (switchedDevice) {
1829 if (DEBUG_FOCUS) {
1830 ALOGD("Conflicting pointer actions: Switched to a different device.");
1831 }
1832 *outConflictingPointerActions = true;
1833 }
1834
1835 if (isHoverAction) {
1836 // Started hovering, therefore no longer down.
1837 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001838 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001839 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1840 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 *outConflictingPointerActions = true;
1843 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001844 tempTouchState.reset();
1845 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1846 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1847 tempTouchState.deviceId = entry.deviceId;
1848 tempTouchState.source = entry.source;
1849 tempTouchState.displayId = displayId;
1850 }
1851 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1852 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1853 // All pointers up or canceled.
1854 tempTouchState.reset();
1855 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1856 // First pointer went down.
1857 if (oldState && oldState->down) {
1858 if (DEBUG_FOCUS) {
1859 ALOGD("Conflicting pointer actions: Down received while already down.");
1860 }
1861 *outConflictingPointerActions = true;
1862 }
1863 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1864 // One pointer went up.
1865 if (isSplit) {
1866 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1867 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001869 for (size_t i = 0; i < tempTouchState.windows.size();) {
1870 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1871 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1872 touchedWindow.pointerIds.clearBit(pointerId);
1873 if (touchedWindow.pointerIds.isEmpty()) {
1874 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1875 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001878 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001880 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001881 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001882
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001883 // Save changes unless the action was scroll in which case the temporary touch
1884 // state was only valid for this one action.
1885 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1886 if (tempTouchState.displayId >= 0) {
1887 mTouchStatesByDisplay[displayId] = tempTouchState;
1888 } else {
1889 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001893 // Update hover state.
1894 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 }
1896
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 return injectionResult;
1898}
1899
1900void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001901 int32_t targetFlags, BitSet32 pointerIds,
1902 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001903 std::vector<InputTarget>::iterator it =
1904 std::find_if(inputTargets.begin(), inputTargets.end(),
1905 [&windowHandle](const InputTarget& inputTarget) {
1906 return inputTarget.inputChannel->getConnectionToken() ==
1907 windowHandle->getToken();
1908 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00001909
Chavi Weingarten114b77f2020-01-15 22:35:10 +00001910 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001911
1912 if (it == inputTargets.end()) {
1913 InputTarget inputTarget;
1914 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1915 if (inputChannel == nullptr) {
1916 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1917 return;
1918 }
1919 inputTarget.inputChannel = inputChannel;
1920 inputTarget.flags = targetFlags;
1921 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
1922 inputTargets.push_back(inputTarget);
1923 it = inputTargets.end() - 1;
1924 }
1925
1926 ALOG_ASSERT(it->flags == targetFlags);
1927 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
1928
1929 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
1930 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931}
1932
Michael Wright3dd60e22019-03-27 22:06:44 +00001933void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001934 int32_t displayId, float xOffset,
1935 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001936 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1937 mGlobalMonitorsByDisplay.find(displayId);
1938
1939 if (it != mGlobalMonitorsByDisplay.end()) {
1940 const std::vector<Monitor>& monitors = it->second;
1941 for (const Monitor& monitor : monitors) {
1942 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 }
1945}
1946
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001947void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1948 float yOffset,
1949 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001950 InputTarget target;
1951 target.inputChannel = monitor.inputChannel;
1952 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001953 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00001954 inputTargets.push_back(target);
1955}
1956
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001958 const InjectionState* injectionState) {
1959 if (injectionState &&
1960 (windowHandle == nullptr ||
1961 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1962 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001963 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001965 "owned by uid %d",
1966 injectionState->injectorPid, injectionState->injectorUid,
1967 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 } else {
1969 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001970 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 }
1972 return false;
1973 }
1974 return true;
1975}
1976
Robert Carrc9bf1d32020-04-13 17:21:08 -07001977/**
1978 * Indicate whether one window handle should be considered as obscuring
1979 * another window handle. We only check a few preconditions. Actually
1980 * checking the bounds is left to the caller.
1981 */
1982static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
1983 const sp<InputWindowHandle>& otherHandle) {
1984 // Compare by token so cloned layers aren't counted
1985 if (haveSameToken(windowHandle, otherHandle)) {
1986 return false;
1987 }
1988 auto info = windowHandle->getInfo();
1989 auto otherInfo = otherHandle->getInfo();
1990 if (!otherInfo->visible) {
1991 return false;
1992 } else if (info->ownerPid == otherInfo->ownerPid && otherHandle->getToken() == nullptr) {
1993 // In general, if ownerPid is the same we don't want to generate occlusion
1994 // events. This line is now necessary since we are including all Surfaces
1995 // in occlusion calculation, so if we didn't check PID like this SurfaceView
1996 // would occlude their parents. On the other hand before we started including
1997 // all surfaces in occlusion calculation and had this line, we would count
1998 // windows with an input channel from the same PID as occluding, and so we
1999 // preserve this behavior with the getToken() == null check.
2000 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002001 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002002 return false;
2003 } else if (otherInfo->displayId != info->displayId) {
2004 return false;
2005 }
2006 return true;
2007}
2008
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002009bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2010 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002012 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2013 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002014 if (windowHandle == otherHandle) {
2015 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002018 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002019 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 return true;
2021 }
2022 }
2023 return false;
2024}
2025
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002026bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2027 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002028 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002029 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002030 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002031 if (windowHandle == otherHandle) {
2032 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002033 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002034 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002035 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002036 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002037 return true;
2038 }
2039 }
2040 return false;
2041}
2042
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002043std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
2044 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002045 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07002046 // If the window is paused then keep waiting.
2047 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002048 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002049 }
2050
2051 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07002052 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002053 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002054 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002055 "registered with the input dispatcher. The window may be in the "
2056 "process of being removed.",
2057 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002058 }
2059
2060 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07002061 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002062 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002063 "The window may be in the process of being removed.",
2064 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07002065 }
2066
2067 // If the connection is backed up then keep waiting.
2068 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002069 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002070 "Outbound queue length: %zu. Wait queue length: %zu.",
2071 targetType, connection->outboundQueue.size(),
2072 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07002073 }
2074
2075 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002076 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07002077 // If the event is a key event, then we must wait for all previous events to
2078 // complete before delivering it because previous events may have the
2079 // side-effect of transferring focus to a different window and we want to
2080 // ensure that the following keys are sent to the new window.
2081 //
2082 // Suppose the user touches a button in a window then immediately presses "A".
2083 // If the button causes a pop-up window to appear then we want to ensure that
2084 // the "A" key is delivered to the new pop-up window. This is because users
2085 // often anticipate pending UI changes when typing on a keyboard.
2086 // To obtain this behavior, we must serialize key events with respect to all
2087 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002088 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002089 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002090 "finished processing all of the input events that were previously "
2091 "delivered to it. Outbound queue length: %zu. Wait queue length: "
2092 "%zu.",
2093 targetType, connection->outboundQueue.size(),
2094 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095 }
Jeff Brownffb49772014-10-10 19:01:34 -07002096 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097 // Touch events can always be sent to a window immediately because the user intended
2098 // to touch whatever was visible at the time. Even if focus changes or a new
2099 // window appears moments later, the touch event was meant to be delivered to
2100 // whatever window happened to be on screen at the time.
2101 //
2102 // Generic motion events, such as trackball or joystick events are a little trickier.
2103 // Like key events, generic motion events are delivered to the focused window.
2104 // Unlike key events, generic motion events don't tend to transfer focus to other
2105 // windows and it is not important for them to be serialized. So we prefer to deliver
2106 // generic motion events as soon as possible to improve efficiency and reduce lag
2107 // through batching.
2108 //
2109 // The one case where we pause input event delivery is when the wait queue is piling
2110 // up with lots of events because the application is not responding.
2111 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002112 if (!connection->waitQueue.empty() &&
2113 currentTime >=
2114 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002115 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002116 "finished processing certain input events that were delivered to "
2117 "it over "
2118 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
2119 "%0.1fms.",
2120 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
2121 connection->waitQueue.size(),
2122 (currentTime - connection->waitQueue.front()->deliveryTime) *
2123 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 }
2125 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002126 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127}
2128
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002129std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 const sp<InputApplicationHandle>& applicationHandle,
2131 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002132 if (applicationHandle != nullptr) {
2133 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002134 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 } else {
2136 return applicationHandle->getName();
2137 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002138 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002139 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002141 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 }
2143}
2144
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002145void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002146 if (eventEntry.type == EventEntry::Type::FOCUS) {
2147 // Focus events are passed to apps, but do not represent user activity.
2148 return;
2149 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002150 int32_t displayId = getTargetDisplayId(eventEntry);
2151 sp<InputWindowHandle> focusedWindowHandle =
2152 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2153 if (focusedWindowHandle != nullptr) {
2154 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2156#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002157 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158#endif
2159 return;
2160 }
2161 }
2162
2163 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002164 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002165 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002166 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2167 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002168 return;
2169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002171 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002172 eventType = USER_ACTIVITY_EVENT_TOUCH;
2173 }
2174 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002176 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002177 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2178 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002179 return;
2180 }
2181 eventType = USER_ACTIVITY_EVENT_BUTTON;
2182 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002184 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002185 case EventEntry::Type::CONFIGURATION_CHANGED:
2186 case EventEntry::Type::DEVICE_RESET: {
2187 LOG_ALWAYS_FATAL("%s events are not user activity",
2188 EventEntry::typeToString(eventEntry.type));
2189 break;
2190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 }
2192
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002193 std::unique_ptr<CommandEntry> commandEntry =
2194 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002195 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002197 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198}
2199
2200void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002201 const sp<Connection>& connection,
2202 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002203 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002204 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002205 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002206 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002207 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002208 ATRACE_NAME(message.c_str());
2209 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210#if DEBUG_DISPATCH_CYCLE
2211 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002212 "globalScaleFactor=%f, pointerIds=0x%x %s",
2213 connection->getInputChannelName().c_str(), inputTarget.flags,
2214 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2215 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216#endif
2217
2218 // Skip this event if the connection status is not normal.
2219 // We don't want to enqueue additional outbound events if the connection is broken.
2220 if (connection->status != Connection::STATUS_NORMAL) {
2221#if DEBUG_DISPATCH_CYCLE
2222 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002223 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224#endif
2225 return;
2226 }
2227
2228 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002229 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2230 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2231 "Entry type %s should not have FLAG_SPLIT",
2232 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002234 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002235 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002236 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002237 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 if (!splitMotionEntry) {
2239 return; // split event was dropped
2240 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002241 if (DEBUG_FOCUS) {
2242 ALOGD("channel '%s' ~ Split motion event.",
2243 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002244 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002245 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002246 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 splitMotionEntry->release();
2248 return;
2249 }
2250 }
2251
2252 // Not splitting. Enqueue dispatch entries for the event as is.
2253 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2254}
2255
2256void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002257 const sp<Connection>& connection,
2258 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002259 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002260 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002261 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002262 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002263 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002264 ATRACE_NAME(message.c_str());
2265 }
2266
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002267 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268
2269 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002270 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002271 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002272 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002273 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002274 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002275 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002276 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002277 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002278 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002279 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002280 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002281 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282
2283 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002284 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 startDispatchCycleLocked(currentTime, connection);
2286 }
2287}
2288
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2290 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002291 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002292 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002293 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002294 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2295 connection->getInputChannelName().c_str(),
2296 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002297 ATRACE_NAME(message.c_str());
2298 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002299 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 if (!(inputTargetFlags & dispatchMode)) {
2301 return;
2302 }
2303 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2304
2305 // This is a new event.
2306 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002307 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002308 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002310 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2311 // different EventEntry than what was passed in.
2312 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002314 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002315 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002316 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002317 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002318 dispatchEntry->resolvedAction = keyEntry.action;
2319 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002321 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2322 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002324 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2325 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002327 return; // skip the inconsistent event
2328 }
2329 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002332 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002333 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002334 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2335 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2336 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2337 static_cast<int32_t>(IdGenerator::Source::OTHER);
2338 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002339 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2340 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2341 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2342 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2343 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2344 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2345 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2346 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2347 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2348 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2349 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002350 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002351 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002352 }
2353 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002354 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2355 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002357 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2358 "event",
2359 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002360#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002361 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002363
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002364 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002365 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2366 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2367 }
2368 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2369 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002372 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2373 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002375 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2376 "event",
2377 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002379 return; // skip the inconsistent event
2380 }
2381
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002382 dispatchEntry->resolvedEventId =
2383 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2384 ? mIdGenerator.nextId()
2385 : motionEntry.id;
2386 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2387 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2388 ") to MotionEvent(id=0x%" PRIx32 ").",
2389 motionEntry.id, dispatchEntry->resolvedEventId);
2390 ATRACE_NAME(message.c_str());
2391 }
2392
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002393 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002394 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002395
2396 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002398 case EventEntry::Type::FOCUS: {
2399 break;
2400 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002401 case EventEntry::Type::CONFIGURATION_CHANGED:
2402 case EventEntry::Type::DEVICE_RESET: {
2403 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002404 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002405 break;
2406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407 }
2408
2409 // Remember that we are waiting for this dispatch to complete.
2410 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002411 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412 }
2413
2414 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002415 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002416 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002417}
2418
chaviwfd6d3512019-03-25 13:23:49 -07002419void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002420 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002421 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002422 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2423 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002424 return;
2425 }
2426
2427 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2428 if (inputWindowHandle == nullptr) {
2429 return;
2430 }
2431
chaviw8c9cf542019-03-25 13:02:48 -07002432 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002433 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002434
2435 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2436
2437 if (!hasFocusChanged) {
2438 return;
2439 }
2440
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002441 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2442 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002443 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002444 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445}
2446
2447void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002448 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002449 if (ATRACE_ENABLED()) {
2450 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002451 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002452 ATRACE_NAME(message.c_str());
2453 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002455 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456#endif
2457
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002458 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2459 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 dispatchEntry->deliveryTime = currentTime;
2461
2462 // Publish the event.
2463 status_t status;
2464 EventEntry* eventEntry = dispatchEntry->eventEntry;
2465 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002466 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002467 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2468 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002470 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002471 status =
2472 connection->inputPublisher
2473 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2474 keyEntry->deviceId, keyEntry->source,
2475 keyEntry->displayId, std::move(hmac),
2476 dispatchEntry->resolvedAction,
2477 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2478 keyEntry->scanCode, keyEntry->metaState,
2479 keyEntry->repeatCount, keyEntry->downTime,
2480 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002481 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 }
2483
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002484 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002485 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002487 PointerCoords scaledCoords[MAX_POINTERS];
2488 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2489
chaviw82357092020-01-28 13:13:06 -08002490 // Set the X and Y offset and X and Y scale depending on the input source.
2491 float xOffset = 0.0f, yOffset = 0.0f;
2492 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002493 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2494 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2495 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002496 xScale = dispatchEntry->windowXScale;
2497 yScale = dispatchEntry->windowYScale;
2498 xOffset = dispatchEntry->xOffset * xScale;
2499 yOffset = dispatchEntry->yOffset * yScale;
2500 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002501 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2502 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002503 // Don't apply window scale here since we don't want scale to affect raw
2504 // coordinates. The scale will be sent back to the client and applied
2505 // later when requesting relative coordinates.
2506 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2507 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002508 }
2509 usingCoords = scaledCoords;
2510 }
2511 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002512 // We don't want the dispatch target to know.
2513 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2514 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2515 scaledCoords[i].clear();
2516 }
2517 usingCoords = scaledCoords;
2518 }
2519 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002520
2521 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002522
2523 // Publish the motion event.
2524 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002525 .publishMotionEvent(dispatchEntry->seq,
2526 dispatchEntry->resolvedEventId,
2527 motionEntry->deviceId, motionEntry->source,
2528 motionEntry->displayId, std::move(hmac),
2529 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002530 motionEntry->actionButton,
2531 dispatchEntry->resolvedFlags,
2532 motionEntry->edgeFlags, motionEntry->metaState,
2533 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002534 motionEntry->classification, xScale, yScale,
2535 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002536 motionEntry->yPrecision,
2537 motionEntry->xCursorPosition,
2538 motionEntry->yCursorPosition,
2539 motionEntry->downTime, motionEntry->eventTime,
2540 motionEntry->pointerCount,
2541 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002542 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002543 break;
2544 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002545 case EventEntry::Type::FOCUS: {
2546 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2547 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002548 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002549 focusEntry->hasFocus,
2550 mInTouchMode);
2551 break;
2552 }
2553
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002554 case EventEntry::Type::CONFIGURATION_CHANGED:
2555 case EventEntry::Type::DEVICE_RESET: {
2556 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2557 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002558 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002560 }
2561
2562 // Check the result.
2563 if (status) {
2564 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002565 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002567 "This is unexpected because the wait queue is empty, so the pipe "
2568 "should be empty and we shouldn't have any problems writing an "
2569 "event to it, status=%d",
2570 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002571 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2572 } else {
2573 // Pipe is full and we are waiting for the app to finish process some events
2574 // before sending more events to it.
2575#if DEBUG_DISPATCH_CYCLE
2576 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577 "waiting for the application to catch up",
2578 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579#endif
2580 connection->inputPublisherBlocked = true;
2581 }
2582 } else {
2583 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002584 "status=%d",
2585 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2587 }
2588 return;
2589 }
2590
2591 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002592 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2593 connection->outboundQueue.end(),
2594 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002595 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002596 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002597 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 }
2599}
2600
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002601const std::array<uint8_t, 32> InputDispatcher::getSignature(
2602 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2603 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2604 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2605 // Only sign events up and down events as the purely move events
2606 // are tied to their up/down counterparts so signing would be redundant.
2607 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2608 verifiedEvent.actionMasked = actionMasked;
2609 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2610 return mHmacKeyManager.sign(verifiedEvent);
2611 }
2612 return INVALID_HMAC;
2613}
2614
2615const std::array<uint8_t, 32> InputDispatcher::getSignature(
2616 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2617 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2618 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2619 verifiedEvent.action = dispatchEntry.resolvedAction;
2620 return mHmacKeyManager.sign(verifiedEvent);
2621}
2622
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002624 const sp<Connection>& connection, uint32_t seq,
2625 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626#if DEBUG_DISPATCH_CYCLE
2627 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002628 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629#endif
2630
2631 connection->inputPublisherBlocked = false;
2632
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002633 if (connection->status == Connection::STATUS_BROKEN ||
2634 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002635 return;
2636 }
2637
2638 // Notify other system components and prepare to start the next dispatch cycle.
2639 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2640}
2641
2642void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002643 const sp<Connection>& connection,
2644 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645#if DEBUG_DISPATCH_CYCLE
2646 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002647 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648#endif
2649
2650 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002651 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002652 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002653 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002654 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655
2656 // The connection appears to be unrecoverably broken.
2657 // Ignore already broken or zombie connections.
2658 if (connection->status == Connection::STATUS_NORMAL) {
2659 connection->status = Connection::STATUS_BROKEN;
2660
2661 if (notify) {
2662 // Notify other system components.
2663 onDispatchCycleBrokenLocked(currentTime, connection);
2664 }
2665 }
2666}
2667
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002668void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2669 while (!queue.empty()) {
2670 DispatchEntry* dispatchEntry = queue.front();
2671 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002672 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673 }
2674}
2675
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002676void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002678 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679 }
2680 delete dispatchEntry;
2681}
2682
2683int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2684 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2685
2686 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002687 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002689 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002691 "fd=%d, events=0x%x",
2692 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693 return 0; // remove the callback
2694 }
2695
2696 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002697 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2699 if (!(events & ALOOPER_EVENT_INPUT)) {
2700 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002701 "events=0x%x",
2702 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 return 1;
2704 }
2705
2706 nsecs_t currentTime = now();
2707 bool gotOne = false;
2708 status_t status;
2709 for (;;) {
2710 uint32_t seq;
2711 bool handled;
2712 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2713 if (status) {
2714 break;
2715 }
2716 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2717 gotOne = true;
2718 }
2719 if (gotOne) {
2720 d->runCommandsLockedInterruptible();
2721 if (status == WOULD_BLOCK) {
2722 return 1;
2723 }
2724 }
2725
2726 notify = status != DEAD_OBJECT || !connection->monitor;
2727 if (notify) {
2728 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002729 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 }
2731 } else {
2732 // Monitor channels are never explicitly unregistered.
2733 // We do it automatically when the remote endpoint is closed so don't warn
2734 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002735 const bool stillHaveWindowHandle =
2736 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2737 nullptr;
2738 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 if (notify) {
2740 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002741 "events=0x%x",
2742 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743 }
2744 }
2745
2746 // Unregister the channel.
2747 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2748 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002749 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750}
2751
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002752void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002754 for (const auto& pair : mConnectionsByFd) {
2755 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756 }
2757}
2758
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002759void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002760 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002761 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2762 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2763}
2764
2765void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2766 const CancelationOptions& options,
2767 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2768 for (const auto& it : monitorsByDisplay) {
2769 const std::vector<Monitor>& monitors = it.second;
2770 for (const Monitor& monitor : monitors) {
2771 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002772 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002773 }
2774}
2775
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2777 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002778 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002779 if (connection == nullptr) {
2780 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002782
2783 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784}
2785
2786void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2787 const sp<Connection>& connection, const CancelationOptions& options) {
2788 if (connection->status == Connection::STATUS_BROKEN) {
2789 return;
2790 }
2791
2792 nsecs_t currentTime = now();
2793
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002794 std::vector<EventEntry*> cancelationEvents =
2795 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002797 if (cancelationEvents.empty()) {
2798 return;
2799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002801 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2802 "with reality: %s, mode=%d.",
2803 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2804 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002806
2807 InputTarget target;
2808 sp<InputWindowHandle> windowHandle =
2809 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2810 if (windowHandle != nullptr) {
2811 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2812 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2813 windowInfo->windowXScale, windowInfo->windowYScale);
2814 target.globalScaleFactor = windowInfo->globalScaleFactor;
2815 }
2816 target.inputChannel = connection->inputChannel;
2817 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2818
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002819 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2820 EventEntry* cancelationEventEntry = cancelationEvents[i];
2821 switch (cancelationEventEntry->type) {
2822 case EventEntry::Type::KEY: {
2823 logOutboundKeyDetails("cancel - ",
2824 static_cast<const KeyEntry&>(*cancelationEventEntry));
2825 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002827 case EventEntry::Type::MOTION: {
2828 logOutboundMotionDetails("cancel - ",
2829 static_cast<const MotionEntry&>(*cancelationEventEntry));
2830 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002832 case EventEntry::Type::FOCUS: {
2833 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2834 break;
2835 }
2836 case EventEntry::Type::CONFIGURATION_CHANGED:
2837 case EventEntry::Type::DEVICE_RESET: {
2838 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2839 EventEntry::typeToString(cancelationEventEntry->type));
2840 break;
2841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 }
2843
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002844 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2845 target, InputTarget::FLAG_DISPATCH_AS_IS);
2846
2847 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002849
2850 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851}
2852
Svet Ganov5d3bc372020-01-26 23:11:07 -08002853void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2854 const sp<Connection>& connection) {
2855 if (connection->status == Connection::STATUS_BROKEN) {
2856 return;
2857 }
2858
2859 nsecs_t currentTime = now();
2860
2861 std::vector<EventEntry*> downEvents =
2862 connection->inputState.synthesizePointerDownEvents(currentTime);
2863
2864 if (downEvents.empty()) {
2865 return;
2866 }
2867
2868#if DEBUG_OUTBOUND_EVENT_DETAILS
2869 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2870 connection->getInputChannelName().c_str(), downEvents.size());
2871#endif
2872
2873 InputTarget target;
2874 sp<InputWindowHandle> windowHandle =
2875 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2876 if (windowHandle != nullptr) {
2877 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2878 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2879 windowInfo->windowXScale, windowInfo->windowYScale);
2880 target.globalScaleFactor = windowInfo->globalScaleFactor;
2881 }
2882 target.inputChannel = connection->inputChannel;
2883 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2884
2885 for (EventEntry* downEventEntry : downEvents) {
2886 switch (downEventEntry->type) {
2887 case EventEntry::Type::MOTION: {
2888 logOutboundMotionDetails("down - ",
2889 static_cast<const MotionEntry&>(*downEventEntry));
2890 break;
2891 }
2892
2893 case EventEntry::Type::KEY:
2894 case EventEntry::Type::FOCUS:
2895 case EventEntry::Type::CONFIGURATION_CHANGED:
2896 case EventEntry::Type::DEVICE_RESET: {
2897 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2898 EventEntry::typeToString(downEventEntry->type));
2899 break;
2900 }
2901 }
2902
2903 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2904 target, InputTarget::FLAG_DISPATCH_AS_IS);
2905
2906 downEventEntry->release();
2907 }
2908
2909 startDispatchCycleLocked(currentTime, connection);
2910}
2911
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002912MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002913 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914 ALOG_ASSERT(pointerIds.value != 0);
2915
2916 uint32_t splitPointerIndexMap[MAX_POINTERS];
2917 PointerProperties splitPointerProperties[MAX_POINTERS];
2918 PointerCoords splitPointerCoords[MAX_POINTERS];
2919
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002920 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921 uint32_t splitPointerCount = 0;
2922
2923 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002924 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002926 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927 uint32_t pointerId = uint32_t(pointerProperties.id);
2928 if (pointerIds.hasBit(pointerId)) {
2929 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2930 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2931 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002932 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 splitPointerCount += 1;
2934 }
2935 }
2936
2937 if (splitPointerCount != pointerIds.count()) {
2938 // This is bad. We are missing some of the pointers that we expected to deliver.
2939 // Most likely this indicates that we received an ACTION_MOVE events that has
2940 // different pointer ids than we expected based on the previous ACTION_DOWN
2941 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2942 // in this way.
2943 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002944 "we expected there to be %d pointers. This probably means we received "
2945 "a broken sequence of pointer ids from the input device.",
2946 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002947 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948 }
2949
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002950 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002952 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2953 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2955 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002956 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957 uint32_t pointerId = uint32_t(pointerProperties.id);
2958 if (pointerIds.hasBit(pointerId)) {
2959 if (pointerIds.count() == 1) {
2960 // The first/last pointer went down/up.
2961 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002962 ? AMOTION_EVENT_ACTION_DOWN
2963 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002964 } else {
2965 // A secondary pointer went down/up.
2966 uint32_t splitPointerIndex = 0;
2967 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2968 splitPointerIndex += 1;
2969 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002970 action = maskedAction |
2971 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 }
2973 } else {
2974 // An unrelated pointer changed.
2975 action = AMOTION_EVENT_ACTION_MOVE;
2976 }
2977 }
2978
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002979 int32_t newId = mIdGenerator.nextId();
2980 if (ATRACE_ENABLED()) {
2981 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
2982 ") to MotionEvent(id=0x%" PRIx32 ").",
2983 originalMotionEntry.id, newId);
2984 ATRACE_NAME(message.c_str());
2985 }
Garfield Tan00f511d2019-06-12 16:55:40 -07002986 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002987 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
2988 originalMotionEntry.source, originalMotionEntry.displayId,
2989 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002990 originalMotionEntry.actionButton, originalMotionEntry.flags,
2991 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2992 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2993 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2994 originalMotionEntry.xCursorPosition,
2995 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002996 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002998 if (originalMotionEntry.injectionState) {
2999 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000 splitMotionEntry->injectionState->refCount += 1;
3001 }
3002
3003 return splitMotionEntry;
3004}
3005
3006void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3007#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003008 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009#endif
3010
3011 bool needWake;
3012 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003013 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014
Prabir Pradhan42611e02018-11-27 14:04:02 -08003015 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003016 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 needWake = enqueueInboundEventLocked(newEntry);
3018 } // release lock
3019
3020 if (needWake) {
3021 mLooper->wake();
3022 }
3023}
3024
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003025/**
3026 * If one of the meta shortcuts is detected, process them here:
3027 * Meta + Backspace -> generate BACK
3028 * Meta + Enter -> generate HOME
3029 * This will potentially overwrite keyCode and metaState.
3030 */
3031void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003032 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003033 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3034 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3035 if (keyCode == AKEYCODE_DEL) {
3036 newKeyCode = AKEYCODE_BACK;
3037 } else if (keyCode == AKEYCODE_ENTER) {
3038 newKeyCode = AKEYCODE_HOME;
3039 }
3040 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003041 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003042 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003043 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003044 keyCode = newKeyCode;
3045 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3046 }
3047 } else if (action == AKEY_EVENT_ACTION_UP) {
3048 // In order to maintain a consistent stream of up and down events, check to see if the key
3049 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3050 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003051 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003052 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003053 auto replacementIt = mReplacedKeys.find(replacement);
3054 if (replacementIt != mReplacedKeys.end()) {
3055 keyCode = replacementIt->second;
3056 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003057 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3058 }
3059 }
3060}
3061
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3063#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003064 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3065 "policyFlags=0x%x, action=0x%x, "
3066 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3067 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3068 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3069 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070#endif
3071 if (!validateKeyEvent(args->action)) {
3072 return;
3073 }
3074
3075 uint32_t policyFlags = args->policyFlags;
3076 int32_t flags = args->flags;
3077 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003078 // InputDispatcher tracks and generates key repeats on behalf of
3079 // whatever notifies it, so repeatCount should always be set to 0
3080 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3082 policyFlags |= POLICY_FLAG_VIRTUAL;
3083 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085 if (policyFlags & POLICY_FLAG_FUNCTION) {
3086 metaState |= AMETA_FUNCTION_ON;
3087 }
3088
3089 policyFlags |= POLICY_FLAG_TRUSTED;
3090
Michael Wright78f24442014-08-06 15:55:28 -07003091 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003092 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003093
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003095 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003096 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3097 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098
Michael Wright2b3c3302018-03-02 17:19:13 +00003099 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003101 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3102 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003103 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003104 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106 bool needWake;
3107 { // acquire lock
3108 mLock.lock();
3109
3110 if (shouldSendKeyToInputFilterLocked(args)) {
3111 mLock.unlock();
3112
3113 policyFlags |= POLICY_FLAG_FILTERED;
3114 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3115 return; // event was consumed by the filter
3116 }
3117
3118 mLock.lock();
3119 }
3120
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003122 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003123 args->displayId, policyFlags, args->action, flags, keyCode,
3124 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125
3126 needWake = enqueueInboundEventLocked(newEntry);
3127 mLock.unlock();
3128 } // release lock
3129
3130 if (needWake) {
3131 mLooper->wake();
3132 }
3133}
3134
3135bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3136 return mInputFilterEnabled;
3137}
3138
3139void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3140#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003141 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3142 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003143 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3144 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003145 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003146 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3147 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3148 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3149 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150 for (uint32_t i = 0; i < args->pointerCount; i++) {
3151 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003152 "x=%f, y=%f, pressure=%f, size=%f, "
3153 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3154 "orientation=%f",
3155 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3156 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3157 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3158 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3159 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3160 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3161 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3162 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3163 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3164 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 }
3166#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003167 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3168 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 return;
3170 }
3171
3172 uint32_t policyFlags = args->policyFlags;
3173 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003174
3175 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003176 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003177 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3178 ALOGW("Excessive delay in interceptMotionBeforeQueueing; 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
3182 bool needWake;
3183 { // acquire lock
3184 mLock.lock();
3185
3186 if (shouldSendMotionToInputFilterLocked(args)) {
3187 mLock.unlock();
3188
3189 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003190 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3191 args->action, args->actionButton, args->flags, args->edgeFlags,
3192 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3193 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3194 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3195 args->downTime, args->eventTime, args->pointerCount,
3196 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197
3198 policyFlags |= POLICY_FLAG_FILTERED;
3199 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3200 return; // event was consumed by the filter
3201 }
3202
3203 mLock.lock();
3204 }
3205
3206 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003207 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003208 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003209 args->displayId, policyFlags, args->action, args->actionButton,
3210 args->flags, args->metaState, args->buttonState,
3211 args->classification, args->edgeFlags, args->xPrecision,
3212 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3213 args->downTime, args->pointerCount, args->pointerProperties,
3214 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215
3216 needWake = enqueueInboundEventLocked(newEntry);
3217 mLock.unlock();
3218 } // release lock
3219
3220 if (needWake) {
3221 mLooper->wake();
3222 }
3223}
3224
3225bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003226 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227}
3228
3229void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3230#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003231 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003232 "switchMask=0x%08x",
3233 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234#endif
3235
3236 uint32_t policyFlags = args->policyFlags;
3237 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003238 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239}
3240
3241void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3242#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3244 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245#endif
3246
3247 bool needWake;
3248 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003249 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250
Prabir Pradhan42611e02018-11-27 14:04:02 -08003251 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003252 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 needWake = enqueueInboundEventLocked(newEntry);
3254 } // release lock
3255
3256 if (needWake) {
3257 mLooper->wake();
3258 }
3259}
3260
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003261int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3262 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003263 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264#if DEBUG_INBOUND_EVENT_DETAILS
3265 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003266 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3267 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268#endif
3269
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003270 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271
3272 policyFlags |= POLICY_FLAG_INJECTED;
3273 if (hasInjectionPermission(injectorPid, injectorUid)) {
3274 policyFlags |= POLICY_FLAG_TRUSTED;
3275 }
3276
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003277 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003279 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003280 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3281 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003282 if (!validateKeyEvent(action)) {
3283 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003286 int32_t flags = incomingKey.getFlags();
3287 int32_t keyCode = incomingKey.getKeyCode();
3288 int32_t metaState = incomingKey.getMetaState();
3289 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003290 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003291 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003292 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003293 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3294 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3295 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003297 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3298 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003299 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003300
3301 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3302 android::base::Timer t;
3303 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3304 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3305 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3306 std::to_string(t.duration().count()).c_str());
3307 }
3308 }
3309
3310 mLock.lock();
3311 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003312 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3313 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003314 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3315 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003316 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003317 injectedEntries.push(injectedEntry);
3318 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319 }
3320
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003321 case AINPUT_EVENT_TYPE_MOTION: {
3322 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3323 int32_t action = motionEvent->getAction();
3324 size_t pointerCount = motionEvent->getPointerCount();
3325 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3326 int32_t actionButton = motionEvent->getActionButton();
3327 int32_t displayId = motionEvent->getDisplayId();
3328 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3329 return INPUT_EVENT_INJECTION_FAILED;
3330 }
3331
3332 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3333 nsecs_t eventTime = motionEvent->getEventTime();
3334 android::base::Timer t;
3335 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3336 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3337 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3338 std::to_string(t.duration().count()).c_str());
3339 }
3340 }
3341
3342 mLock.lock();
3343 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3344 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3345 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003346 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3347 motionEvent->getSource(), motionEvent->getDisplayId(),
3348 policyFlags, action, actionButton, motionEvent->getFlags(),
3349 motionEvent->getMetaState(), motionEvent->getButtonState(),
3350 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3351 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003352 motionEvent->getRawXCursorPosition(),
3353 motionEvent->getRawYCursorPosition(),
3354 motionEvent->getDownTime(), uint32_t(pointerCount),
3355 pointerProperties, samplePointerCoords,
3356 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003357 injectedEntries.push(injectedEntry);
3358 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3359 sampleEventTimes += 1;
3360 samplePointerCoords += pointerCount;
3361 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003362 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003363 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003364 motionEvent->getDisplayId(), policyFlags, action,
3365 actionButton, motionEvent->getFlags(),
3366 motionEvent->getMetaState(), motionEvent->getButtonState(),
3367 motionEvent->getClassification(),
3368 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3369 motionEvent->getYPrecision(),
3370 motionEvent->getRawXCursorPosition(),
3371 motionEvent->getRawYCursorPosition(),
3372 motionEvent->getDownTime(), uint32_t(pointerCount),
3373 pointerProperties, samplePointerCoords,
3374 motionEvent->getXOffset(), motionEvent->getYOffset());
3375 injectedEntries.push(nextInjectedEntry);
3376 }
3377 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003380 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003381 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003382 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 }
3384
3385 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3386 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3387 injectionState->injectionIsAsync = true;
3388 }
3389
3390 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003391 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392
3393 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003394 while (!injectedEntries.empty()) {
3395 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3396 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397 }
3398
3399 mLock.unlock();
3400
3401 if (needWake) {
3402 mLooper->wake();
3403 }
3404
3405 int32_t injectionResult;
3406 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003407 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408
3409 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3410 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3411 } else {
3412 for (;;) {
3413 injectionResult = injectionState->injectionResult;
3414 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3415 break;
3416 }
3417
3418 nsecs_t remainingTimeout = endTime - now();
3419 if (remainingTimeout <= 0) {
3420#if DEBUG_INJECTION
3421 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003422 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423#endif
3424 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3425 break;
3426 }
3427
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003428 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429 }
3430
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003431 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3432 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 while (injectionState->pendingForegroundDispatches != 0) {
3434#if DEBUG_INJECTION
3435 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003436 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437#endif
3438 nsecs_t remainingTimeout = endTime - now();
3439 if (remainingTimeout <= 0) {
3440#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003441 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3442 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443#endif
3444 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3445 break;
3446 }
3447
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003448 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449 }
3450 }
3451 }
3452
3453 injectionState->release();
3454 } // release lock
3455
3456#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003457 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003458 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459#endif
3460
3461 return injectionResult;
3462}
3463
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003464std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003465 std::array<uint8_t, 32> calculatedHmac;
3466 std::unique_ptr<VerifiedInputEvent> result;
3467 switch (event.getType()) {
3468 case AINPUT_EVENT_TYPE_KEY: {
3469 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3470 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3471 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3472 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3473 break;
3474 }
3475 case AINPUT_EVENT_TYPE_MOTION: {
3476 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3477 VerifiedMotionEvent verifiedMotionEvent =
3478 verifiedMotionEventFromMotionEvent(motionEvent);
3479 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3480 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3481 break;
3482 }
3483 default: {
3484 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3485 return nullptr;
3486 }
3487 }
3488 if (calculatedHmac == INVALID_HMAC) {
3489 return nullptr;
3490 }
3491 if (calculatedHmac != event.getHmac()) {
3492 return nullptr;
3493 }
3494 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003495}
3496
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003498 return injectorUid == 0 ||
3499 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500}
3501
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003502void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503 InjectionState* injectionState = entry->injectionState;
3504 if (injectionState) {
3505#if DEBUG_INJECTION
3506 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003507 "injectorPid=%d, injectorUid=%d",
3508 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509#endif
3510
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003511 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 // Log the outcome since the injector did not wait for the injection result.
3513 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003514 case INPUT_EVENT_INJECTION_SUCCEEDED:
3515 ALOGV("Asynchronous input event injection succeeded.");
3516 break;
3517 case INPUT_EVENT_INJECTION_FAILED:
3518 ALOGW("Asynchronous input event injection failed.");
3519 break;
3520 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3521 ALOGW("Asynchronous input event injection permission denied.");
3522 break;
3523 case INPUT_EVENT_INJECTION_TIMED_OUT:
3524 ALOGW("Asynchronous input event injection timed out.");
3525 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 }
3527 }
3528
3529 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003530 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 }
3532}
3533
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003534void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 InjectionState* injectionState = entry->injectionState;
3536 if (injectionState) {
3537 injectionState->pendingForegroundDispatches += 1;
3538 }
3539}
3540
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003541void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 InjectionState* injectionState = entry->injectionState;
3543 if (injectionState) {
3544 injectionState->pendingForegroundDispatches -= 1;
3545
3546 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003547 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548 }
3549 }
3550}
3551
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003552std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3553 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003554 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003555}
3556
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003558 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003559 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003560 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3561 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003562 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003563 return windowHandle;
3564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 }
3566 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003567 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003568}
3569
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003570bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003571 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003572 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3573 for (const sp<InputWindowHandle>& handle : windowHandles) {
3574 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003575 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003576 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003577 ", but it should belong to display %" PRId32,
3578 windowHandle->getName().c_str(), it.first,
3579 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003580 }
3581 return true;
3582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 }
3584 }
3585 return false;
3586}
3587
Robert Carr5c8a0262018-10-03 16:30:44 -07003588sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3589 size_t count = mInputChannelsByToken.count(token);
3590 if (count == 0) {
3591 return nullptr;
3592 }
3593 return mInputChannelsByToken.at(token);
3594}
3595
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003596void InputDispatcher::updateWindowHandlesForDisplayLocked(
3597 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3598 if (inputWindowHandles.empty()) {
3599 // Remove all handles on a display if there are no windows left.
3600 mWindowHandlesByDisplay.erase(displayId);
3601 return;
3602 }
3603
3604 // Since we compare the pointer of input window handles across window updates, we need
3605 // to make sure the handle object for the same window stays unchanged across updates.
3606 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003607 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003608 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003609 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003610 }
3611
3612 std::vector<sp<InputWindowHandle>> newHandles;
3613 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3614 if (!handle->updateInfo()) {
3615 // handle no longer valid
3616 continue;
3617 }
3618
3619 const InputWindowInfo* info = handle->getInfo();
3620 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3621 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3622 const bool noInputChannel =
3623 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3624 const bool canReceiveInput =
3625 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3626 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3627 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003628 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003629 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003630 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003631 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003632 }
3633
3634 if (info->displayId != displayId) {
3635 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3636 handle->getName().c_str(), displayId, info->displayId);
3637 continue;
3638 }
3639
chaviwaf87b3e2019-10-01 16:59:28 -07003640 if (oldHandlesById.find(handle->getId()) != oldHandlesById.end()) {
3641 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003642 oldHandle->updateFrom(handle);
3643 newHandles.push_back(oldHandle);
3644 } else {
3645 newHandles.push_back(handle);
3646 }
3647 }
3648
3649 // Insert or replace
3650 mWindowHandlesByDisplay[displayId] = newHandles;
3651}
3652
Arthur Hung72d8dc32020-03-28 00:48:39 +00003653void InputDispatcher::setInputWindows(
3654 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3655 { // acquire lock
3656 std::scoped_lock _l(mLock);
3657 for (auto const& i : handlesPerDisplay) {
3658 setInputWindowsLocked(i.second, i.first);
3659 }
3660 }
3661 // Wake up poll loop since it may need to make new input dispatching choices.
3662 mLooper->wake();
3663}
3664
Arthur Hungb92218b2018-08-14 12:00:21 +08003665/**
3666 * Called from InputManagerService, update window handle list by displayId that can receive input.
3667 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3668 * If set an empty list, remove all handles from the specific display.
3669 * For focused handle, check if need to change and send a cancel event to previous one.
3670 * For removed handle, check if need to send a cancel event if already in touch.
3671 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003672void InputDispatcher::setInputWindowsLocked(
3673 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003674 if (DEBUG_FOCUS) {
3675 std::string windowList;
3676 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3677 windowList += iwh->getName() + " ";
3678 }
3679 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681
Arthur Hung72d8dc32020-03-28 00:48:39 +00003682 // Copy old handles for release if they are no longer present.
3683 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684
Arthur Hung72d8dc32020-03-28 00:48:39 +00003685 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003686
Arthur Hung72d8dc32020-03-28 00:48:39 +00003687 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3688 bool foundHoveredWindow = false;
3689 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3690 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3691 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3692 windowHandle->getInfo()->visible) {
3693 newFocusedWindowHandle = windowHandle;
3694 }
3695 if (windowHandle == mLastHoverWindowHandle) {
3696 foundHoveredWindow = true;
3697 }
3698 }
3699
3700 if (!foundHoveredWindow) {
3701 mLastHoverWindowHandle = nullptr;
3702 }
3703
3704 sp<InputWindowHandle> oldFocusedWindowHandle =
3705 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3706
3707 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3708 if (oldFocusedWindowHandle != nullptr) {
3709 if (DEBUG_FOCUS) {
3710 ALOGD("Focus left window: %s in display %" PRId32,
3711 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003712 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003713 sp<InputChannel> focusedInputChannel =
3714 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3715 if (focusedInputChannel != nullptr) {
3716 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3717 "focus left window");
3718 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3719 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003720 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003721 mFocusedWindowHandlesByDisplay.erase(displayId);
3722 }
3723 if (newFocusedWindowHandle != nullptr) {
3724 if (DEBUG_FOCUS) {
3725 ALOGD("Focus entered window: %s in display %" PRId32,
3726 newFocusedWindowHandle->getName().c_str(), displayId);
3727 }
3728 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3729 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 }
3731
Arthur Hung72d8dc32020-03-28 00:48:39 +00003732 if (mFocusedDisplayId == displayId) {
3733 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003737 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3738 mTouchStatesByDisplay.find(displayId);
3739 if (stateIt != mTouchStatesByDisplay.end()) {
3740 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003741 for (size_t i = 0; i < state.windows.size();) {
3742 TouchedWindow& touchedWindow = state.windows[i];
3743 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003744 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003745 ALOGD("Touched window was removed: %s in display %" PRId32,
3746 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003747 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003748 sp<InputChannel> touchedInputChannel =
3749 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3750 if (touchedInputChannel != nullptr) {
3751 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3752 "touched window was removed");
3753 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003755 state.windows.erase(state.windows.begin() + i);
3756 } else {
3757 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 }
3759 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003760 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003761
Arthur Hung72d8dc32020-03-28 00:48:39 +00003762 // Release information for windows that are no longer present.
3763 // This ensures that unused input channels are released promptly.
3764 // Otherwise, they might stick around until the window handle is destroyed
3765 // which might not happen until the next GC.
3766 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3767 if (!hasWindowHandleLocked(oldWindowHandle)) {
3768 if (DEBUG_FOCUS) {
3769 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003770 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003771 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003772 }
chaviw291d88a2019-02-14 10:33:58 -08003773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774}
3775
3776void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003777 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003778 if (DEBUG_FOCUS) {
3779 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3780 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003783 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784
Tiger Huang721e26f2018-07-24 22:26:19 +08003785 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3786 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003787 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003788 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3789 if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003790 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003792 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003794 } else if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003795 resetAnrTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003796 oldFocusedApplicationHandle.clear();
3797 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 } // release lock
3800
3801 // Wake up poll loop since it may need to make new input dispatching choices.
3802 mLooper->wake();
3803}
3804
Tiger Huang721e26f2018-07-24 22:26:19 +08003805/**
3806 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3807 * the display not specified.
3808 *
3809 * We track any unreleased events for each window. If a window loses the ability to receive the
3810 * released event, we will send a cancel event to it. So when the focused display is changed, we
3811 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3812 * display. The display-specified events won't be affected.
3813 */
3814void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003815 if (DEBUG_FOCUS) {
3816 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3817 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003818 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003819 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003820
3821 if (mFocusedDisplayId != displayId) {
3822 sp<InputWindowHandle> oldFocusedWindowHandle =
3823 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3824 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003825 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003826 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003827 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003828 CancelationOptions
3829 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3830 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003831 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003832 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3833 }
3834 }
3835 mFocusedDisplayId = displayId;
3836
3837 // Sanity check
3838 sp<InputWindowHandle> newFocusedWindowHandle =
3839 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003840 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003841
Tiger Huang721e26f2018-07-24 22:26:19 +08003842 if (newFocusedWindowHandle == nullptr) {
3843 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3844 if (!mFocusedWindowHandlesByDisplay.empty()) {
3845 ALOGE("But another display has a focused window:");
3846 for (auto& it : mFocusedWindowHandlesByDisplay) {
3847 const int32_t displayId = it.first;
3848 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003849 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3850 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003851 }
3852 }
3853 }
3854 }
3855
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003856 if (DEBUG_FOCUS) {
3857 logDispatchStateLocked();
3858 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003859 } // release lock
3860
3861 // Wake up poll loop since it may need to make new input dispatching choices.
3862 mLooper->wake();
3863}
3864
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003866 if (DEBUG_FOCUS) {
3867 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869
3870 bool changed;
3871 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003872 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873
3874 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3875 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003876 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 }
3878
3879 if (mDispatchEnabled && !enabled) {
3880 resetAndDropEverythingLocked("dispatcher is being disabled");
3881 }
3882
3883 mDispatchEnabled = enabled;
3884 mDispatchFrozen = frozen;
3885 changed = true;
3886 } else {
3887 changed = false;
3888 }
3889
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003890 if (DEBUG_FOCUS) {
3891 logDispatchStateLocked();
3892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 } // release lock
3894
3895 if (changed) {
3896 // Wake up poll loop since it may need to make new input dispatching choices.
3897 mLooper->wake();
3898 }
3899}
3900
3901void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003902 if (DEBUG_FOCUS) {
3903 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905
3906 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003907 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908
3909 if (mInputFilterEnabled == enabled) {
3910 return;
3911 }
3912
3913 mInputFilterEnabled = enabled;
3914 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3915 } // release lock
3916
3917 // Wake up poll loop since there might be work to do to drop everything.
3918 mLooper->wake();
3919}
3920
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003921void InputDispatcher::setInTouchMode(bool inTouchMode) {
3922 std::scoped_lock lock(mLock);
3923 mInTouchMode = inTouchMode;
3924}
3925
chaviwfbe5d9c2018-12-26 12:23:37 -08003926bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3927 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003928 if (DEBUG_FOCUS) {
3929 ALOGD("Trivial transfer to same window.");
3930 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003931 return true;
3932 }
3933
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003935 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936
chaviwfbe5d9c2018-12-26 12:23:37 -08003937 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3938 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003939 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003940 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941 return false;
3942 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003943 if (DEBUG_FOCUS) {
3944 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3945 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003948 if (DEBUG_FOCUS) {
3949 ALOGD("Cannot transfer focus because windows are on different displays.");
3950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 return false;
3952 }
3953
3954 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003955 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
3956 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003957 for (size_t i = 0; i < state.windows.size(); i++) {
3958 const TouchedWindow& touchedWindow = state.windows[i];
3959 if (touchedWindow.windowHandle == fromWindowHandle) {
3960 int32_t oldTargetFlags = touchedWindow.targetFlags;
3961 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003963 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003965 int32_t newTargetFlags = oldTargetFlags &
3966 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3967 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003968 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969
Jeff Brownf086ddb2014-02-11 14:28:48 -08003970 found = true;
3971 goto Found;
3972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 }
3974 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003975 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003977 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003978 if (DEBUG_FOCUS) {
3979 ALOGD("Focus transfer failed because from window did not have focus.");
3980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 return false;
3982 }
3983
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003984 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3985 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003986 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003987 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003988 CancelationOptions
3989 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3990 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003992 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 }
3994
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003995 if (DEBUG_FOCUS) {
3996 logDispatchStateLocked();
3997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998 } // release lock
3999
4000 // Wake up poll loop since it may need to make new input dispatching choices.
4001 mLooper->wake();
4002 return true;
4003}
4004
4005void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004006 if (DEBUG_FOCUS) {
4007 ALOGD("Resetting and dropping all events (%s).", reason);
4008 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009
4010 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4011 synthesizeCancelationEventsForAllConnectionsLocked(options);
4012
4013 resetKeyRepeatLocked();
4014 releasePendingEventLocked();
4015 drainInboundQueueLocked();
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004016 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017
Jeff Brownf086ddb2014-02-11 14:28:48 -08004018 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004020 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021}
4022
4023void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004024 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025 dumpDispatchStateLocked(dump);
4026
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004027 std::istringstream stream(dump);
4028 std::string line;
4029
4030 while (std::getline(stream, line, '\n')) {
4031 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032 }
4033}
4034
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004035void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004036 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4037 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4038 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004039 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004040
Tiger Huang721e26f2018-07-24 22:26:19 +08004041 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4042 dump += StringPrintf(INDENT "FocusedApplications:\n");
4043 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4044 const int32_t displayId = it.first;
4045 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004046 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004047 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004048 displayId, applicationHandle->getName().c_str(),
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004049 ns2ms(applicationHandle
4050 ->getDispatchingTimeout(
4051 DEFAULT_INPUT_DISPATCHING_TIMEOUT)
4052 .count()));
Tiger Huang721e26f2018-07-24 22:26:19 +08004053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004055 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004057
4058 if (!mFocusedWindowHandlesByDisplay.empty()) {
4059 dump += StringPrintf(INDENT "FocusedWindows:\n");
4060 for (auto& it : mFocusedWindowHandlesByDisplay) {
4061 const int32_t displayId = it.first;
4062 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004063 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4064 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004065 }
4066 } else {
4067 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004070 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004071 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004072 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4073 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004074 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004075 state.displayId, toString(state.down), toString(state.split),
4076 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004077 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004078 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004079 for (size_t i = 0; i < state.windows.size(); i++) {
4080 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004081 dump += StringPrintf(INDENT4
4082 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4083 i, touchedWindow.windowHandle->getName().c_str(),
4084 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004085 }
4086 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004087 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004088 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004089 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004090 dump += INDENT3 "Portal windows:\n";
4091 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004092 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004093 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4094 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004095 }
4096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 }
4098 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004099 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 }
4101
Arthur Hungb92218b2018-08-14 12:00:21 +08004102 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004103 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004104 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004105 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004106 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004107 dump += INDENT2 "Windows:\n";
4108 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004109 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004110 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111
Arthur Hungb92218b2018-08-14 12:00:21 +08004112 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004113 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004114 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4115 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004116 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004117 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004118 i, windowInfo->name.c_str(), windowInfo->displayId,
4119 windowInfo->portalToDisplayId,
4120 toString(windowInfo->paused),
4121 toString(windowInfo->hasFocus),
4122 toString(windowInfo->hasWallpaper),
4123 toString(windowInfo->visible),
4124 toString(windowInfo->canReceiveKeys),
4125 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004126 windowInfo->layoutParamsType, windowInfo->frameLeft,
4127 windowInfo->frameTop, windowInfo->frameRight,
4128 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4129 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004130 dumpRegion(dump, windowInfo->touchableRegion);
4131 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004132 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4133 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004134 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004135 ns2ms(windowInfo->dispatchingTimeout));
Siarhei Vishniakou67d44502020-04-09 11:09:29 -07004136 dump += StringPrintf(INDENT4 " flags: %s\n",
4137 inputWindowFlagsToString(windowInfo->layoutParamsFlags)
4138 .c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004139 }
4140 } else {
4141 dump += INDENT2 "Windows: <none>\n";
4142 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143 }
4144 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004145 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 }
4147
Michael Wright3dd60e22019-03-27 22:06:44 +00004148 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004149 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004150 const std::vector<Monitor>& monitors = it.second;
4151 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4152 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004153 }
4154 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004155 const std::vector<Monitor>& monitors = it.second;
4156 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4157 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004160 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 }
4162
4163 nsecs_t currentTime = now();
4164
4165 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004166 if (!mRecentQueue.empty()) {
4167 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4168 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004169 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004171 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 }
4173 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004174 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 }
4176
4177 // Dump event currently being dispatched.
4178 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004179 dump += INDENT "PendingEvent:\n";
4180 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004182 dump += StringPrintf(", age=%" PRId64 "ms\n",
4183 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004185 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 }
4187
4188 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004189 if (!mInboundQueue.empty()) {
4190 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4191 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004192 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004194 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 }
4196 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004197 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 }
4199
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004200 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004201 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004202 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4203 const KeyReplacement& replacement = pair.first;
4204 int32_t newKeyCode = pair.second;
4205 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004206 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004207 }
4208 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004209 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004210 }
4211
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004212 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004213 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004214 for (const auto& pair : mConnectionsByFd) {
4215 const sp<Connection>& connection = pair.second;
4216 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
4217 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
4218 pair.first, connection->getInputChannelName().c_str(),
4219 connection->getWindowName().c_str(), connection->getStatusLabel(),
4220 toString(connection->monitor),
4221 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004223 if (!connection->outboundQueue.empty()) {
4224 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4225 connection->outboundQueue.size());
4226 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 dump.append(INDENT4);
4228 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004229 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4230 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004231 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004232 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 }
4234 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004235 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 }
4237
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004238 if (!connection->waitQueue.empty()) {
4239 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4240 connection->waitQueue.size());
4241 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004242 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004244 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004245 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004247 ns2ms(currentTime - entry->eventEntry->eventTime),
4248 ns2ms(currentTime - entry->deliveryTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 }
4250 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004251 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 }
4253 }
4254 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004255 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 }
4257
4258 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004259 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4260 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004262 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 }
4264
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004265 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004266 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4267 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4268 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269}
4270
Michael Wright3dd60e22019-03-27 22:06:44 +00004271void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4272 const size_t numMonitors = monitors.size();
4273 for (size_t i = 0; i < numMonitors; i++) {
4274 const Monitor& monitor = monitors[i];
4275 const sp<InputChannel>& channel = monitor.inputChannel;
4276 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4277 dump += "\n";
4278 }
4279}
4280
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004281status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004283 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284#endif
4285
4286 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004287 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004288 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004289 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004291 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 return BAD_VALUE;
4293 }
4294
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004295 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296
4297 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004298 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004299 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4302 } // release lock
4303
4304 // Wake the looper because some connections have changed.
4305 mLooper->wake();
4306 return OK;
4307}
4308
Michael Wright3dd60e22019-03-27 22:06:44 +00004309status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004310 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004311 { // acquire lock
4312 std::scoped_lock _l(mLock);
4313
4314 if (displayId < 0) {
4315 ALOGW("Attempted to register input monitor without a specified display.");
4316 return BAD_VALUE;
4317 }
4318
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004319 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004320 ALOGW("Attempted to register input monitor without an identifying token.");
4321 return BAD_VALUE;
4322 }
4323
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004324 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004325
4326 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004327 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004328 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004329
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004330 auto& monitorsByDisplay =
4331 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004332 monitorsByDisplay[displayId].emplace_back(inputChannel);
4333
4334 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004335 }
4336 // Wake the looper because some connections have changed.
4337 mLooper->wake();
4338 return OK;
4339}
4340
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4342#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004343 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344#endif
4345
4346 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004347 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348
4349 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4350 if (status) {
4351 return status;
4352 }
4353 } // release lock
4354
4355 // Wake the poll loop because removing the connection may have changed the current
4356 // synchronization state.
4357 mLooper->wake();
4358 return OK;
4359}
4360
4361status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004362 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004363 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004364 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004366 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 return BAD_VALUE;
4368 }
4369
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004370 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004371 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004372
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 if (connection->monitor) {
4374 removeMonitorChannelLocked(inputChannel);
4375 }
4376
4377 mLooper->removeFd(inputChannel->getFd());
4378
4379 nsecs_t currentTime = now();
4380 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4381
4382 connection->status = Connection::STATUS_ZOMBIE;
4383 return OK;
4384}
4385
4386void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004387 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4388 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4389}
4390
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004391void InputDispatcher::removeMonitorChannelLocked(
4392 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004393 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004394 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004395 std::vector<Monitor>& monitors = it->second;
4396 const size_t numMonitors = monitors.size();
4397 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004398 if (monitors[i].inputChannel == inputChannel) {
4399 monitors.erase(monitors.begin() + i);
4400 break;
4401 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004402 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004403 if (monitors.empty()) {
4404 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004405 } else {
4406 ++it;
4407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 }
4409}
4410
Michael Wright3dd60e22019-03-27 22:06:44 +00004411status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4412 { // acquire lock
4413 std::scoped_lock _l(mLock);
4414 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4415
4416 if (!foundDisplayId) {
4417 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4418 return BAD_VALUE;
4419 }
4420 int32_t displayId = foundDisplayId.value();
4421
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004422 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4423 mTouchStatesByDisplay.find(displayId);
4424 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004425 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4426 return BAD_VALUE;
4427 }
4428
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004429 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004430 std::optional<int32_t> foundDeviceId;
4431 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004432 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004433 foundDeviceId = state.deviceId;
4434 }
4435 }
4436 if (!foundDeviceId || !state.down) {
4437 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004438 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004439 return BAD_VALUE;
4440 }
4441 int32_t deviceId = foundDeviceId.value();
4442
4443 // Send cancel events to all the input channels we're stealing from.
4444 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004445 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004446 options.deviceId = deviceId;
4447 options.displayId = displayId;
4448 for (const TouchedWindow& window : state.windows) {
4449 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004450 if (channel != nullptr) {
4451 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4452 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004453 }
4454 // Then clear the current touch state so we stop dispatching to them as well.
4455 state.filterNonMonitors();
4456 }
4457 return OK;
4458}
4459
Michael Wright3dd60e22019-03-27 22:06:44 +00004460std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4461 const sp<IBinder>& token) {
4462 for (const auto& it : mGestureMonitorsByDisplay) {
4463 const std::vector<Monitor>& monitors = it.second;
4464 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004465 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004466 return it.first;
4467 }
4468 }
4469 }
4470 return std::nullopt;
4471}
4472
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004473sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004474 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004475 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004476 }
4477
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004478 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004479 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004480 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004481 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 }
4483 }
Robert Carr4e670e52018-08-15 13:26:12 -07004484
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004485 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486}
4487
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004488void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
4489 removeByValue(mConnectionsByFd, connection);
4490}
4491
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004492void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4493 const sp<Connection>& connection, uint32_t seq,
4494 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004495 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4496 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497 commandEntry->connection = connection;
4498 commandEntry->eventTime = currentTime;
4499 commandEntry->seq = seq;
4500 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004501 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502}
4503
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004504void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4505 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004507 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004509 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4510 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004512 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513}
4514
chaviw0c06c6e2019-01-09 13:27:07 -08004515void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004516 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004517 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4518 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004519 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4520 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004521 commandEntry->oldToken = oldToken;
4522 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004523 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004524}
4525
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004526void InputDispatcher::onAnrLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004527 const sp<InputApplicationHandle>& applicationHandle,
4528 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4529 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4531 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4532 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004533 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4534 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4535 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536
4537 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004538 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539 struct tm tm;
4540 localtime_r(&t, &tm);
4541 char timestr[64];
4542 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004543 mLastAnrState.clear();
4544 mLastAnrState += INDENT "ANR:\n";
4545 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
4546 mLastAnrState +=
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004547 StringPrintf(INDENT2 "Window: %s\n",
4548 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004549 mLastAnrState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4550 mLastAnrState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4551 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason);
4552 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004554 std::unique_ptr<CommandEntry> commandEntry =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004555 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004557 commandEntry->inputChannel =
4558 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004560 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561}
4562
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004563void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 mLock.unlock();
4565
4566 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4567
4568 mLock.lock();
4569}
4570
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004571void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572 sp<Connection> connection = commandEntry->connection;
4573
4574 if (connection->status != Connection::STATUS_ZOMBIE) {
4575 mLock.unlock();
4576
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004577 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578
4579 mLock.lock();
4580 }
4581}
4582
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004583void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004584 sp<IBinder> oldToken = commandEntry->oldToken;
4585 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004586 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004587 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004588 mLock.lock();
4589}
4590
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004591void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004592 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004593 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594 mLock.unlock();
4595
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004596 const nsecs_t timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004597 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004598
4599 mLock.lock();
4600
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004601 resumeAfterTargetsNotReadyTimeoutLocked(timeoutExtension, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602}
4603
4604void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4605 CommandEntry* commandEntry) {
4606 KeyEntry* entry = commandEntry->keyEntry;
4607
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004608 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609
4610 mLock.unlock();
4611
Michael Wright2b3c3302018-03-02 17:19:13 +00004612 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004613 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004614 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004615 : nullptr;
4616 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004617 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4618 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004619 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621
4622 mLock.lock();
4623
4624 if (delay < 0) {
4625 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4626 } else if (!delay) {
4627 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4628 } else {
4629 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4630 entry->interceptKeyWakeupTime = now() + delay;
4631 }
4632 entry->release();
4633}
4634
chaviwfd6d3512019-03-25 13:23:49 -07004635void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4636 mLock.unlock();
4637 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4638 mLock.lock();
4639}
4640
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004641void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004642 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004643 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004645 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004646
4647 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004648 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004649 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004650 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004652 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004653
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004654 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004655 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004656 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4657 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004658 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004659 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004660
4661 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004662 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004663 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4664 restartEvent =
4665 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004666 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004667 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4668 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4669 handled);
4670 } else {
4671 restartEvent = false;
4672 }
4673
4674 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004675 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004676 // contents of the wait queue to have been drained, so we need to double-check
4677 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004678 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4679 if (dispatchEntryIt != connection->waitQueue.end()) {
4680 dispatchEntry = *dispatchEntryIt;
4681 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004682 traceWaitQueueLength(connection);
4683 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004684 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004685 traceOutboundQueueLength(connection);
4686 } else {
4687 releaseDispatchEntry(dispatchEntry);
4688 }
4689 }
4690
4691 // Start the next dispatch cycle for this connection.
4692 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004693}
4694
4695bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004696 DispatchEntry* dispatchEntry,
4697 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004698 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004699 if (!handled) {
4700 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004701 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004702 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004703 return false;
4704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004706 // Get the fallback key state.
4707 // Clear it out after dispatching the UP.
4708 int32_t originalKeyCode = keyEntry->keyCode;
4709 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4710 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4711 connection->inputState.removeFallbackKey(originalKeyCode);
4712 }
4713
4714 if (handled || !dispatchEntry->hasForegroundTarget()) {
4715 // If the application handles the original key for which we previously
4716 // generated a fallback or if the window is not a foreground window,
4717 // then cancel the associated fallback key, if any.
4718 if (fallbackKeyCode != -1) {
4719 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004721 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004722 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4723 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4724 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004726 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004727 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728
4729 mLock.unlock();
4730
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004731 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004732 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733
4734 mLock.lock();
4735
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004736 // Cancel the fallback key.
4737 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004739 "application handled the original non-fallback key "
4740 "or is no longer a foreground target, "
4741 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742 options.keyCode = fallbackKeyCode;
4743 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004745 connection->inputState.removeFallbackKey(originalKeyCode);
4746 }
4747 } else {
4748 // If the application did not handle a non-fallback key, first check
4749 // that we are in a good state to perform unhandled key event processing
4750 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004751 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004752 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004754 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004755 "since this is not an initial down. "
4756 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4757 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004759 return false;
4760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004761
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004762 // Dispatch the unhandled key to the policy.
4763#if DEBUG_OUTBOUND_EVENT_DETAILS
4764 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004765 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4766 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004767#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004768 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004769
4770 mLock.unlock();
4771
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004772 bool fallback =
4773 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4774 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004775
4776 mLock.lock();
4777
4778 if (connection->status != Connection::STATUS_NORMAL) {
4779 connection->inputState.removeFallbackKey(originalKeyCode);
4780 return false;
4781 }
4782
4783 // Latch the fallback keycode for this key on an initial down.
4784 // The fallback keycode cannot change at any other point in the lifecycle.
4785 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004787 fallbackKeyCode = event.getKeyCode();
4788 } else {
4789 fallbackKeyCode = AKEYCODE_UNKNOWN;
4790 }
4791 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4792 }
4793
4794 ALOG_ASSERT(fallbackKeyCode != -1);
4795
4796 // Cancel the fallback key if the policy decides not to send it anymore.
4797 // We will continue to dispatch the key to the policy but we will no
4798 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004799 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4800 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004801#if DEBUG_OUTBOUND_EVENT_DETAILS
4802 if (fallback) {
4803 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004804 "as a fallback for %d, but on the DOWN it had requested "
4805 "to send %d instead. Fallback canceled.",
4806 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004807 } else {
4808 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004809 "but on the DOWN it had requested to send %d. "
4810 "Fallback canceled.",
4811 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004812 }
4813#endif
4814
4815 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4816 "canceling fallback, policy no longer desires it");
4817 options.keyCode = fallbackKeyCode;
4818 synthesizeCancelationEventsForConnectionLocked(connection, options);
4819
4820 fallback = false;
4821 fallbackKeyCode = AKEYCODE_UNKNOWN;
4822 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004823 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004824 }
4825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826
4827#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004828 {
4829 std::string msg;
4830 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4831 connection->inputState.getFallbackKeys();
4832 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004833 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004835 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004836 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004837 }
4838#endif
4839
4840 if (fallback) {
4841 // Restart the dispatch cycle using the fallback key.
4842 keyEntry->eventTime = event.getEventTime();
4843 keyEntry->deviceId = event.getDeviceId();
4844 keyEntry->source = event.getSource();
4845 keyEntry->displayId = event.getDisplayId();
4846 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4847 keyEntry->keyCode = fallbackKeyCode;
4848 keyEntry->scanCode = event.getScanCode();
4849 keyEntry->metaState = event.getMetaState();
4850 keyEntry->repeatCount = event.getRepeatCount();
4851 keyEntry->downTime = event.getDownTime();
4852 keyEntry->syntheticRepeat = false;
4853
4854#if DEBUG_OUTBOUND_EVENT_DETAILS
4855 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004856 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4857 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004858#endif
4859 return true; // restart the event
4860 } else {
4861#if DEBUG_OUTBOUND_EVENT_DETAILS
4862 ALOGD("Unhandled key event: No fallback key.");
4863#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004864
4865 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004866 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 }
4868 }
4869 return false;
4870}
4871
4872bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004873 DispatchEntry* dispatchEntry,
4874 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 return false;
4876}
4877
4878void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4879 mLock.unlock();
4880
4881 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4882
4883 mLock.lock();
4884}
4885
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004886KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4887 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004888 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004889 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
4890 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004891 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892}
4893
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004894void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
4895 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896 // TODO Write some statistics about how long we spend waiting.
4897}
4898
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004899/**
4900 * Report the touch event latency to the statsd server.
4901 * Input events are reported for statistics if:
4902 * - This is a touchscreen event
4903 * - InputFilter is not enabled
4904 * - Event is not injected or synthesized
4905 *
4906 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4907 * from getting aggregated with the "old" data.
4908 */
4909void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4910 REQUIRES(mLock) {
4911 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4912 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4913 if (!reportForStatistics) {
4914 return;
4915 }
4916
4917 if (mTouchStatistics.shouldReport()) {
4918 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4919 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4920 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4921 mTouchStatistics.reset();
4922 }
4923 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4924 mTouchStatistics.addValue(latencyMicros);
4925}
4926
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927void InputDispatcher::traceInboundQueueLengthLocked() {
4928 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004929 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930 }
4931}
4932
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004933void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934 if (ATRACE_ENABLED()) {
4935 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004936 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004937 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938 }
4939}
4940
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004941void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942 if (ATRACE_ENABLED()) {
4943 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004944 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004945 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946 }
4947}
4948
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004949void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004950 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004952 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953 dumpDispatchStateLocked(dump);
4954
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004955 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004956 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004957 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958 }
4959}
4960
4961void InputDispatcher::monitor() {
4962 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004963 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004965 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004966}
4967
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004968/**
4969 * Wake up the dispatcher and wait until it processes all events and commands.
4970 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4971 * this method can be safely called from any thread, as long as you've ensured that
4972 * the work you are interested in completing has already been queued.
4973 */
4974bool InputDispatcher::waitForIdle() {
4975 /**
4976 * Timeout should represent the longest possible time that a device might spend processing
4977 * events and commands.
4978 */
4979 constexpr std::chrono::duration TIMEOUT = 100ms;
4980 std::unique_lock lock(mLock);
4981 mLooper->wake();
4982 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4983 return result == std::cv_status::no_timeout;
4984}
4985
Garfield Tane84e6f92019-08-29 17:28:41 -07004986} // namespace android::inputdispatcher