blob: 2bc198c1bf8e3d4600f959e413e851676d006a50 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Garfield Tane84e6f92019-08-29 17:28:41 -070048#include "Connection.h"
49
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <errno.h>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080051#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <limits.h>
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -050053#include <statslog.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080055#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056#include <unistd.h>
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -070057#include <queue>
58#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070059
Michael Wright2b3c3302018-03-02 17:19:13 +000060#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070062#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080063#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <log/log.h>
Gang Wang342c9272020-01-13 13:15:04 -050065#include <openssl/hmac.h>
66#include <openssl/rand.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070067#include <powermanager/PowerManager.h>
68#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080069
70#define INDENT " "
71#define INDENT2 " "
72#define INDENT3 " "
73#define INDENT4 " "
74
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080075using android::base::StringPrintf;
76
Garfield Tane84e6f92019-08-29 17:28:41 -070077namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
79// Default input dispatching timeout if there is no focused application or paused window
80// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -070081constexpr std::chrono::nanoseconds DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5s;
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Amount of time to allow for all pending events to be processed when an app switch
84// key is on the way. This is used to preempt input dispatch and drop input events
85// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000086constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow for an event to be dispatched (measured since its eventTime)
89// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92// Amount of time to allow touch events to be streamed out to a connection before requiring
93// that the first event be finished. This value extends the ANR timeout by the specified
94// amount. For example, if streaming is allowed to get ahead by one second relative to the
95// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000096constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
98// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000099constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
100
101// Log a warning when an interception call takes longer than this to process.
102constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
104// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107static inline nsecs_t now() {
108 return systemTime(SYSTEM_TIME_MONOTONIC);
109}
110
111static inline const char* toString(bool value) {
112 return value ? "true" : "false";
113}
114
115static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700116 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
117 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118}
119
120static bool isValidKeyAction(int32_t action) {
121 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700122 case AKEY_EVENT_ACTION_DOWN:
123 case AKEY_EVENT_ACTION_UP:
124 return true;
125 default:
126 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127 }
128}
129
130static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 ALOGE("Key event has invalid action code 0x%x", action);
133 return false;
134 }
135 return true;
136}
137
Michael Wright7b159c92015-05-14 14:48:03 +0100138static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 case AMOTION_EVENT_ACTION_DOWN:
141 case AMOTION_EVENT_ACTION_UP:
142 case AMOTION_EVENT_ACTION_CANCEL:
143 case AMOTION_EVENT_ACTION_MOVE:
144 case AMOTION_EVENT_ACTION_OUTSIDE:
145 case AMOTION_EVENT_ACTION_HOVER_ENTER:
146 case AMOTION_EVENT_ACTION_HOVER_MOVE:
147 case AMOTION_EVENT_ACTION_HOVER_EXIT:
148 case AMOTION_EVENT_ACTION_SCROLL:
149 return true;
150 case AMOTION_EVENT_ACTION_POINTER_DOWN:
151 case AMOTION_EVENT_ACTION_POINTER_UP: {
152 int32_t index = getMotionEventActionPointerIndex(action);
153 return index >= 0 && index < pointerCount;
154 }
155 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
156 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
157 return actionButton != 0;
158 default:
159 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160 }
161}
162
Michael Wright7b159c92015-05-14 14:48:03 +0100163static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 const PointerProperties* pointerProperties) {
165 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 ALOGE("Motion event has invalid action code 0x%x", action);
167 return false;
168 }
169 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000170 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700171 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 return false;
173 }
174 BitSet32 pointerIdBits;
175 for (size_t i = 0; i < pointerCount; i++) {
176 int32_t id = pointerProperties[i].id;
177 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
179 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 return false;
181 }
182 if (pointerIdBits.hasBit(id)) {
183 ALOGE("Motion event has duplicate pointer id %d", id);
184 return false;
185 }
186 pointerIdBits.markBit(id);
187 }
188 return true;
189}
190
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800191static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800193 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 return;
195 }
196
197 bool first = true;
198 Region::const_iterator cur = region.begin();
199 Region::const_iterator const tail = region.end();
200 while (cur != tail) {
201 if (first) {
202 first = false;
203 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800204 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800206 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 cur++;
208 }
209}
210
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700211/**
212 * Find the entry in std::unordered_map by key, and return it.
213 * If the entry is not found, return a default constructed entry.
214 *
215 * Useful when the entries are vectors, since an empty vector will be returned
216 * if the entry is not found.
217 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
218 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700219template <typename K, typename V>
220static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700221 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700222 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800223}
224
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700225/**
226 * Find the entry in std::unordered_map by value, and remove it.
227 * If more than one entry has the same value, then all matching
228 * key-value pairs will be removed.
229 *
230 * Return true if at least one value has been removed.
231 */
232template <typename K, typename V>
233static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
234 bool removed = false;
235 for (auto it = map.begin(); it != map.end();) {
236 if (it->second == value) {
237 it = map.erase(it);
238 removed = true;
239 } else {
240 it++;
241 }
242 }
243 return removed;
244}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245
chaviwaf87b3e2019-10-01 16:59:28 -0700246static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
247 if (first == second) {
248 return true;
249 }
250
251 if (first == nullptr || second == nullptr) {
252 return false;
253 }
254
255 return first->getToken() == second->getToken();
256}
257
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800258static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
259 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
260}
261
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000262static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
263 EventEntry* eventEntry,
264 int32_t inputTargetFlags) {
265 if (inputTarget.useDefaultPointerInfo()) {
266 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
267 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
268 inputTargetFlags, pointerInfo.xOffset,
269 pointerInfo.yOffset, inputTarget.globalScaleFactor,
270 pointerInfo.windowXScale, pointerInfo.windowYScale);
271 }
272
273 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
274 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
275
276 PointerCoords pointerCoords[motionEntry.pointerCount];
277
278 // Use the first pointer information to normalize all other pointers. This could be any pointer
279 // as long as all other pointers are normalized to the same value and the final DispatchEntry
280 // uses the offset and scale for the normalized pointer.
281 const PointerInfo& firstPointerInfo =
282 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
283
284 // Iterate through all pointers in the event to normalize against the first.
285 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
286 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
287 uint32_t pointerId = uint32_t(pointerProperties.id);
288 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
289
290 // The scale factor is the ratio of the current pointers scale to the normalized scale.
291 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
292 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
293
294 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
295 // First apply the current pointers offset to set the window at 0,0
296 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
297 // Next scale the coordinates.
298 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
299 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
300 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
301 -firstPointerInfo.yOffset);
302 }
303
304 MotionEntry* combinedMotionEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800305 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000306 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
307 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
308 motionEntry.metaState, motionEntry.buttonState,
309 motionEntry.classification, motionEntry.edgeFlags,
310 motionEntry.xPrecision, motionEntry.yPrecision,
311 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
312 motionEntry.downTime, motionEntry.pointerCount,
313 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
314 0 /* yOffset */);
315
316 if (motionEntry.injectionState) {
317 combinedMotionEntry->injectionState = motionEntry.injectionState;
318 combinedMotionEntry->injectionState->refCount += 1;
319 }
320
321 std::unique_ptr<DispatchEntry> dispatchEntry =
322 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
323 inputTargetFlags, firstPointerInfo.xOffset,
324 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
325 firstPointerInfo.windowXScale,
326 firstPointerInfo.windowYScale);
327 combinedMotionEntry->release();
328 return dispatchEntry;
329}
330
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -0700331static void addGestureMonitors(const std::vector<Monitor>& monitors,
332 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
333 float yOffset = 0) {
334 if (monitors.empty()) {
335 return;
336 }
337 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
338 for (const Monitor& monitor : monitors) {
339 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
340 }
341}
342
Gang Wang342c9272020-01-13 13:15:04 -0500343static std::array<uint8_t, 128> getRandomKey() {
344 std::array<uint8_t, 128> key;
345 if (RAND_bytes(key.data(), key.size()) != 1) {
346 LOG_ALWAYS_FATAL("Can't generate HMAC key");
347 }
348 return key;
349}
350
351// --- HmacKeyManager ---
352
353HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
354
355std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
356 size_t size;
357 switch (event.type) {
358 case VerifiedInputEvent::Type::KEY: {
359 size = sizeof(VerifiedKeyEvent);
360 break;
361 }
362 case VerifiedInputEvent::Type::MOTION: {
363 size = sizeof(VerifiedMotionEvent);
364 break;
365 }
366 }
Gang Wang342c9272020-01-13 13:15:04 -0500367 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700368 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500369}
370
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700371std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500372 // SHA256 always generates 32-bytes result
373 std::array<uint8_t, 32> hash;
374 unsigned int hashLen = 0;
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700375 uint8_t* result =
376 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500377 if (result == nullptr) {
378 ALOGE("Could not sign the data using HMAC");
379 return INVALID_HMAC;
380 }
381
382 if (hashLen != hash.size()) {
383 ALOGE("HMAC-SHA256 has unexpected length");
384 return INVALID_HMAC;
385 }
386
387 return hash;
388}
389
Michael Wrightd02c5b62014-02-10 15:10:22 -0800390// --- InputDispatcher ---
391
Garfield Tan00f511d2019-06-12 16:55:40 -0700392InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
393 : mPolicy(policy),
394 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700395 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tan1c7bc862020-01-28 13:24:04 -0800396 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700397 mAppSwitchSawKeyDown(false),
398 mAppSwitchDueTime(LONG_LONG_MAX),
399 mNextUnblockedEvent(nullptr),
400 mDispatchEnabled(false),
401 mDispatchFrozen(false),
402 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800403 // mInTouchMode will be initialized by the WindowManager to the default device config.
404 // To avoid leaking stack in case that call never comes, and for tests,
405 // initialize it here anyways.
406 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700407 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
408 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800410 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411
Yi Kong9b14ac62018-07-17 13:48:38 -0700412 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413
414 policy->getDispatcherConfiguration(&mConfig);
415}
416
417InputDispatcher::~InputDispatcher() {
418 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800419 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800420
421 resetKeyRepeatLocked();
422 releasePendingEventLocked();
423 drainInboundQueueLocked();
424 }
425
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700426 while (!mConnectionsByFd.empty()) {
427 sp<Connection> connection = mConnectionsByFd.begin()->second;
428 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800429 }
430}
431
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700432status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700433 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700434 return ALREADY_EXISTS;
435 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700436 mThread = std::make_unique<InputThread>(
437 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
438 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700439}
440
441status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700442 if (mThread && mThread->isCallingThread()) {
443 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700444 return INVALID_OPERATION;
445 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700446 mThread.reset();
447 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700448}
449
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450void InputDispatcher::dispatchOnce() {
451 nsecs_t nextWakeupTime = LONG_LONG_MAX;
452 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800453 std::scoped_lock _l(mLock);
454 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455
456 // Run a dispatch loop if there are no pending commands.
457 // The dispatch loop might enqueue commands to run afterwards.
458 if (!haveCommandsLocked()) {
459 dispatchOnceInnerLocked(&nextWakeupTime);
460 }
461
462 // Run all pending commands if there are any.
463 // If any commands were run then force the next poll to wake up immediately.
464 if (runCommandsLockedInterruptible()) {
465 nextWakeupTime = LONG_LONG_MIN;
466 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800467
468 // We are about to enter an infinitely long sleep, because we have no commands or
469 // pending or queued events
470 if (nextWakeupTime == LONG_LONG_MAX) {
471 mDispatcherEnteredIdle.notify_all();
472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800473 } // release lock
474
475 // Wait for callback or timeout or wake. (make sure we round up, not down)
476 nsecs_t currentTime = now();
477 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
478 mLooper->pollOnce(timeoutMillis);
479}
480
481void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
482 nsecs_t currentTime = now();
483
Jeff Browndc5992e2014-04-11 01:27:26 -0700484 // Reset the key repeat timer whenever normal dispatch is suspended while the
485 // device is in a non-interactive state. This is to ensure that we abort a key
486 // repeat if the device is just coming out of sleep.
487 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488 resetKeyRepeatLocked();
489 }
490
491 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
492 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100493 if (DEBUG_FOCUS) {
494 ALOGD("Dispatch frozen. Waiting some more.");
495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496 return;
497 }
498
499 // Optimize latency of app switches.
500 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
501 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
502 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
503 if (mAppSwitchDueTime < *nextWakeupTime) {
504 *nextWakeupTime = mAppSwitchDueTime;
505 }
506
507 // Ready to start a new event.
508 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700509 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700510 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 if (isAppSwitchDue) {
512 // The inbound queue is empty so the app switch key we were waiting
513 // for will never arrive. Stop waiting for it.
514 resetPendingAppSwitchLocked(false);
515 isAppSwitchDue = false;
516 }
517
518 // Synthesize a key repeat if appropriate.
519 if (mKeyRepeatState.lastKeyEntry) {
520 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
521 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
522 } else {
523 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
524 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
525 }
526 }
527 }
528
529 // Nothing to do if there is no pending event.
530 if (!mPendingEvent) {
531 return;
532 }
533 } else {
534 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700535 mPendingEvent = mInboundQueue.front();
536 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537 traceInboundQueueLengthLocked();
538 }
539
540 // Poke user activity for this event.
541 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700542 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 }
544
545 // Get ready to dispatch the event.
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700546 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547 }
548
549 // Now we have an event to dispatch.
550 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700551 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700553 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700555 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700557 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 }
559
560 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700561 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 }
563
564 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700565 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700566 ConfigurationChangedEntry* typedEntry =
567 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
568 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700569 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700570 break;
571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700573 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700574 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
575 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700576 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700577 break;
578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100580 case EventEntry::Type::FOCUS: {
581 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
582 dispatchFocusLocked(currentTime, typedEntry);
583 done = true;
584 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
585 break;
586 }
587
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700588 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700589 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
590 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700591 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700592 resetPendingAppSwitchLocked(true);
593 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700594 } else if (dropReason == DropReason::NOT_DROPPED) {
595 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700596 }
597 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700598 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700599 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700600 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700601 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
602 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700603 }
604 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
605 break;
606 }
607
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700608 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700609 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700610 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
611 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700613 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700614 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700615 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700616 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
617 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700618 }
619 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
620 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 }
623
624 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700625 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700626 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 }
Michael Wright3a981722015-06-10 15:26:13 +0100628 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629
630 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700631 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 }
633}
634
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700635/**
636 * Return true if the events preceding this incoming motion event should be dropped
637 * Return false otherwise (the default behaviour)
638 */
639bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
640 bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
641 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
642 if (isPointerDownEvent &&
643 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
644 mInputTargetWaitApplicationToken != nullptr) {
645 int32_t displayId = motionEntry.displayId;
646 int32_t x = static_cast<int32_t>(
647 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
648 int32_t y = static_cast<int32_t>(
649 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
650 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
651 if (touchedWindowHandle != nullptr &&
652 touchedWindowHandle->getApplicationToken() != mInputTargetWaitApplicationToken) {
653 // User touched a different application than the one we are waiting on.
654 // Flag the event, and start pruning the input queue.
655 ALOGI("Pruning input queue because user touched a different application");
656 return true;
657 }
658 }
659 return false;
660}
661
Michael Wrightd02c5b62014-02-10 15:10:22 -0800662bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700663 bool needWake = mInboundQueue.empty();
664 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665 traceInboundQueueLengthLocked();
666
667 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700668 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700669 // Optimize app switch latency.
670 // If the application takes too long to catch up then we drop all events preceding
671 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700672 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700673 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700674 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700675 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700676 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700677 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700679 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700681 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700682 mAppSwitchSawKeyDown = false;
683 needWake = true;
684 }
685 }
686 }
687 break;
688 }
689
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700690 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700691 // Optimize case where the current application is unresponsive and the user
692 // decides to touch a window in a different application.
693 // If the application takes too long to catch up then we drop all events preceding
694 // the touch into the other window.
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700695 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
696 mNextUnblockedEvent = entry;
697 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700699 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100701 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700702 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
703 break;
704 }
705 case EventEntry::Type::CONFIGURATION_CHANGED:
706 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700707 // nothing to do
708 break;
709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710 }
711
712 return needWake;
713}
714
715void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
716 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700717 mRecentQueue.push_back(entry);
718 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
719 mRecentQueue.front()->release();
720 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800721 }
722}
723
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700724sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
725 int32_t y, bool addOutsideTargets,
726 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800728 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
729 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 const InputWindowInfo* windowInfo = windowHandle->getInfo();
731 if (windowInfo->displayId == displayId) {
732 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733
734 if (windowInfo->visible) {
735 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700736 bool isTouchModal = (flags &
737 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
738 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800740 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700741 if (portalToDisplayId != ADISPLAY_ID_NONE &&
742 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800743 if (addPortalWindows) {
744 // For the monitoring channels of the display.
745 mTempTouchState.addPortalWindow(windowHandle);
746 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700747 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
748 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 // Found window.
751 return windowHandle;
752 }
753 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800754
755 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700756 mTempTouchState.addOrUpdateWindow(windowHandle,
757 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
758 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800759 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800761 }
762 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700763 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764}
765
Garfield Tane84e6f92019-08-29 17:28:41 -0700766std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -0700767 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000768 std::vector<TouchedMonitor> touchedMonitors;
769
770 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
771 addGestureMonitors(monitors, touchedMonitors);
772 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
773 const InputWindowInfo* windowInfo = portalWindow->getInfo();
774 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700775 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
776 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000777 }
778 return touchedMonitors;
779}
780
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700781void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 const char* reason;
783 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700784 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700786 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700788 reason = "inbound event was dropped because the policy consumed it";
789 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700790 case DropReason::DISABLED:
791 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700792 ALOGI("Dropped event because input dispatch is disabled.");
793 }
794 reason = "inbound event was dropped because input dispatch is disabled";
795 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700796 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700797 ALOGI("Dropped event because of pending overdue app switch.");
798 reason = "inbound event was dropped because of pending overdue app switch";
799 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700800 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700801 ALOGI("Dropped event because the current application is not responding and the user "
802 "has started interacting with a different application.");
803 reason = "inbound event was dropped because the current application is not responding "
804 "and the user has started interacting with a different application";
805 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700806 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700807 ALOGI("Dropped event because it is stale.");
808 reason = "inbound event was dropped because it is stale";
809 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700810 case DropReason::NOT_DROPPED: {
811 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 }
815
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700816 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700817 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
819 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700820 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700822 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700823 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
824 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700825 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
826 synthesizeCancelationEventsForAllConnectionsLocked(options);
827 } else {
828 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
829 synthesizeCancelationEventsForAllConnectionsLocked(options);
830 }
831 break;
832 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100833 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700834 case EventEntry::Type::CONFIGURATION_CHANGED:
835 case EventEntry::Type::DEVICE_RESET: {
836 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
837 break;
838 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 }
840}
841
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800842static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700843 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
844 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845}
846
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700847bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
848 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
849 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
850 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851}
852
853bool InputDispatcher::isAppSwitchPendingLocked() {
854 return mAppSwitchDueTime != LONG_LONG_MAX;
855}
856
857void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
858 mAppSwitchDueTime = LONG_LONG_MAX;
859
860#if DEBUG_APP_SWITCH
861 if (handled) {
862 ALOGD("App switch has arrived.");
863 } else {
864 ALOGD("App switch was abandoned.");
865 }
866#endif
867}
868
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700870 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871}
872
873bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700874 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 return false;
876 }
877
878 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700879 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700880 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700882 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883
884 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700885 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 return true;
887}
888
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700889void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
890 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891}
892
893void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700894 while (!mInboundQueue.empty()) {
895 EventEntry* entry = mInboundQueue.front();
896 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 releaseInboundEventLocked(entry);
898 }
899 traceInboundQueueLengthLocked();
900}
901
902void InputDispatcher::releasePendingEventLocked() {
903 if (mPendingEvent) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700904 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700906 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 }
908}
909
910void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
911 InjectionState* injectionState = entry->injectionState;
912 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
913#if DEBUG_DISPATCH_CYCLE
914 ALOGD("Injected inbound event was dropped.");
915#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800916 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917 }
918 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700919 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 }
921 addRecentEventLocked(entry);
922 entry->release();
923}
924
925void InputDispatcher::resetKeyRepeatLocked() {
926 if (mKeyRepeatState.lastKeyEntry) {
927 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700928 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 }
930}
931
Garfield Tane84e6f92019-08-29 17:28:41 -0700932KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
934
935 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700936 uint32_t policyFlags = entry->policyFlags &
937 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 if (entry->refCount == 1) {
939 entry->recycle();
Garfield Tan1c7bc862020-01-28 13:24:04 -0800940 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941 entry->eventTime = currentTime;
942 entry->policyFlags = policyFlags;
943 entry->repeatCount += 1;
944 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700945 KeyEntry* newEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -0800946 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800947 entry->displayId, policyFlags, entry->action, entry->flags,
948 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700949 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950
951 mKeyRepeatState.lastKeyEntry = newEntry;
952 entry->release();
953
954 entry = newEntry;
955 }
956 entry->syntheticRepeat = true;
957
958 // Increment reference count since we keep a reference to the event in
959 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
960 entry->refCount += 1;
961
962 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
963 return entry;
964}
965
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700966bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
967 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700969 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970#endif
971
972 // Reset key repeating in case a keyboard device was added or removed or something.
973 resetKeyRepeatLocked();
974
975 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700976 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
977 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700979 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980 return true;
981}
982
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700983bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700985 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987#endif
988
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 options.deviceId = entry->deviceId;
991 synthesizeCancelationEventsForAllConnectionsLocked(options);
992 return true;
993}
994
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100995void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700996 if (mPendingEvent != nullptr) {
997 // Move the pending event to the front of the queue. This will give the chance
998 // for the pending event to get dispatched to the newly focused window
999 mInboundQueue.push_front(mPendingEvent);
1000 mPendingEvent = nullptr;
1001 }
1002
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001003 FocusEntry* focusEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08001004 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07001005
1006 // This event should go to the front of the queue, but behind all other focus events
1007 // Find the last focus event, and insert right after it
1008 std::deque<EventEntry*>::reverse_iterator it =
1009 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1010 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1011
1012 // Maintain the order of focus events. Insert the entry after all other focus events.
1013 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001014}
1015
1016void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1017 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1018 if (channel == nullptr) {
1019 return; // Window has gone away
1020 }
1021 InputTarget target;
1022 target.inputChannel = channel;
1023 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1024 entry->dispatchInProgress = true;
1025
1026 dispatchEventLocked(currentTime, entry, {target});
1027}
1028
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001032 if (!entry->dispatchInProgress) {
1033 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1034 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1035 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1036 if (mKeyRepeatState.lastKeyEntry &&
1037 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 // We have seen two identical key downs in a row which indicates that the device
1039 // driver is automatically generating key repeats itself. We take note of the
1040 // repeat here, but we disable our own next key repeat timer since it is clear that
1041 // we will not need to synthesize key repeats ourselves.
1042 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1043 resetKeyRepeatLocked();
1044 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1045 } else {
1046 // Not a repeat. Save key down state in case we do see a repeat later.
1047 resetKeyRepeatLocked();
1048 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1049 }
1050 mKeyRepeatState.lastKeyEntry = entry;
1051 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 resetKeyRepeatLocked();
1054 }
1055
1056 if (entry->repeatCount == 1) {
1057 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1058 } else {
1059 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1060 }
1061
1062 entry->dispatchInProgress = true;
1063
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001064 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 }
1066
1067 // Handle case where the policy asked us to try again later last time.
1068 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1069 if (currentTime < entry->interceptKeyWakeupTime) {
1070 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1071 *nextWakeupTime = entry->interceptKeyWakeupTime;
1072 }
1073 return false; // wait until next wakeup
1074 }
1075 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1076 entry->interceptKeyWakeupTime = 0;
1077 }
1078
1079 // Give the policy a chance to intercept the key.
1080 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1081 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001082 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001083 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001084 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001085 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001086 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001087 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 }
1089 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001090 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 entry->refCount += 1;
1092 return false; // wait for the command to run
1093 } else {
1094 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1095 }
1096 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001097 if (*dropReason == DropReason::NOT_DROPPED) {
1098 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 }
1100 }
1101
1102 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001103 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001105 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001106 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001107 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108 return true;
1109 }
1110
1111 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001112 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001113 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001114 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1116 return false;
1117 }
1118
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001119 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1121 return true;
1122 }
1123
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001124 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001125 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126
1127 // Dispatch the key.
1128 dispatchEventLocked(currentTime, entry, inputTargets);
1129 return true;
1130}
1131
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001132void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001134 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001135 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1136 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001137 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1138 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1139 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140#endif
1141}
1142
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001143bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1144 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001145 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001147 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 entry->dispatchInProgress = true;
1149
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001150 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 }
1152
1153 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001154 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001155 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001156 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001157 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 return true;
1159 }
1160
1161 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1162
1163 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001164 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165
1166 bool conflictingPointerActions = false;
1167 int32_t injectionResult;
1168 if (isPointerEvent) {
1169 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001170 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001171 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001172 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 } else {
1174 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001175 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001176 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 }
1178 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1179 return false;
1180 }
1181
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001182 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001183 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1184 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1185 return true;
1186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001188 CancelationOptions::Mode mode(isPointerEvent
1189 ? CancelationOptions::CANCEL_POINTER_EVENTS
1190 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1191 CancelationOptions options(mode, "input event injection failed");
1192 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 return true;
1194 }
1195
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001196 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001197 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001199 if (isPointerEvent) {
1200 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
1201 if (stateIndex >= 0) {
1202 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001203 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001204 // The event has gone through these portal windows, so we add monitoring targets of
1205 // the corresponding displays as well.
1206 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001207 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001208 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001209 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001210 }
1211 }
1212 }
1213 }
1214
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 // Dispatch the motion.
1216 if (conflictingPointerActions) {
1217 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001218 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 synthesizeCancelationEventsForAllConnectionsLocked(options);
1220 }
1221 dispatchEventLocked(currentTime, entry, inputTargets);
1222 return true;
1223}
1224
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001225void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001227 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001228 ", policyFlags=0x%x, "
1229 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1230 "metaState=0x%x, buttonState=0x%x,"
1231 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001232 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1233 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1234 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001236 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001238 "x=%f, y=%f, pressure=%f, size=%f, "
1239 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1240 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001241 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1242 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1243 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1244 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1245 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1246 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1247 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1248 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1249 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1250 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 }
1252#endif
1253}
1254
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001255void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1256 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001257 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258#if DEBUG_DISPATCH_CYCLE
1259 ALOGD("dispatchEventToCurrentInputTargets");
1260#endif
1261
1262 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1263
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001264 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001266 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001267 sp<Connection> connection =
1268 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001269 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001270 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001272 if (DEBUG_FOCUS) {
1273 ALOGD("Dropping event delivery to target with channel '%s' because it "
1274 "is no longer registered with the input dispatcher.",
1275 inputTarget.inputChannel->getName().c_str());
1276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 }
1278 }
1279}
1280
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001281int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001282 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001284 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001285 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001287 if (DEBUG_FOCUS) {
1288 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1291 mInputTargetWaitStartTime = currentTime;
1292 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1293 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001294 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 }
1296 } else {
1297 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001298 ALOGI("Waiting for application to become ready for input: %s. Reason: %s",
1299 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
1300 std::chrono::nanoseconds timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001301 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001303 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001304 timeout =
1305 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 } else {
1307 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1308 }
1309
1310 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1311 mInputTargetWaitStartTime = currentTime;
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001312 mInputTargetWaitTimeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001314 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315
Yi Kong9b14ac62018-07-17 13:48:38 -07001316 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001317 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 }
Robert Carr740167f2018-10-11 19:03:41 -07001319 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1320 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 }
1322 }
1323 }
1324
1325 if (mInputTargetWaitTimeoutExpired) {
1326 return INPUT_EVENT_INJECTION_TIMED_OUT;
1327 }
1328
1329 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001330 onAnrLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001331 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332
1333 // Force poll loop to wake up immediately on next iteration once we get the
1334 // ANR response back from the policy.
1335 *nextWakeupTime = LONG_LONG_MIN;
1336 return INPUT_EVENT_INJECTION_PENDING;
1337 } else {
1338 // Force poll loop to wake up when timeout is due.
1339 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1340 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1341 }
1342 return INPUT_EVENT_INJECTION_PENDING;
1343 }
1344}
1345
Robert Carr803535b2018-08-02 16:38:15 -07001346void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1347 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1348 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1349 state.removeWindowByToken(token);
1350 }
1351}
1352
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001353void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001354 nsecs_t timeoutExtension, const sp<IBinder>& inputConnectionToken) {
1355 if (timeoutExtension > 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356 // Extend the timeout.
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07001357 mInputTargetWaitTimeoutTime = now() + timeoutExtension;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 } else {
1359 // Give up.
1360 mInputTargetWaitTimeoutExpired = true;
1361
1362 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001363 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001364 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001365 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001367 if (connection->status == Connection::STATUS_NORMAL) {
1368 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1369 "application not responding");
1370 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371 }
1372 }
1373 }
1374}
1375
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001376void InputDispatcher::resetAnrTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001377 if (DEBUG_FOCUS) {
1378 ALOGD("Resetting ANR timeouts.");
1379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380
1381 // Reset input target wait timeout.
1382 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001383 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384}
1385
Tiger Huang721e26f2018-07-24 22:26:19 +08001386/**
1387 * Get the display id that the given event should go to. If this event specifies a valid display id,
1388 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1389 * Focused display is the display that the user most recently interacted with.
1390 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001391int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001392 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001393 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001394 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001395 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1396 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001397 break;
1398 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001399 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1401 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001402 break;
1403 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001404 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001405 case EventEntry::Type::CONFIGURATION_CHANGED:
1406 case EventEntry::Type::DEVICE_RESET: {
1407 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001408 return ADISPLAY_ID_NONE;
1409 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001410 }
1411 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1412}
1413
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001415 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001416 std::vector<InputTarget>& inputTargets,
1417 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001418 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419
Tiger Huang721e26f2018-07-24 22:26:19 +08001420 int32_t displayId = getTargetDisplayId(entry);
1421 sp<InputWindowHandle> focusedWindowHandle =
1422 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1423 sp<InputApplicationHandle> focusedApplicationHandle =
1424 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1425
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426 // If there is no currently focused window and no focused application
1427 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001428 if (focusedWindowHandle == nullptr) {
1429 if (focusedApplicationHandle != nullptr) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001430 return handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1431 nullptr, nextWakeupTime,
1432 "Waiting because no window has focus but there is "
1433 "a focused application that may eventually add a "
1434 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 }
1436
Arthur Hung3b413f22018-10-26 18:05:34 +08001437 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001438 "%" PRId32 ".",
1439 displayId);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001440 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441 }
1442
1443 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001444 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001445 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 }
1447
Jeff Brownffb49772014-10-10 19:01:34 -07001448 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001449 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001450 if (!reason.empty()) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001451 return handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1452 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 }
1454
1455 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001456 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001457 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1458 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459
1460 // Done.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001461 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462}
1463
1464int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001465 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001466 std::vector<InputTarget>& inputTargets,
1467 nsecs_t* nextWakeupTime,
1468 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001469 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 enum InjectionPermission {
1471 INJECTION_PERMISSION_UNKNOWN,
1472 INJECTION_PERMISSION_GRANTED,
1473 INJECTION_PERMISSION_DENIED
1474 };
1475
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 // For security reasons, we defer updating the touch state until we are sure that
1477 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001478 int32_t displayId = entry.displayId;
1479 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1481
1482 // Update the touch state as needed based on the properties of the touch event.
1483 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1484 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1485 sp<InputWindowHandle> newHoverWindowHandle;
1486
Jeff Brownf086ddb2014-02-11 14:28:48 -08001487 // Copy current touch state into mTempTouchState.
1488 // This state is always reset at the end of this function, so if we don't find state
1489 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001490 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001491 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1492 if (oldStateIndex >= 0) {
1493 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1494 mTempTouchState.copyFrom(*oldState);
1495 }
1496
1497 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001498 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001499 (mTempTouchState.deviceId != entry.deviceId || mTempTouchState.source != entry.source ||
1500 mTempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001501 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1502 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1503 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1504 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1505 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001506 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 bool wrongDevice = false;
1508 if (newGesture) {
1509 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001510 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001511 ALOGI("Dropping event because a pointer for a different device is already down "
1512 "in display %" PRId32,
1513 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001514 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1516 switchedDevice = false;
1517 wrongDevice = true;
1518 goto Failed;
1519 }
1520 mTempTouchState.reset();
1521 mTempTouchState.down = down;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001522 mTempTouchState.deviceId = entry.deviceId;
1523 mTempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 mTempTouchState.displayId = displayId;
1525 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001526 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001527 ALOGI("Dropping move event because a pointer for a different device is already active "
1528 "in display %" PRId32,
1529 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001530 // TODO: test multiple simultaneous input streams.
1531 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1532 switchedDevice = false;
1533 wrongDevice = true;
1534 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535 }
1536
1537 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1538 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1539
Garfield Tan00f511d2019-06-12 16:55:40 -07001540 int32_t x;
1541 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001543 // Always dispatch mouse events to cursor position.
1544 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001545 x = int32_t(entry.xCursorPosition);
1546 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001547 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001548 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1549 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001550 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001551 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001552 sp<InputWindowHandle> newTouchedWindowHandle =
1553 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1554 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001555
1556 std::vector<TouchedMonitor> newGestureMonitors = isDown
1557 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1558 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001561 if (newTouchedWindowHandle != nullptr &&
1562 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001563 // New window supports splitting, but we should never split mouse events.
1564 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 } else if (isSplit) {
1566 // New window does not support splitting but we have already split events.
1567 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001568 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569 }
1570
1571 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001572 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 // Try to assign the pointer to the first foreground window we find, if there is one.
1574 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001575 }
1576
1577 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1578 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001579 "(%d, %d) in display %" PRId32 ".",
1580 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001581 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1582 goto Failed;
1583 }
1584
1585 if (newTouchedWindowHandle != nullptr) {
1586 // Set target flags.
1587 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1588 if (isSplit) {
1589 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001591 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1592 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1593 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1594 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1595 }
1596
1597 // Update hover state.
1598 if (isHoverAction) {
1599 newHoverWindowHandle = newTouchedWindowHandle;
1600 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1601 newHoverWindowHandle = mLastHoverWindowHandle;
1602 }
1603
1604 // Update the temporary touch state.
1605 BitSet32 pointerIds;
1606 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001607 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001608 pointerIds.markBit(pointerId);
1609 }
1610 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611 }
1612
Michael Wright3dd60e22019-03-27 22:06:44 +00001613 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 } else {
1615 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1616
1617 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001618 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001619 if (DEBUG_FOCUS) {
1620 ALOGD("Dropping event because the pointer is not down or we previously "
1621 "dropped the pointer down event in display %" PRId32,
1622 displayId);
1623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1625 goto Failed;
1626 }
1627
1628 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001629 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001630 mTempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001631 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1632 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633
1634 sp<InputWindowHandle> oldTouchedWindowHandle =
1635 mTempTouchState.getFirstForegroundWindowHandle();
1636 sp<InputWindowHandle> newTouchedWindowHandle =
1637 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001638 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1639 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001640 if (DEBUG_FOCUS) {
1641 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1642 oldTouchedWindowHandle->getName().c_str(),
1643 newTouchedWindowHandle->getName().c_str(), displayId);
1644 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 // Make a slippery exit from the old window.
1646 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001647 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1648 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649
1650 // Make a slippery entrance into the new window.
1651 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1652 isSplit = true;
1653 }
1654
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001655 int32_t targetFlags =
1656 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 if (isSplit) {
1658 targetFlags |= InputTarget::FLAG_SPLIT;
1659 }
1660 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1661 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1662 }
1663
1664 BitSet32 pointerIds;
1665 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001666 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 }
1668 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1669 }
1670 }
1671 }
1672
1673 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1674 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001675 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676#if DEBUG_HOVER
1677 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001678 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679#endif
1680 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001681 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1682 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 }
1684
1685 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001686 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687#if DEBUG_HOVER
1688 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001689 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690#endif
1691 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001692 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1693 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 }
1695 }
1696
1697 // Check permission to inject into all touched foreground windows and ensure there
1698 // is at least one touched foreground window.
1699 {
1700 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001701 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1703 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001704 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1706 injectionPermission = INJECTION_PERMISSION_DENIED;
1707 goto Failed;
1708 }
1709 }
1710 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001711 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1712 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001713 ALOGI("Dropping event because there is no touched foreground window in display "
1714 "%" PRId32 " or gesture monitor to receive it.",
1715 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1717 goto Failed;
1718 }
1719
1720 // Permission granted to injection into all touched foreground windows.
1721 injectionPermission = INJECTION_PERMISSION_GRANTED;
1722 }
1723
1724 // Check whether windows listening for outside touches are owned by the same UID. If it is
1725 // set the policy flag that we will not reveal coordinate information to this window.
1726 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1727 sp<InputWindowHandle> foregroundWindowHandle =
1728 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001729 if (foregroundWindowHandle) {
1730 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1731 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1732 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1733 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1734 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1735 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001736 InputTarget::FLAG_ZERO_COORDS,
1737 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 }
1740 }
1741 }
1742 }
1743
1744 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001745 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001747 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001748 std::string reason =
1749 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1750 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001751 if (!reason.empty()) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001752 return handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1753 touchedWindow.windowHandle, nextWakeupTime,
1754 reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 }
1756 }
1757 }
1758
1759 // If this is the first pointer going down and the touched window has a wallpaper
1760 // then also add the touched wallpaper windows so they are locked in for the duration
1761 // of the touch gesture.
1762 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1763 // engine only supports touch events. We would need to add a mechanism similar
1764 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1765 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1766 sp<InputWindowHandle> foregroundWindowHandle =
1767 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001768 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001769 const std::vector<sp<InputWindowHandle>> windowHandles =
1770 getWindowHandlesLocked(displayId);
1771 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001773 if (info->displayId == displayId &&
1774 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1775 mTempTouchState
1776 .addOrUpdateWindow(windowHandle,
1777 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1778 InputTarget::
1779 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1780 InputTarget::FLAG_DISPATCH_AS_IS,
1781 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 }
1783 }
1784 }
1785 }
1786
1787 // Success! Output targets.
1788 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1789
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001790 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001792 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 }
1794
Michael Wright3dd60e22019-03-27 22:06:44 +00001795 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1796 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001797 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001798 }
1799
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 // Drop the outside or hover touch windows since we will not care about them
1801 // in the next iteration.
1802 mTempTouchState.filterNonAsIsTouchWindows();
1803
1804Failed:
1805 // Check injection permission once and for all.
1806 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001807 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 injectionPermission = INJECTION_PERMISSION_GRANTED;
1809 } else {
1810 injectionPermission = INJECTION_PERMISSION_DENIED;
1811 }
1812 }
1813
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001814 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1815 return injectionResult;
1816 }
1817
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001819 if (!wrongDevice) {
1820 if (switchedDevice) {
1821 if (DEBUG_FOCUS) {
1822 ALOGD("Conflicting pointer actions: Switched to a different device.");
1823 }
1824 *outConflictingPointerActions = true;
1825 }
1826
1827 if (isHoverAction) {
1828 // Started hovering, therefore no longer down.
1829 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001830 if (DEBUG_FOCUS) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001831 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1832 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 *outConflictingPointerActions = true;
1835 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001836 mTempTouchState.reset();
1837 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1838 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1839 mTempTouchState.deviceId = entry.deviceId;
1840 mTempTouchState.source = entry.source;
1841 mTempTouchState.displayId = displayId;
1842 }
1843 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1844 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1845 // All pointers up or canceled.
1846 mTempTouchState.reset();
1847 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1848 // First pointer went down.
1849 if (oldState && oldState->down) {
1850 if (DEBUG_FOCUS) {
1851 ALOGD("Conflicting pointer actions: Down received while already down.");
1852 }
1853 *outConflictingPointerActions = true;
1854 }
1855 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1856 // One pointer went up.
1857 if (isSplit) {
1858 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1859 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001861 for (size_t i = 0; i < mTempTouchState.windows.size();) {
1862 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1863 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1864 touchedWindow.pointerIds.clearBit(pointerId);
1865 if (touchedWindow.pointerIds.isEmpty()) {
1866 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
1867 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001870 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001872 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001873 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001874
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001875 // Save changes unless the action was scroll in which case the temporary touch
1876 // state was only valid for this one action.
1877 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1878 if (mTempTouchState.displayId >= 0) {
1879 if (oldStateIndex >= 0) {
1880 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1881 } else {
1882 mTouchStatesByDisplay.add(displayId, mTempTouchState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001883 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001884 } else if (oldStateIndex >= 0) {
1885 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001889 // Update hover state.
1890 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891 }
1892
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 return injectionResult;
1894}
1895
1896void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001897 int32_t targetFlags, BitSet32 pointerIds,
1898 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001899 std::vector<InputTarget>::iterator it =
1900 std::find_if(inputTargets.begin(), inputTargets.end(),
1901 [&windowHandle](const InputTarget& inputTarget) {
1902 return inputTarget.inputChannel->getConnectionToken() ==
1903 windowHandle->getToken();
1904 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00001905
Chavi Weingarten114b77f2020-01-15 22:35:10 +00001906 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001907
1908 if (it == inputTargets.end()) {
1909 InputTarget inputTarget;
1910 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1911 if (inputChannel == nullptr) {
1912 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1913 return;
1914 }
1915 inputTarget.inputChannel = inputChannel;
1916 inputTarget.flags = targetFlags;
1917 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
1918 inputTargets.push_back(inputTarget);
1919 it = inputTargets.end() - 1;
1920 }
1921
1922 ALOG_ASSERT(it->flags == targetFlags);
1923 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
1924
1925 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
1926 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927}
1928
Michael Wright3dd60e22019-03-27 22:06:44 +00001929void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001930 int32_t displayId, float xOffset,
1931 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001932 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1933 mGlobalMonitorsByDisplay.find(displayId);
1934
1935 if (it != mGlobalMonitorsByDisplay.end()) {
1936 const std::vector<Monitor>& monitors = it->second;
1937 for (const Monitor& monitor : monitors) {
1938 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 }
1941}
1942
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001943void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1944 float yOffset,
1945 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001946 InputTarget target;
1947 target.inputChannel = monitor.inputChannel;
1948 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001949 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00001950 inputTargets.push_back(target);
1951}
1952
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001954 const InjectionState* injectionState) {
1955 if (injectionState &&
1956 (windowHandle == nullptr ||
1957 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1958 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001959 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001961 "owned by uid %d",
1962 injectionState->injectorPid, injectionState->injectorUid,
1963 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 } else {
1965 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001966 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967 }
1968 return false;
1969 }
1970 return true;
1971}
1972
Robert Carr9cada032020-04-13 17:21:08 -07001973/**
1974 * Indicate whether one window handle should be considered as obscuring
1975 * another window handle. We only check a few preconditions. Actually
1976 * checking the bounds is left to the caller.
1977 */
1978static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
1979 const sp<InputWindowHandle>& otherHandle) {
1980 // Compare by token so cloned layers aren't counted
1981 if (haveSameToken(windowHandle, otherHandle)) {
1982 return false;
1983 }
1984 auto info = windowHandle->getInfo();
1985 auto otherInfo = otherHandle->getInfo();
1986 if (!otherInfo->visible) {
1987 return false;
1988 } else if (info->ownerPid == otherInfo->ownerPid && otherHandle->getToken() == nullptr) {
1989 // In general, if ownerPid is the same we don't want to generate occlusion
1990 // events. This line is now necessary since we are including all Surfaces
1991 // in occlusion calculation, so if we didn't check PID like this SurfaceView
1992 // would occlude their parents. On the other hand before we started including
1993 // all surfaces in occlusion calculation and had this line, we would count
1994 // windows with an input channel from the same PID as occluding, and so we
1995 // preserve this behavior with the getToken() == null check.
1996 return false;
1997 } else if (otherInfo->isTrustedOverlay()) {
1998 return false;
1999 } else if (otherInfo->displayId != info->displayId) {
2000 return false;
2001 }
2002 return true;
2003}
2004
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002005bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2006 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002008 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2009 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002010 if (windowHandle == otherHandle) {
2011 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002014 if (canBeObscuredBy(windowHandle, otherHandle) &&
2015 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 return true;
2017 }
2018 }
2019 return false;
2020}
2021
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002022bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2023 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002024 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002025 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002026 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002027 if (windowHandle == otherHandle) {
2028 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002029 }
2030
2031 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002032 if (canBeObscuredBy(windowHandle, otherHandle) &&
2033 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002034 return true;
2035 }
2036 }
2037 return false;
2038}
2039
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002040std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
2041 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002042 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07002043 // If the window is paused then keep waiting.
2044 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002045 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002046 }
2047
2048 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07002049 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002050 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002051 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002052 "registered with the input dispatcher. The window may be in the "
2053 "process of being removed.",
2054 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002055 }
2056
2057 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07002058 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002059 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002060 "The window may be in the process of being removed.",
2061 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07002062 }
2063
2064 // If the connection is backed up then keep waiting.
2065 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002066 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002067 "Outbound queue length: %zu. Wait queue length: %zu.",
2068 targetType, connection->outboundQueue.size(),
2069 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07002070 }
2071
2072 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002073 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07002074 // If the event is a key event, then we must wait for all previous events to
2075 // complete before delivering it because previous events may have the
2076 // side-effect of transferring focus to a different window and we want to
2077 // ensure that the following keys are sent to the new window.
2078 //
2079 // Suppose the user touches a button in a window then immediately presses "A".
2080 // If the button causes a pop-up window to appear then we want to ensure that
2081 // the "A" key is delivered to the new pop-up window. This is because users
2082 // often anticipate pending UI changes when typing on a keyboard.
2083 // To obtain this behavior, we must serialize key events with respect to all
2084 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002085 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002086 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002087 "finished processing all of the input events that were previously "
2088 "delivered to it. Outbound queue length: %zu. Wait queue length: "
2089 "%zu.",
2090 targetType, connection->outboundQueue.size(),
2091 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092 }
Jeff Brownffb49772014-10-10 19:01:34 -07002093 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 // Touch events can always be sent to a window immediately because the user intended
2095 // to touch whatever was visible at the time. Even if focus changes or a new
2096 // window appears moments later, the touch event was meant to be delivered to
2097 // whatever window happened to be on screen at the time.
2098 //
2099 // Generic motion events, such as trackball or joystick events are a little trickier.
2100 // Like key events, generic motion events are delivered to the focused window.
2101 // Unlike key events, generic motion events don't tend to transfer focus to other
2102 // windows and it is not important for them to be serialized. So we prefer to deliver
2103 // generic motion events as soon as possible to improve efficiency and reduce lag
2104 // through batching.
2105 //
2106 // The one case where we pause input event delivery is when the wait queue is piling
2107 // up with lots of events because the application is not responding.
2108 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002109 if (!connection->waitQueue.empty() &&
2110 currentTime >=
2111 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002112 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002113 "finished processing certain input events that were delivered to "
2114 "it over "
2115 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
2116 "%0.1fms.",
2117 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
2118 connection->waitQueue.size(),
2119 (currentTime - connection->waitQueue.front()->deliveryTime) *
2120 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 }
2122 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002123 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124}
2125
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002126std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127 const sp<InputApplicationHandle>& applicationHandle,
2128 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002129 if (applicationHandle != nullptr) {
2130 if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002131 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 } else {
2133 return applicationHandle->getName();
2134 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002135 } else if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002136 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002138 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 }
2140}
2141
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002142void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002143 if (eventEntry.type == EventEntry::Type::FOCUS) {
2144 // Focus events are passed to apps, but do not represent user activity.
2145 return;
2146 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002147 int32_t displayId = getTargetDisplayId(eventEntry);
2148 sp<InputWindowHandle> focusedWindowHandle =
2149 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2150 if (focusedWindowHandle != nullptr) {
2151 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2153#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002154 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155#endif
2156 return;
2157 }
2158 }
2159
2160 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002161 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002162 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002163 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2164 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002165 return;
2166 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002168 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002169 eventType = USER_ACTIVITY_EVENT_TOUCH;
2170 }
2171 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002173 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002174 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2175 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002176 return;
2177 }
2178 eventType = USER_ACTIVITY_EVENT_BUTTON;
2179 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002181 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002182 case EventEntry::Type::CONFIGURATION_CHANGED:
2183 case EventEntry::Type::DEVICE_RESET: {
2184 LOG_ALWAYS_FATAL("%s events are not user activity",
2185 EventEntry::typeToString(eventEntry.type));
2186 break;
2187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 }
2189
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002190 std::unique_ptr<CommandEntry> commandEntry =
2191 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002192 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002194 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195}
2196
2197void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002198 const sp<Connection>& connection,
2199 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002200 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002201 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002202 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002203 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002204 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002205 ATRACE_NAME(message.c_str());
2206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207#if DEBUG_DISPATCH_CYCLE
2208 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002209 "globalScaleFactor=%f, pointerIds=0x%x %s",
2210 connection->getInputChannelName().c_str(), inputTarget.flags,
2211 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2212 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213#endif
2214
2215 // Skip this event if the connection status is not normal.
2216 // We don't want to enqueue additional outbound events if the connection is broken.
2217 if (connection->status != Connection::STATUS_NORMAL) {
2218#if DEBUG_DISPATCH_CYCLE
2219 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002220 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221#endif
2222 return;
2223 }
2224
2225 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002226 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2227 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2228 "Entry type %s should not have FLAG_SPLIT",
2229 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002231 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002232 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002233 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002234 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235 if (!splitMotionEntry) {
2236 return; // split event was dropped
2237 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002238 if (DEBUG_FOCUS) {
2239 ALOGD("channel '%s' ~ Split motion event.",
2240 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002241 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002242 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002243 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 splitMotionEntry->release();
2245 return;
2246 }
2247 }
2248
2249 // Not splitting. Enqueue dispatch entries for the event as is.
2250 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2251}
2252
2253void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 const sp<Connection>& connection,
2255 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002256 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002257 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002258 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002259 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002260 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002261 ATRACE_NAME(message.c_str());
2262 }
2263
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002264 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265
2266 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002267 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002268 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002269 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002270 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002271 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002272 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002273 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002274 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002275 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002276 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002277 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002278 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279
2280 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002281 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 startDispatchCycleLocked(currentTime, connection);
2283 }
2284}
2285
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002286void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2287 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002288 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002290 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002291 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2292 connection->getInputChannelName().c_str(),
2293 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002294 ATRACE_NAME(message.c_str());
2295 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002296 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 if (!(inputTargetFlags & dispatchMode)) {
2298 return;
2299 }
2300 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2301
2302 // This is a new event.
2303 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002304 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002305 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002307 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2308 // different EventEntry than what was passed in.
2309 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002311 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002312 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002313 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002314 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002315 dispatchEntry->resolvedAction = keyEntry.action;
2316 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002318 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2319 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002321 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2322 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002324 return; // skip the inconsistent event
2325 }
2326 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002329 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002330 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002331 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2332 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2333 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2334 static_cast<int32_t>(IdGenerator::Source::OTHER);
2335 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002336 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2337 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2338 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2339 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2340 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2341 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2342 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2343 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2344 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2345 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2346 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002347 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002348 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002349 }
2350 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002351 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2352 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002354 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2355 "event",
2356 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002358 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002360
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002361 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002362 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2363 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2364 }
2365 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2366 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002369 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2370 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002372 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2373 "event",
2374 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002376 return; // skip the inconsistent event
2377 }
2378
Garfield Tan1c7bc862020-01-28 13:24:04 -08002379 dispatchEntry->resolvedEventId =
2380 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2381 ? mIdGenerator.nextId()
2382 : motionEntry.id;
2383 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2384 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2385 ") to MotionEvent(id=0x%" PRIx32 ").",
2386 motionEntry.id, dispatchEntry->resolvedEventId);
2387 ATRACE_NAME(message.c_str());
2388 }
2389
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002390 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002391 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002392
2393 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002395 case EventEntry::Type::FOCUS: {
2396 break;
2397 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002398 case EventEntry::Type::CONFIGURATION_CHANGED:
2399 case EventEntry::Type::DEVICE_RESET: {
2400 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002401 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002402 break;
2403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 }
2405
2406 // Remember that we are waiting for this dispatch to complete.
2407 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002408 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 }
2410
2411 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002412 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002413 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002414}
2415
chaviwfd6d3512019-03-25 13:23:49 -07002416void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002417 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002418 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002419 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2420 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002421 return;
2422 }
2423
2424 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2425 if (inputWindowHandle == nullptr) {
2426 return;
2427 }
2428
chaviw8c9cf542019-03-25 13:02:48 -07002429 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002430 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002431
2432 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2433
2434 if (!hasFocusChanged) {
2435 return;
2436 }
2437
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002438 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2439 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002440 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002441 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442}
2443
2444void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002445 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002446 if (ATRACE_ENABLED()) {
2447 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002448 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002449 ATRACE_NAME(message.c_str());
2450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002452 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453#endif
2454
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002455 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2456 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 dispatchEntry->deliveryTime = currentTime;
2458
2459 // Publish the event.
2460 status_t status;
2461 EventEntry* eventEntry = dispatchEntry->eventEntry;
2462 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002463 case EventEntry::Type::KEY: {
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002464 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2465 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002467 // Publish the key event.
Garfield Tan1c7bc862020-01-28 13:24:04 -08002468 status =
2469 connection->inputPublisher
2470 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2471 keyEntry->deviceId, keyEntry->source,
2472 keyEntry->displayId, std::move(hmac),
2473 dispatchEntry->resolvedAction,
2474 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2475 keyEntry->scanCode, keyEntry->metaState,
2476 keyEntry->repeatCount, keyEntry->downTime,
2477 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002478 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 }
2480
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002481 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002482 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002484 PointerCoords scaledCoords[MAX_POINTERS];
2485 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2486
chaviw82357092020-01-28 13:13:06 -08002487 // Set the X and Y offset and X and Y scale depending on the input source.
2488 float xOffset = 0.0f, yOffset = 0.0f;
2489 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002490 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2491 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2492 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002493 xScale = dispatchEntry->windowXScale;
2494 yScale = dispatchEntry->windowYScale;
2495 xOffset = dispatchEntry->xOffset * xScale;
2496 yOffset = dispatchEntry->yOffset * yScale;
2497 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002498 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2499 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002500 // Don't apply window scale here since we don't want scale to affect raw
2501 // coordinates. The scale will be sent back to the client and applied
2502 // later when requesting relative coordinates.
2503 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2504 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002505 }
2506 usingCoords = scaledCoords;
2507 }
2508 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002509 // We don't want the dispatch target to know.
2510 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2511 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2512 scaledCoords[i].clear();
2513 }
2514 usingCoords = scaledCoords;
2515 }
2516 }
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002517
2518 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002519
2520 // Publish the motion event.
2521 status = connection->inputPublisher
Garfield Tan1c7bc862020-01-28 13:24:04 -08002522 .publishMotionEvent(dispatchEntry->seq,
2523 dispatchEntry->resolvedEventId,
2524 motionEntry->deviceId, motionEntry->source,
2525 motionEntry->displayId, std::move(hmac),
2526 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002527 motionEntry->actionButton,
2528 dispatchEntry->resolvedFlags,
2529 motionEntry->edgeFlags, motionEntry->metaState,
2530 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002531 motionEntry->classification, xScale, yScale,
2532 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533 motionEntry->yPrecision,
2534 motionEntry->xCursorPosition,
2535 motionEntry->yCursorPosition,
2536 motionEntry->downTime, motionEntry->eventTime,
2537 motionEntry->pointerCount,
2538 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002539 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002540 break;
2541 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002542 case EventEntry::Type::FOCUS: {
2543 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2544 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tan1c7bc862020-01-28 13:24:04 -08002545 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002546 focusEntry->hasFocus,
2547 mInTouchMode);
2548 break;
2549 }
2550
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002551 case EventEntry::Type::CONFIGURATION_CHANGED:
2552 case EventEntry::Type::DEVICE_RESET: {
2553 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2554 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002555 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 }
2558
2559 // Check the result.
2560 if (status) {
2561 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002562 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002564 "This is unexpected because the wait queue is empty, so the pipe "
2565 "should be empty and we shouldn't have any problems writing an "
2566 "event to it, status=%d",
2567 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2569 } else {
2570 // Pipe is full and we are waiting for the app to finish process some events
2571 // before sending more events to it.
2572#if DEBUG_DISPATCH_CYCLE
2573 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002574 "waiting for the application to catch up",
2575 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576#endif
2577 connection->inputPublisherBlocked = true;
2578 }
2579 } else {
2580 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002581 "status=%d",
2582 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2584 }
2585 return;
2586 }
2587
2588 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002589 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2590 connection->outboundQueue.end(),
2591 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002592 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002593 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002594 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595 }
2596}
2597
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002598const std::array<uint8_t, 32> InputDispatcher::getSignature(
2599 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2600 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2601 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2602 // Only sign events up and down events as the purely move events
2603 // are tied to their up/down counterparts so signing would be redundant.
2604 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2605 verifiedEvent.actionMasked = actionMasked;
2606 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2607 return mHmacKeyManager.sign(verifiedEvent);
2608 }
2609 return INVALID_HMAC;
2610}
2611
2612const std::array<uint8_t, 32> InputDispatcher::getSignature(
2613 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2614 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2615 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2616 verifiedEvent.action = dispatchEntry.resolvedAction;
2617 return mHmacKeyManager.sign(verifiedEvent);
2618}
2619
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002621 const sp<Connection>& connection, uint32_t seq,
2622 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623#if DEBUG_DISPATCH_CYCLE
2624 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002625 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626#endif
2627
2628 connection->inputPublisherBlocked = false;
2629
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002630 if (connection->status == Connection::STATUS_BROKEN ||
2631 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632 return;
2633 }
2634
2635 // Notify other system components and prepare to start the next dispatch cycle.
2636 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2637}
2638
2639void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002640 const sp<Connection>& connection,
2641 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642#if DEBUG_DISPATCH_CYCLE
2643 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002644 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645#endif
2646
2647 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002648 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002649 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002650 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002651 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652
2653 // The connection appears to be unrecoverably broken.
2654 // Ignore already broken or zombie connections.
2655 if (connection->status == Connection::STATUS_NORMAL) {
2656 connection->status = Connection::STATUS_BROKEN;
2657
2658 if (notify) {
2659 // Notify other system components.
2660 onDispatchCycleBrokenLocked(currentTime, connection);
2661 }
2662 }
2663}
2664
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002665void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2666 while (!queue.empty()) {
2667 DispatchEntry* dispatchEntry = queue.front();
2668 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002669 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 }
2671}
2672
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002673void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002675 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676 }
2677 delete dispatchEntry;
2678}
2679
2680int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2681 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2682
2683 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002684 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002686 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002688 "fd=%d, events=0x%x",
2689 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690 return 0; // remove the callback
2691 }
2692
2693 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002694 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2696 if (!(events & ALOOPER_EVENT_INPUT)) {
2697 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002698 "events=0x%x",
2699 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 return 1;
2701 }
2702
2703 nsecs_t currentTime = now();
2704 bool gotOne = false;
2705 status_t status;
2706 for (;;) {
2707 uint32_t seq;
2708 bool handled;
2709 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2710 if (status) {
2711 break;
2712 }
2713 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2714 gotOne = true;
2715 }
2716 if (gotOne) {
2717 d->runCommandsLockedInterruptible();
2718 if (status == WOULD_BLOCK) {
2719 return 1;
2720 }
2721 }
2722
2723 notify = status != DEAD_OBJECT || !connection->monitor;
2724 if (notify) {
2725 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002726 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727 }
2728 } else {
2729 // Monitor channels are never explicitly unregistered.
2730 // We do it automatically when the remote endpoint is closed so don't warn
2731 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002732 const bool stillHaveWindowHandle =
2733 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2734 nullptr;
2735 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 if (notify) {
2737 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002738 "events=0x%x",
2739 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740 }
2741 }
2742
2743 // Unregister the channel.
2744 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2745 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002746 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747}
2748
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002749void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002751 for (const auto& pair : mConnectionsByFd) {
2752 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753 }
2754}
2755
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002756void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002757 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002758 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2759 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2760}
2761
2762void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2763 const CancelationOptions& options,
2764 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2765 for (const auto& it : monitorsByDisplay) {
2766 const std::vector<Monitor>& monitors = it.second;
2767 for (const Monitor& monitor : monitors) {
2768 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002769 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002770 }
2771}
2772
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2774 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002775 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002776 if (connection == nullptr) {
2777 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002779
2780 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781}
2782
2783void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2784 const sp<Connection>& connection, const CancelationOptions& options) {
2785 if (connection->status == Connection::STATUS_BROKEN) {
2786 return;
2787 }
2788
2789 nsecs_t currentTime = now();
2790
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002791 std::vector<EventEntry*> cancelationEvents =
2792 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002794 if (cancelationEvents.empty()) {
2795 return;
2796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002798 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2799 "with reality: %s, mode=%d.",
2800 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2801 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002803
2804 InputTarget target;
2805 sp<InputWindowHandle> windowHandle =
2806 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2807 if (windowHandle != nullptr) {
2808 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2809 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2810 windowInfo->windowXScale, windowInfo->windowYScale);
2811 target.globalScaleFactor = windowInfo->globalScaleFactor;
2812 }
2813 target.inputChannel = connection->inputChannel;
2814 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2815
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002816 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2817 EventEntry* cancelationEventEntry = cancelationEvents[i];
2818 switch (cancelationEventEntry->type) {
2819 case EventEntry::Type::KEY: {
2820 logOutboundKeyDetails("cancel - ",
2821 static_cast<const KeyEntry&>(*cancelationEventEntry));
2822 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002824 case EventEntry::Type::MOTION: {
2825 logOutboundMotionDetails("cancel - ",
2826 static_cast<const MotionEntry&>(*cancelationEventEntry));
2827 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002829 case EventEntry::Type::FOCUS: {
2830 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2831 break;
2832 }
2833 case EventEntry::Type::CONFIGURATION_CHANGED:
2834 case EventEntry::Type::DEVICE_RESET: {
2835 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2836 EventEntry::typeToString(cancelationEventEntry->type));
2837 break;
2838 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839 }
2840
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002841 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2842 target, InputTarget::FLAG_DISPATCH_AS_IS);
2843
2844 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002846
2847 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848}
2849
Svet Ganov5d3bc372020-01-26 23:11:07 -08002850void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2851 const sp<Connection>& connection) {
2852 if (connection->status == Connection::STATUS_BROKEN) {
2853 return;
2854 }
2855
2856 nsecs_t currentTime = now();
2857
2858 std::vector<EventEntry*> downEvents =
2859 connection->inputState.synthesizePointerDownEvents(currentTime);
2860
2861 if (downEvents.empty()) {
2862 return;
2863 }
2864
2865#if DEBUG_OUTBOUND_EVENT_DETAILS
2866 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2867 connection->getInputChannelName().c_str(), downEvents.size());
2868#endif
2869
2870 InputTarget target;
2871 sp<InputWindowHandle> windowHandle =
2872 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2873 if (windowHandle != nullptr) {
2874 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2875 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2876 windowInfo->windowXScale, windowInfo->windowYScale);
2877 target.globalScaleFactor = windowInfo->globalScaleFactor;
2878 }
2879 target.inputChannel = connection->inputChannel;
2880 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2881
2882 for (EventEntry* downEventEntry : downEvents) {
2883 switch (downEventEntry->type) {
2884 case EventEntry::Type::MOTION: {
2885 logOutboundMotionDetails("down - ",
2886 static_cast<const MotionEntry&>(*downEventEntry));
2887 break;
2888 }
2889
2890 case EventEntry::Type::KEY:
2891 case EventEntry::Type::FOCUS:
2892 case EventEntry::Type::CONFIGURATION_CHANGED:
2893 case EventEntry::Type::DEVICE_RESET: {
2894 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2895 EventEntry::typeToString(downEventEntry->type));
2896 break;
2897 }
2898 }
2899
2900 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2901 target, InputTarget::FLAG_DISPATCH_AS_IS);
2902
2903 downEventEntry->release();
2904 }
2905
2906 startDispatchCycleLocked(currentTime, connection);
2907}
2908
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002909MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002910 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911 ALOG_ASSERT(pointerIds.value != 0);
2912
2913 uint32_t splitPointerIndexMap[MAX_POINTERS];
2914 PointerProperties splitPointerProperties[MAX_POINTERS];
2915 PointerCoords splitPointerCoords[MAX_POINTERS];
2916
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002917 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918 uint32_t splitPointerCount = 0;
2919
2920 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002921 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002923 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924 uint32_t pointerId = uint32_t(pointerProperties.id);
2925 if (pointerIds.hasBit(pointerId)) {
2926 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2927 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2928 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002929 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 splitPointerCount += 1;
2931 }
2932 }
2933
2934 if (splitPointerCount != pointerIds.count()) {
2935 // This is bad. We are missing some of the pointers that we expected to deliver.
2936 // Most likely this indicates that we received an ACTION_MOVE events that has
2937 // different pointer ids than we expected based on the previous ACTION_DOWN
2938 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2939 // in this way.
2940 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002941 "we expected there to be %d pointers. This probably means we received "
2942 "a broken sequence of pointer ids from the input device.",
2943 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002944 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945 }
2946
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002947 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002949 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2950 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2952 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002953 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954 uint32_t pointerId = uint32_t(pointerProperties.id);
2955 if (pointerIds.hasBit(pointerId)) {
2956 if (pointerIds.count() == 1) {
2957 // The first/last pointer went down/up.
2958 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 ? AMOTION_EVENT_ACTION_DOWN
2960 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961 } else {
2962 // A secondary pointer went down/up.
2963 uint32_t splitPointerIndex = 0;
2964 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2965 splitPointerIndex += 1;
2966 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 action = maskedAction |
2968 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969 }
2970 } else {
2971 // An unrelated pointer changed.
2972 action = AMOTION_EVENT_ACTION_MOVE;
2973 }
2974 }
2975
Garfield Tan1c7bc862020-01-28 13:24:04 -08002976 int32_t newId = mIdGenerator.nextId();
2977 if (ATRACE_ENABLED()) {
2978 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
2979 ") to MotionEvent(id=0x%" PRIx32 ").",
2980 originalMotionEntry.id, newId);
2981 ATRACE_NAME(message.c_str());
2982 }
Garfield Tan00f511d2019-06-12 16:55:40 -07002983 MotionEntry* splitMotionEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002984 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
2985 originalMotionEntry.source, originalMotionEntry.displayId,
2986 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002987 originalMotionEntry.actionButton, originalMotionEntry.flags,
2988 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2989 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2990 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2991 originalMotionEntry.xCursorPosition,
2992 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002993 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002995 if (originalMotionEntry.injectionState) {
2996 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997 splitMotionEntry->injectionState->refCount += 1;
2998 }
2999
3000 return splitMotionEntry;
3001}
3002
3003void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3004#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003005 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006#endif
3007
3008 bool needWake;
3009 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003010 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011
Prabir Pradhan42611e02018-11-27 14:04:02 -08003012 ConfigurationChangedEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003013 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014 needWake = enqueueInboundEventLocked(newEntry);
3015 } // release lock
3016
3017 if (needWake) {
3018 mLooper->wake();
3019 }
3020}
3021
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003022/**
3023 * If one of the meta shortcuts is detected, process them here:
3024 * Meta + Backspace -> generate BACK
3025 * Meta + Enter -> generate HOME
3026 * This will potentially overwrite keyCode and metaState.
3027 */
3028void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003029 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003030 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3031 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3032 if (keyCode == AKEYCODE_DEL) {
3033 newKeyCode = AKEYCODE_BACK;
3034 } else if (keyCode == AKEYCODE_ENTER) {
3035 newKeyCode = AKEYCODE_HOME;
3036 }
3037 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003038 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003039 struct KeyReplacement replacement = {keyCode, deviceId};
3040 mReplacedKeys.add(replacement, newKeyCode);
3041 keyCode = newKeyCode;
3042 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3043 }
3044 } else if (action == AKEY_EVENT_ACTION_UP) {
3045 // In order to maintain a consistent stream of up and down events, check to see if the key
3046 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3047 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003048 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003049 struct KeyReplacement replacement = {keyCode, deviceId};
3050 ssize_t index = mReplacedKeys.indexOfKey(replacement);
3051 if (index >= 0) {
3052 keyCode = mReplacedKeys.valueAt(index);
3053 mReplacedKeys.removeItemsAt(index);
3054 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3055 }
3056 }
3057}
3058
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3060#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003061 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3062 "policyFlags=0x%x, action=0x%x, "
3063 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3064 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3065 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3066 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067#endif
3068 if (!validateKeyEvent(args->action)) {
3069 return;
3070 }
3071
3072 uint32_t policyFlags = args->policyFlags;
3073 int32_t flags = args->flags;
3074 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003075 // InputDispatcher tracks and generates key repeats on behalf of
3076 // whatever notifies it, so repeatCount should always be set to 0
3077 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3079 policyFlags |= POLICY_FLAG_VIRTUAL;
3080 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082 if (policyFlags & POLICY_FLAG_FUNCTION) {
3083 metaState |= AMETA_FUNCTION_ON;
3084 }
3085
3086 policyFlags |= POLICY_FLAG_TRUSTED;
3087
Michael Wright78f24442014-08-06 15:55:28 -07003088 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003089 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003090
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003092 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08003093 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3094 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095
Michael Wright2b3c3302018-03-02 17:19:13 +00003096 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003098 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3099 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003101 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 bool needWake;
3104 { // acquire lock
3105 mLock.lock();
3106
3107 if (shouldSendKeyToInputFilterLocked(args)) {
3108 mLock.unlock();
3109
3110 policyFlags |= POLICY_FLAG_FILTERED;
3111 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3112 return; // event was consumed by the filter
3113 }
3114
3115 mLock.lock();
3116 }
3117
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003118 KeyEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003119 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003120 args->displayId, policyFlags, args->action, flags, keyCode,
3121 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122
3123 needWake = enqueueInboundEventLocked(newEntry);
3124 mLock.unlock();
3125 } // release lock
3126
3127 if (needWake) {
3128 mLooper->wake();
3129 }
3130}
3131
3132bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3133 return mInputFilterEnabled;
3134}
3135
3136void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3137#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003138 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3139 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003140 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3141 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003142 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003143 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3144 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3145 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3146 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 for (uint32_t i = 0; i < args->pointerCount; i++) {
3148 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 "x=%f, y=%f, pressure=%f, size=%f, "
3150 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3151 "orientation=%f",
3152 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3153 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3154 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3155 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3156 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3157 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3158 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3159 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3160 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3161 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 }
3163#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003164 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3165 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166 return;
3167 }
3168
3169 uint32_t policyFlags = args->policyFlags;
3170 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003171
3172 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003173 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003174 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3175 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003176 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178
3179 bool needWake;
3180 { // acquire lock
3181 mLock.lock();
3182
3183 if (shouldSendMotionToInputFilterLocked(args)) {
3184 mLock.unlock();
3185
3186 MotionEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003187 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3188 args->action, args->actionButton, args->flags, args->edgeFlags,
3189 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3190 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3191 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3192 args->downTime, args->eventTime, args->pointerCount,
3193 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194
3195 policyFlags |= POLICY_FLAG_FILTERED;
3196 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3197 return; // event was consumed by the filter
3198 }
3199
3200 mLock.lock();
3201 }
3202
3203 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003204 MotionEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003205 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003206 args->displayId, policyFlags, args->action, args->actionButton,
3207 args->flags, args->metaState, args->buttonState,
3208 args->classification, args->edgeFlags, args->xPrecision,
3209 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3210 args->downTime, args->pointerCount, args->pointerProperties,
3211 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212
3213 needWake = enqueueInboundEventLocked(newEntry);
3214 mLock.unlock();
3215 } // release lock
3216
3217 if (needWake) {
3218 mLooper->wake();
3219 }
3220}
3221
3222bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003223 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224}
3225
3226void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3227#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003228 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 "switchMask=0x%08x",
3230 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231#endif
3232
3233 uint32_t policyFlags = args->policyFlags;
3234 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003235 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236}
3237
3238void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3239#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003240 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3241 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242#endif
3243
3244 bool needWake;
3245 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003246 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247
Prabir Pradhan42611e02018-11-27 14:04:02 -08003248 DeviceResetEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003249 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 needWake = enqueueInboundEventLocked(newEntry);
3251 } // release lock
3252
3253 if (needWake) {
3254 mLooper->wake();
3255 }
3256}
3257
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003258int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3259 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003260 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261#if DEBUG_INBOUND_EVENT_DETAILS
3262 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003263 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3264 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265#endif
3266
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003267 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268
3269 policyFlags |= POLICY_FLAG_INJECTED;
3270 if (hasInjectionPermission(injectorPid, injectorUid)) {
3271 policyFlags |= POLICY_FLAG_TRUSTED;
3272 }
3273
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003274 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003276 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003277 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3278 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003279 if (!validateKeyEvent(action)) {
3280 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003283 int32_t flags = incomingKey.getFlags();
3284 int32_t keyCode = incomingKey.getKeyCode();
3285 int32_t metaState = incomingKey.getMetaState();
3286 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003287 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003288 KeyEvent keyEvent;
Garfield Tanfbe732e2020-01-24 11:26:14 -08003289 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003290 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3291 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3292 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003294 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3295 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003296 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003297
3298 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3299 android::base::Timer t;
3300 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3301 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3302 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3303 std::to_string(t.duration().count()).c_str());
3304 }
3305 }
3306
3307 mLock.lock();
3308 KeyEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003309 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3310 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003311 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3312 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tanfbe732e2020-01-24 11:26:14 -08003313 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003314 injectedEntries.push(injectedEntry);
3315 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316 }
3317
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 case AINPUT_EVENT_TYPE_MOTION: {
3319 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3320 int32_t action = motionEvent->getAction();
3321 size_t pointerCount = motionEvent->getPointerCount();
3322 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3323 int32_t actionButton = motionEvent->getActionButton();
3324 int32_t displayId = motionEvent->getDisplayId();
3325 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3326 return INPUT_EVENT_INJECTION_FAILED;
3327 }
3328
3329 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3330 nsecs_t eventTime = motionEvent->getEventTime();
3331 android::base::Timer t;
3332 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3333 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3334 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3335 std::to_string(t.duration().count()).c_str());
3336 }
3337 }
3338
3339 mLock.lock();
3340 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3341 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3342 MotionEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003343 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3344 motionEvent->getSource(), motionEvent->getDisplayId(),
3345 policyFlags, action, actionButton, motionEvent->getFlags(),
3346 motionEvent->getMetaState(), motionEvent->getButtonState(),
3347 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3348 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003349 motionEvent->getRawXCursorPosition(),
3350 motionEvent->getRawYCursorPosition(),
3351 motionEvent->getDownTime(), uint32_t(pointerCount),
3352 pointerProperties, samplePointerCoords,
3353 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003354 injectedEntries.push(injectedEntry);
3355 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3356 sampleEventTimes += 1;
3357 samplePointerCoords += pointerCount;
3358 MotionEntry* nextInjectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003359 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003360 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003361 motionEvent->getDisplayId(), policyFlags, action,
3362 actionButton, motionEvent->getFlags(),
3363 motionEvent->getMetaState(), motionEvent->getButtonState(),
3364 motionEvent->getClassification(),
3365 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3366 motionEvent->getYPrecision(),
3367 motionEvent->getRawXCursorPosition(),
3368 motionEvent->getRawYCursorPosition(),
3369 motionEvent->getDownTime(), uint32_t(pointerCount),
3370 pointerProperties, samplePointerCoords,
3371 motionEvent->getXOffset(), motionEvent->getYOffset());
3372 injectedEntries.push(nextInjectedEntry);
3373 }
3374 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003377 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003378 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380 }
3381
3382 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3383 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3384 injectionState->injectionIsAsync = true;
3385 }
3386
3387 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003388 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389
3390 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003391 while (!injectedEntries.empty()) {
3392 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3393 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 }
3395
3396 mLock.unlock();
3397
3398 if (needWake) {
3399 mLooper->wake();
3400 }
3401
3402 int32_t injectionResult;
3403 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003404 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405
3406 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3407 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3408 } else {
3409 for (;;) {
3410 injectionResult = injectionState->injectionResult;
3411 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3412 break;
3413 }
3414
3415 nsecs_t remainingTimeout = endTime - now();
3416 if (remainingTimeout <= 0) {
3417#if DEBUG_INJECTION
3418 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003419 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420#endif
3421 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3422 break;
3423 }
3424
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003425 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 }
3427
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003428 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3429 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 while (injectionState->pendingForegroundDispatches != 0) {
3431#if DEBUG_INJECTION
3432 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003433 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434#endif
3435 nsecs_t remainingTimeout = endTime - now();
3436 if (remainingTimeout <= 0) {
3437#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003438 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3439 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440#endif
3441 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3442 break;
3443 }
3444
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003445 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446 }
3447 }
3448 }
3449
3450 injectionState->release();
3451 } // release lock
3452
3453#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003454 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003455 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456#endif
3457
3458 return injectionResult;
3459}
3460
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003461std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003462 std::array<uint8_t, 32> calculatedHmac;
3463 std::unique_ptr<VerifiedInputEvent> result;
3464 switch (event.getType()) {
3465 case AINPUT_EVENT_TYPE_KEY: {
3466 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3467 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3468 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3469 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3470 break;
3471 }
3472 case AINPUT_EVENT_TYPE_MOTION: {
3473 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3474 VerifiedMotionEvent verifiedMotionEvent =
3475 verifiedMotionEventFromMotionEvent(motionEvent);
3476 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3477 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3478 break;
3479 }
3480 default: {
3481 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3482 return nullptr;
3483 }
3484 }
3485 if (calculatedHmac == INVALID_HMAC) {
3486 return nullptr;
3487 }
3488 if (calculatedHmac != event.getHmac()) {
3489 return nullptr;
3490 }
3491 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003492}
3493
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003495 return injectorUid == 0 ||
3496 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497}
3498
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003499void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500 InjectionState* injectionState = entry->injectionState;
3501 if (injectionState) {
3502#if DEBUG_INJECTION
3503 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003504 "injectorPid=%d, injectorUid=%d",
3505 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506#endif
3507
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003508 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 // Log the outcome since the injector did not wait for the injection result.
3510 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003511 case INPUT_EVENT_INJECTION_SUCCEEDED:
3512 ALOGV("Asynchronous input event injection succeeded.");
3513 break;
3514 case INPUT_EVENT_INJECTION_FAILED:
3515 ALOGW("Asynchronous input event injection failed.");
3516 break;
3517 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3518 ALOGW("Asynchronous input event injection permission denied.");
3519 break;
3520 case INPUT_EVENT_INJECTION_TIMED_OUT:
3521 ALOGW("Asynchronous input event injection timed out.");
3522 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523 }
3524 }
3525
3526 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003527 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 }
3529}
3530
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003531void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 InjectionState* injectionState = entry->injectionState;
3533 if (injectionState) {
3534 injectionState->pendingForegroundDispatches += 1;
3535 }
3536}
3537
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003538void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539 InjectionState* injectionState = entry->injectionState;
3540 if (injectionState) {
3541 injectionState->pendingForegroundDispatches -= 1;
3542
3543 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003544 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 }
3546 }
3547}
3548
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003549std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3550 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003551 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003552}
3553
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003555 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003556 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003557 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3558 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003559 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003560 return windowHandle;
3561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562 }
3563 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003564 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565}
3566
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003567bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003568 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003569 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3570 for (const sp<InputWindowHandle>& handle : windowHandles) {
3571 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003572 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003573 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003574 ", but it should belong to display %" PRId32,
3575 windowHandle->getName().c_str(), it.first,
3576 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003577 }
3578 return true;
3579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 }
3581 }
3582 return false;
3583}
3584
Robert Carr5c8a0262018-10-03 16:30:44 -07003585sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3586 size_t count = mInputChannelsByToken.count(token);
3587 if (count == 0) {
3588 return nullptr;
3589 }
3590 return mInputChannelsByToken.at(token);
3591}
3592
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003593void InputDispatcher::updateWindowHandlesForDisplayLocked(
3594 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3595 if (inputWindowHandles.empty()) {
3596 // Remove all handles on a display if there are no windows left.
3597 mWindowHandlesByDisplay.erase(displayId);
3598 return;
3599 }
3600
3601 // Since we compare the pointer of input window handles across window updates, we need
3602 // to make sure the handle object for the same window stays unchanged across updates.
3603 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003604 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003605 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003606 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003607 }
3608
3609 std::vector<sp<InputWindowHandle>> newHandles;
3610 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3611 if (!handle->updateInfo()) {
3612 // handle no longer valid
3613 continue;
3614 }
3615
3616 const InputWindowInfo* info = handle->getInfo();
3617 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3618 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3619 const bool noInputChannel =
3620 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3621 const bool canReceiveInput =
3622 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3623 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3624 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003625 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003626 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003627 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003628 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003629 }
3630
3631 if (info->displayId != displayId) {
3632 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3633 handle->getName().c_str(), displayId, info->displayId);
3634 continue;
3635 }
3636
Robert Carredd13602020-04-13 17:24:34 -07003637 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3638 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003639 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003640 oldHandle->updateFrom(handle);
3641 newHandles.push_back(oldHandle);
3642 } else {
3643 newHandles.push_back(handle);
3644 }
3645 }
3646
3647 // Insert or replace
3648 mWindowHandlesByDisplay[displayId] = newHandles;
3649}
3650
Arthur Hung72d8dc32020-03-28 00:48:39 +00003651void InputDispatcher::setInputWindows(
3652 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3653 { // acquire lock
3654 std::scoped_lock _l(mLock);
3655 for (auto const& i : handlesPerDisplay) {
3656 setInputWindowsLocked(i.second, i.first);
3657 }
3658 }
3659 // Wake up poll loop since it may need to make new input dispatching choices.
3660 mLooper->wake();
3661}
3662
Arthur Hungb92218b2018-08-14 12:00:21 +08003663/**
3664 * Called from InputManagerService, update window handle list by displayId that can receive input.
3665 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3666 * If set an empty list, remove all handles from the specific display.
3667 * For focused handle, check if need to change and send a cancel event to previous one.
3668 * For removed handle, check if need to send a cancel event if already in touch.
3669 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003670void InputDispatcher::setInputWindowsLocked(
3671 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003672 if (DEBUG_FOCUS) {
3673 std::string windowList;
3674 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3675 windowList += iwh->getName() + " ";
3676 }
3677 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679
Arthur Hung72d8dc32020-03-28 00:48:39 +00003680 // Copy old handles for release if they are no longer present.
3681 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682
Arthur Hung72d8dc32020-03-28 00:48:39 +00003683 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003684
Arthur Hung72d8dc32020-03-28 00:48:39 +00003685 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3686 bool foundHoveredWindow = false;
3687 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3688 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3689 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3690 windowHandle->getInfo()->visible) {
3691 newFocusedWindowHandle = windowHandle;
3692 }
3693 if (windowHandle == mLastHoverWindowHandle) {
3694 foundHoveredWindow = true;
3695 }
3696 }
3697
3698 if (!foundHoveredWindow) {
3699 mLastHoverWindowHandle = nullptr;
3700 }
3701
3702 sp<InputWindowHandle> oldFocusedWindowHandle =
3703 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3704
3705 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3706 if (oldFocusedWindowHandle != nullptr) {
3707 if (DEBUG_FOCUS) {
3708 ALOGD("Focus left window: %s in display %" PRId32,
3709 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003710 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003711 sp<InputChannel> focusedInputChannel =
3712 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3713 if (focusedInputChannel != nullptr) {
3714 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3715 "focus left window");
3716 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3717 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003718 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003719 mFocusedWindowHandlesByDisplay.erase(displayId);
3720 }
3721 if (newFocusedWindowHandle != nullptr) {
3722 if (DEBUG_FOCUS) {
3723 ALOGD("Focus entered window: %s in display %" PRId32,
3724 newFocusedWindowHandle->getName().c_str(), displayId);
3725 }
3726 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3727 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 }
3729
Arthur Hung72d8dc32020-03-28 00:48:39 +00003730 if (mFocusedDisplayId == displayId) {
3731 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734
Arthur Hung72d8dc32020-03-28 00:48:39 +00003735 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3736 if (stateIndex >= 0) {
3737 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
3738 for (size_t i = 0; i < state.windows.size();) {
3739 TouchedWindow& touchedWindow = state.windows[i];
3740 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003741 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003742 ALOGD("Touched window was removed: %s in display %" PRId32,
3743 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003744 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003745 sp<InputChannel> touchedInputChannel =
3746 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3747 if (touchedInputChannel != nullptr) {
3748 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3749 "touched window was removed");
3750 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003752 state.windows.erase(state.windows.begin() + i);
3753 } else {
3754 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755 }
3756 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003757 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003758
Arthur Hung72d8dc32020-03-28 00:48:39 +00003759 // Release information for windows that are no longer present.
3760 // This ensures that unused input channels are released promptly.
3761 // Otherwise, they might stick around until the window handle is destroyed
3762 // which might not happen until the next GC.
3763 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3764 if (!hasWindowHandleLocked(oldWindowHandle)) {
3765 if (DEBUG_FOCUS) {
3766 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003767 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003768 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003769 }
chaviw291d88a2019-02-14 10:33:58 -08003770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771}
3772
3773void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003774 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003775 if (DEBUG_FOCUS) {
3776 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3777 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003780 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781
Tiger Huang721e26f2018-07-24 22:26:19 +08003782 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3783 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003784 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003785 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3786 if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003787 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003789 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003791 } else if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003792 resetAnrTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003793 oldFocusedApplicationHandle.clear();
3794 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 } // release lock
3797
3798 // Wake up poll loop since it may need to make new input dispatching choices.
3799 mLooper->wake();
3800}
3801
Tiger Huang721e26f2018-07-24 22:26:19 +08003802/**
3803 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3804 * the display not specified.
3805 *
3806 * We track any unreleased events for each window. If a window loses the ability to receive the
3807 * released event, we will send a cancel event to it. So when the focused display is changed, we
3808 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3809 * display. The display-specified events won't be affected.
3810 */
3811void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003812 if (DEBUG_FOCUS) {
3813 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3814 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003815 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003816 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003817
3818 if (mFocusedDisplayId != displayId) {
3819 sp<InputWindowHandle> oldFocusedWindowHandle =
3820 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3821 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003822 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003823 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003824 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003825 CancelationOptions
3826 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3827 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003828 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003829 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3830 }
3831 }
3832 mFocusedDisplayId = displayId;
3833
3834 // Sanity check
3835 sp<InputWindowHandle> newFocusedWindowHandle =
3836 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003837 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003838
Tiger Huang721e26f2018-07-24 22:26:19 +08003839 if (newFocusedWindowHandle == nullptr) {
3840 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3841 if (!mFocusedWindowHandlesByDisplay.empty()) {
3842 ALOGE("But another display has a focused window:");
3843 for (auto& it : mFocusedWindowHandlesByDisplay) {
3844 const int32_t displayId = it.first;
3845 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003846 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3847 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003848 }
3849 }
3850 }
3851 }
3852
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003853 if (DEBUG_FOCUS) {
3854 logDispatchStateLocked();
3855 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003856 } // release lock
3857
3858 // Wake up poll loop since it may need to make new input dispatching choices.
3859 mLooper->wake();
3860}
3861
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003863 if (DEBUG_FOCUS) {
3864 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3865 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866
3867 bool changed;
3868 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003869 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870
3871 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3872 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003873 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 }
3875
3876 if (mDispatchEnabled && !enabled) {
3877 resetAndDropEverythingLocked("dispatcher is being disabled");
3878 }
3879
3880 mDispatchEnabled = enabled;
3881 mDispatchFrozen = frozen;
3882 changed = true;
3883 } else {
3884 changed = false;
3885 }
3886
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003887 if (DEBUG_FOCUS) {
3888 logDispatchStateLocked();
3889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890 } // release lock
3891
3892 if (changed) {
3893 // Wake up poll loop since it may need to make new input dispatching choices.
3894 mLooper->wake();
3895 }
3896}
3897
3898void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003899 if (DEBUG_FOCUS) {
3900 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902
3903 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003904 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905
3906 if (mInputFilterEnabled == enabled) {
3907 return;
3908 }
3909
3910 mInputFilterEnabled = enabled;
3911 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3912 } // release lock
3913
3914 // Wake up poll loop since there might be work to do to drop everything.
3915 mLooper->wake();
3916}
3917
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003918void InputDispatcher::setInTouchMode(bool inTouchMode) {
3919 std::scoped_lock lock(mLock);
3920 mInTouchMode = inTouchMode;
3921}
3922
chaviwfbe5d9c2018-12-26 12:23:37 -08003923bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3924 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003925 if (DEBUG_FOCUS) {
3926 ALOGD("Trivial transfer to same window.");
3927 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003928 return true;
3929 }
3930
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003932 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933
chaviwfbe5d9c2018-12-26 12:23:37 -08003934 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3935 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003936 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003937 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938 return false;
3939 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003940 if (DEBUG_FOCUS) {
3941 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3942 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003945 if (DEBUG_FOCUS) {
3946 ALOGD("Cannot transfer focus because windows are on different displays.");
3947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948 return false;
3949 }
3950
3951 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003952 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3953 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3954 for (size_t i = 0; i < state.windows.size(); i++) {
3955 const TouchedWindow& touchedWindow = state.windows[i];
3956 if (touchedWindow.windowHandle == fromWindowHandle) {
3957 int32_t oldTargetFlags = touchedWindow.targetFlags;
3958 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003960 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962 int32_t newTargetFlags = oldTargetFlags &
3963 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3964 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003965 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966
Jeff Brownf086ddb2014-02-11 14:28:48 -08003967 found = true;
3968 goto Found;
3969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 }
3971 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003972 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003974 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003975 if (DEBUG_FOCUS) {
3976 ALOGD("Focus transfer failed because from window did not have focus.");
3977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 return false;
3979 }
3980
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003981 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3982 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003983 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003984 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003985 CancelationOptions
3986 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3987 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003989 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 }
3991
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003992 if (DEBUG_FOCUS) {
3993 logDispatchStateLocked();
3994 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 } // release lock
3996
3997 // Wake up poll loop since it may need to make new input dispatching choices.
3998 mLooper->wake();
3999 return true;
4000}
4001
4002void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004003 if (DEBUG_FOCUS) {
4004 ALOGD("Resetting and dropping all events (%s).", reason);
4005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006
4007 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4008 synthesizeCancelationEventsForAllConnectionsLocked(options);
4009
4010 resetKeyRepeatLocked();
4011 releasePendingEventLocked();
4012 drainInboundQueueLocked();
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004013 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014
Jeff Brownf086ddb2014-02-11 14:28:48 -08004015 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004017 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018}
4019
4020void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004021 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022 dumpDispatchStateLocked(dump);
4023
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004024 std::istringstream stream(dump);
4025 std::string line;
4026
4027 while (std::getline(stream, line, '\n')) {
4028 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 }
4030}
4031
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004032void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004033 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4034 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4035 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004036 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037
Tiger Huang721e26f2018-07-24 22:26:19 +08004038 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4039 dump += StringPrintf(INDENT "FocusedApplications:\n");
4040 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4041 const int32_t displayId = it.first;
4042 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004043 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004044 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004045 displayId, applicationHandle->getName().c_str(),
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004046 ns2ms(applicationHandle
4047 ->getDispatchingTimeout(
4048 DEFAULT_INPUT_DISPATCHING_TIMEOUT)
4049 .count()));
Tiger Huang721e26f2018-07-24 22:26:19 +08004050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004052 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004054
4055 if (!mFocusedWindowHandlesByDisplay.empty()) {
4056 dump += StringPrintf(INDENT "FocusedWindows:\n");
4057 for (auto& it : mFocusedWindowHandlesByDisplay) {
4058 const int32_t displayId = it.first;
4059 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004060 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4061 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004062 }
4063 } else {
4064 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4065 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066
Jeff Brownf086ddb2014-02-11 14:28:48 -08004067 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004068 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08004069 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
4070 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004071 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004072 state.displayId, toString(state.down), toString(state.split),
4073 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004074 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004075 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004076 for (size_t i = 0; i < state.windows.size(); i++) {
4077 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004078 dump += StringPrintf(INDENT4
4079 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4080 i, touchedWindow.windowHandle->getName().c_str(),
4081 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004082 }
4083 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004084 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004085 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004086 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004087 dump += INDENT3 "Portal windows:\n";
4088 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004089 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004090 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4091 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004092 }
4093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094 }
4095 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004096 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 }
4098
Arthur Hungb92218b2018-08-14 12:00:21 +08004099 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004100 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004101 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004102 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004103 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004104 dump += INDENT2 "Windows:\n";
4105 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004106 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004107 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108
Arthur Hungb92218b2018-08-14 12:00:21 +08004109 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004110 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004111 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4112 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004113 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004114 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004115 i, windowInfo->name.c_str(), windowInfo->displayId,
4116 windowInfo->portalToDisplayId,
4117 toString(windowInfo->paused),
4118 toString(windowInfo->hasFocus),
4119 toString(windowInfo->hasWallpaper),
4120 toString(windowInfo->visible),
4121 toString(windowInfo->canReceiveKeys),
4122 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004123 windowInfo->layoutParamsType, windowInfo->frameLeft,
4124 windowInfo->frameTop, windowInfo->frameRight,
4125 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4126 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004127 dumpRegion(dump, windowInfo->touchableRegion);
4128 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004129 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4130 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004131 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004132 ns2ms(windowInfo->dispatchingTimeout));
Arthur Hungb92218b2018-08-14 12:00:21 +08004133 }
4134 } else {
4135 dump += INDENT2 "Windows: <none>\n";
4136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 }
4138 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004139 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 }
4141
Michael Wright3dd60e22019-03-27 22:06:44 +00004142 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004143 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004144 const std::vector<Monitor>& monitors = it.second;
4145 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4146 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004147 }
4148 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004149 const std::vector<Monitor>& monitors = it.second;
4150 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4151 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004152 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004154 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 }
4156
4157 nsecs_t currentTime = now();
4158
4159 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004160 if (!mRecentQueue.empty()) {
4161 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4162 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004163 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004165 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 }
4167 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004168 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 }
4170
4171 // Dump event currently being dispatched.
4172 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004173 dump += INDENT "PendingEvent:\n";
4174 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004176 dump += StringPrintf(", age=%" PRId64 "ms\n",
4177 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004179 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 }
4181
4182 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004183 if (!mInboundQueue.empty()) {
4184 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4185 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004186 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004188 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 }
4190 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004191 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 }
4193
Michael Wright78f24442014-08-06 15:55:28 -07004194 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004195 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07004196 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
4197 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
4198 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004199 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
4200 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004201 }
4202 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004203 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004204 }
4205
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004206 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004207 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004208 for (const auto& pair : mConnectionsByFd) {
4209 const sp<Connection>& connection = pair.second;
4210 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
4211 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
4212 pair.first, connection->getInputChannelName().c_str(),
4213 connection->getWindowName().c_str(), connection->getStatusLabel(),
4214 toString(connection->monitor),
4215 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004217 if (!connection->outboundQueue.empty()) {
4218 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4219 connection->outboundQueue.size());
4220 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 dump.append(INDENT4);
4222 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004223 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4224 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004225 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004226 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 }
4228 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004229 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230 }
4231
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004232 if (!connection->waitQueue.empty()) {
4233 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4234 connection->waitQueue.size());
4235 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004236 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004238 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004239 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004240 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004241 ns2ms(currentTime - entry->eventEntry->eventTime),
4242 ns2ms(currentTime - entry->deliveryTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 }
4244 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004245 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246 }
4247 }
4248 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004249 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 }
4251
4252 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004253 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4254 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004256 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 }
4258
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004259 dump += INDENT "Configuration:\n";
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004260 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4261 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4262 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263}
4264
Michael Wright3dd60e22019-03-27 22:06:44 +00004265void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4266 const size_t numMonitors = monitors.size();
4267 for (size_t i = 0; i < numMonitors; i++) {
4268 const Monitor& monitor = monitors[i];
4269 const sp<InputChannel>& channel = monitor.inputChannel;
4270 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4271 dump += "\n";
4272 }
4273}
4274
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004275status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004277 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278#endif
4279
4280 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004281 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004282 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004283 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004285 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 return BAD_VALUE;
4287 }
4288
Garfield Tan1c7bc862020-01-28 13:24:04 -08004289 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290
4291 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004292 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004293 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4296 } // release lock
4297
4298 // Wake the looper because some connections have changed.
4299 mLooper->wake();
4300 return OK;
4301}
4302
Michael Wright3dd60e22019-03-27 22:06:44 +00004303status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004304 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004305 { // acquire lock
4306 std::scoped_lock _l(mLock);
4307
4308 if (displayId < 0) {
4309 ALOGW("Attempted to register input monitor without a specified display.");
4310 return BAD_VALUE;
4311 }
4312
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004313 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004314 ALOGW("Attempted to register input monitor without an identifying token.");
4315 return BAD_VALUE;
4316 }
4317
Garfield Tan1c7bc862020-01-28 13:24:04 -08004318 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004319
4320 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004321 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004322 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004323
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004324 auto& monitorsByDisplay =
4325 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004326 monitorsByDisplay[displayId].emplace_back(inputChannel);
4327
4328 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004329 }
4330 // Wake the looper because some connections have changed.
4331 mLooper->wake();
4332 return OK;
4333}
4334
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4336#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004337 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338#endif
4339
4340 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004341 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342
4343 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4344 if (status) {
4345 return status;
4346 }
4347 } // release lock
4348
4349 // Wake the poll loop because removing the connection may have changed the current
4350 // synchronization state.
4351 mLooper->wake();
4352 return OK;
4353}
4354
4355status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004356 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004357 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004358 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004360 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 return BAD_VALUE;
4362 }
4363
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004364 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004365 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004366
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 if (connection->monitor) {
4368 removeMonitorChannelLocked(inputChannel);
4369 }
4370
4371 mLooper->removeFd(inputChannel->getFd());
4372
4373 nsecs_t currentTime = now();
4374 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4375
4376 connection->status = Connection::STATUS_ZOMBIE;
4377 return OK;
4378}
4379
4380void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004381 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4382 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4383}
4384
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004385void InputDispatcher::removeMonitorChannelLocked(
4386 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004387 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004388 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004389 std::vector<Monitor>& monitors = it->second;
4390 const size_t numMonitors = monitors.size();
4391 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004392 if (monitors[i].inputChannel == inputChannel) {
4393 monitors.erase(monitors.begin() + i);
4394 break;
4395 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004396 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004397 if (monitors.empty()) {
4398 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004399 } else {
4400 ++it;
4401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402 }
4403}
4404
Michael Wright3dd60e22019-03-27 22:06:44 +00004405status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4406 { // acquire lock
4407 std::scoped_lock _l(mLock);
4408 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4409
4410 if (!foundDisplayId) {
4411 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4412 return BAD_VALUE;
4413 }
4414 int32_t displayId = foundDisplayId.value();
4415
4416 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4417 if (stateIndex < 0) {
4418 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4419 return BAD_VALUE;
4420 }
4421
4422 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4423 std::optional<int32_t> foundDeviceId;
4424 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004425 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004426 foundDeviceId = state.deviceId;
4427 }
4428 }
4429 if (!foundDeviceId || !state.down) {
4430 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004431 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004432 return BAD_VALUE;
4433 }
4434 int32_t deviceId = foundDeviceId.value();
4435
4436 // Send cancel events to all the input channels we're stealing from.
4437 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004438 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004439 options.deviceId = deviceId;
4440 options.displayId = displayId;
4441 for (const TouchedWindow& window : state.windows) {
4442 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004443 if (channel != nullptr) {
4444 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4445 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004446 }
4447 // Then clear the current touch state so we stop dispatching to them as well.
4448 state.filterNonMonitors();
4449 }
4450 return OK;
4451}
4452
Michael Wright3dd60e22019-03-27 22:06:44 +00004453std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4454 const sp<IBinder>& token) {
4455 for (const auto& it : mGestureMonitorsByDisplay) {
4456 const std::vector<Monitor>& monitors = it.second;
4457 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004458 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004459 return it.first;
4460 }
4461 }
4462 }
4463 return std::nullopt;
4464}
4465
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004466sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004467 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004468 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004469 }
4470
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004471 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004472 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004473 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004474 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475 }
4476 }
Robert Carr4e670e52018-08-15 13:26:12 -07004477
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004478 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479}
4480
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004481void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
4482 removeByValue(mConnectionsByFd, connection);
4483}
4484
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004485void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4486 const sp<Connection>& connection, uint32_t seq,
4487 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004488 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4489 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490 commandEntry->connection = connection;
4491 commandEntry->eventTime = currentTime;
4492 commandEntry->seq = seq;
4493 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004494 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495}
4496
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004497void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4498 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004500 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004502 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4503 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004505 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506}
4507
chaviw0c06c6e2019-01-09 13:27:07 -08004508void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004509 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004510 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4511 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004512 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4513 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004514 commandEntry->oldToken = oldToken;
4515 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004516 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004517}
4518
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004519void InputDispatcher::onAnrLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004520 const sp<InputApplicationHandle>& applicationHandle,
4521 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4522 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4524 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4525 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004526 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4527 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4528 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529
4530 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004531 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532 struct tm tm;
4533 localtime_r(&t, &tm);
4534 char timestr[64];
4535 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004536 mLastAnrState.clear();
4537 mLastAnrState += INDENT "ANR:\n";
4538 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
4539 mLastAnrState +=
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004540 StringPrintf(INDENT2 "Window: %s\n",
4541 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004542 mLastAnrState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4543 mLastAnrState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4544 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason);
4545 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004547 std::unique_ptr<CommandEntry> commandEntry =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004548 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004550 commandEntry->inputChannel =
4551 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004553 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554}
4555
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004556void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 mLock.unlock();
4558
4559 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4560
4561 mLock.lock();
4562}
4563
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004564void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 sp<Connection> connection = commandEntry->connection;
4566
4567 if (connection->status != Connection::STATUS_ZOMBIE) {
4568 mLock.unlock();
4569
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004570 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571
4572 mLock.lock();
4573 }
4574}
4575
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004576void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004577 sp<IBinder> oldToken = commandEntry->oldToken;
4578 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004579 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004580 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004581 mLock.lock();
4582}
4583
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004584void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004585 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004586 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587 mLock.unlock();
4588
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004589 const nsecs_t timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004590 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591
4592 mLock.lock();
4593
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004594 resumeAfterTargetsNotReadyTimeoutLocked(timeoutExtension, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595}
4596
4597void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4598 CommandEntry* commandEntry) {
4599 KeyEntry* entry = commandEntry->keyEntry;
4600
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004601 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602
4603 mLock.unlock();
4604
Michael Wright2b3c3302018-03-02 17:19:13 +00004605 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004606 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004607 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004608 : nullptr;
4609 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004610 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4611 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004612 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614
4615 mLock.lock();
4616
4617 if (delay < 0) {
4618 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4619 } else if (!delay) {
4620 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4621 } else {
4622 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4623 entry->interceptKeyWakeupTime = now() + delay;
4624 }
4625 entry->release();
4626}
4627
chaviwfd6d3512019-03-25 13:23:49 -07004628void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4629 mLock.unlock();
4630 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4631 mLock.lock();
4632}
4633
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004634void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004636 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004638 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639
4640 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004641 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004642 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004643 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004645 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004646
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004647 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004648 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004649 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4650 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004651 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004652 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004653
4654 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004655 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004656 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4657 restartEvent =
4658 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004659 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004660 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4661 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4662 handled);
4663 } else {
4664 restartEvent = false;
4665 }
4666
4667 // Dequeue the event and start the next cycle.
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004668 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004669 // contents of the wait queue to have been drained, so we need to double-check
4670 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004671 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4672 if (dispatchEntryIt != connection->waitQueue.end()) {
4673 dispatchEntry = *dispatchEntryIt;
4674 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004675 traceWaitQueueLength(connection);
4676 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004677 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004678 traceOutboundQueueLength(connection);
4679 } else {
4680 releaseDispatchEntry(dispatchEntry);
4681 }
4682 }
4683
4684 // Start the next dispatch cycle for this connection.
4685 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686}
4687
4688bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004689 DispatchEntry* dispatchEntry,
4690 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004691 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004692 if (!handled) {
4693 // Report the key as unhandled, since the fallback was not handled.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004694 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004695 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004696 return false;
4697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004699 // Get the fallback key state.
4700 // Clear it out after dispatching the UP.
4701 int32_t originalKeyCode = keyEntry->keyCode;
4702 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4703 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4704 connection->inputState.removeFallbackKey(originalKeyCode);
4705 }
4706
4707 if (handled || !dispatchEntry->hasForegroundTarget()) {
4708 // If the application handles the original key for which we previously
4709 // generated a fallback or if the window is not a foreground window,
4710 // then cancel the associated fallback key, if any.
4711 if (fallbackKeyCode != -1) {
4712 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004714 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004715 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4716 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4717 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004719 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004720 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721
4722 mLock.unlock();
4723
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004724 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004725 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726
4727 mLock.lock();
4728
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004729 // Cancel the fallback key.
4730 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004732 "application handled the original non-fallback key "
4733 "or is no longer a foreground target, "
4734 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735 options.keyCode = fallbackKeyCode;
4736 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004738 connection->inputState.removeFallbackKey(originalKeyCode);
4739 }
4740 } else {
4741 // If the application did not handle a non-fallback key, first check
4742 // that we are in a good state to perform unhandled key event processing
4743 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004744 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004745 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004747 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004748 "since this is not an initial down. "
4749 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4750 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004752 return false;
4753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004755 // Dispatch the unhandled key to the policy.
4756#if DEBUG_OUTBOUND_EVENT_DETAILS
4757 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004758 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4759 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004760#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004761 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004762
4763 mLock.unlock();
4764
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004765 bool fallback =
4766 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4767 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004768
4769 mLock.lock();
4770
4771 if (connection->status != Connection::STATUS_NORMAL) {
4772 connection->inputState.removeFallbackKey(originalKeyCode);
4773 return false;
4774 }
4775
4776 // Latch the fallback keycode for this key on an initial down.
4777 // The fallback keycode cannot change at any other point in the lifecycle.
4778 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004779 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004780 fallbackKeyCode = event.getKeyCode();
4781 } else {
4782 fallbackKeyCode = AKEYCODE_UNKNOWN;
4783 }
4784 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4785 }
4786
4787 ALOG_ASSERT(fallbackKeyCode != -1);
4788
4789 // Cancel the fallback key if the policy decides not to send it anymore.
4790 // We will continue to dispatch the key to the policy but we will no
4791 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004792 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4793 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004794#if DEBUG_OUTBOUND_EVENT_DETAILS
4795 if (fallback) {
4796 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004797 "as a fallback for %d, but on the DOWN it had requested "
4798 "to send %d instead. Fallback canceled.",
4799 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004800 } else {
4801 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004802 "but on the DOWN it had requested to send %d. "
4803 "Fallback canceled.",
4804 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004805 }
4806#endif
4807
4808 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4809 "canceling fallback, policy no longer desires it");
4810 options.keyCode = fallbackKeyCode;
4811 synthesizeCancelationEventsForConnectionLocked(connection, options);
4812
4813 fallback = false;
4814 fallbackKeyCode = AKEYCODE_UNKNOWN;
4815 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004816 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004817 }
4818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819
4820#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004821 {
4822 std::string msg;
4823 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4824 connection->inputState.getFallbackKeys();
4825 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004826 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004828 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004829 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004830 }
4831#endif
4832
4833 if (fallback) {
4834 // Restart the dispatch cycle using the fallback key.
4835 keyEntry->eventTime = event.getEventTime();
4836 keyEntry->deviceId = event.getDeviceId();
4837 keyEntry->source = event.getSource();
4838 keyEntry->displayId = event.getDisplayId();
4839 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4840 keyEntry->keyCode = fallbackKeyCode;
4841 keyEntry->scanCode = event.getScanCode();
4842 keyEntry->metaState = event.getMetaState();
4843 keyEntry->repeatCount = event.getRepeatCount();
4844 keyEntry->downTime = event.getDownTime();
4845 keyEntry->syntheticRepeat = false;
4846
4847#if DEBUG_OUTBOUND_EVENT_DETAILS
4848 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004849 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4850 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004851#endif
4852 return true; // restart the event
4853 } else {
4854#if DEBUG_OUTBOUND_EVENT_DETAILS
4855 ALOGD("Unhandled key event: No fallback key.");
4856#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004857
4858 // Report the key as unhandled, since there is no fallback key.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004859 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 }
4861 }
4862 return false;
4863}
4864
4865bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004866 DispatchEntry* dispatchEntry,
4867 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 return false;
4869}
4870
4871void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4872 mLock.unlock();
4873
4874 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4875
4876 mLock.lock();
4877}
4878
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004879KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4880 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004881 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08004882 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
4883 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004884 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885}
4886
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004887void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
4888 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 // TODO Write some statistics about how long we spend waiting.
4890}
4891
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004892/**
4893 * Report the touch event latency to the statsd server.
4894 * Input events are reported for statistics if:
4895 * - This is a touchscreen event
4896 * - InputFilter is not enabled
4897 * - Event is not injected or synthesized
4898 *
4899 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4900 * from getting aggregated with the "old" data.
4901 */
4902void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4903 REQUIRES(mLock) {
4904 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4905 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4906 if (!reportForStatistics) {
4907 return;
4908 }
4909
4910 if (mTouchStatistics.shouldReport()) {
4911 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4912 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4913 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4914 mTouchStatistics.reset();
4915 }
4916 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4917 mTouchStatistics.addValue(latencyMicros);
4918}
4919
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920void InputDispatcher::traceInboundQueueLengthLocked() {
4921 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004922 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923 }
4924}
4925
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004926void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927 if (ATRACE_ENABLED()) {
4928 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004929 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004930 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004931 }
4932}
4933
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004934void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935 if (ATRACE_ENABLED()) {
4936 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004937 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004938 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939 }
4940}
4941
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004942void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004943 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004945 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946 dumpDispatchStateLocked(dump);
4947
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004948 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004949 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004950 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951 }
4952}
4953
4954void InputDispatcher::monitor() {
4955 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004956 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004957 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004958 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959}
4960
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004961/**
4962 * Wake up the dispatcher and wait until it processes all events and commands.
4963 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4964 * this method can be safely called from any thread, as long as you've ensured that
4965 * the work you are interested in completing has already been queued.
4966 */
4967bool InputDispatcher::waitForIdle() {
4968 /**
4969 * Timeout should represent the longest possible time that a device might spend processing
4970 * events and commands.
4971 */
4972 constexpr std::chrono::duration TIMEOUT = 100ms;
4973 std::unique_lock lock(mLock);
4974 mLooper->wake();
4975 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4976 return result == std::cv_status::no_timeout;
4977}
4978
Garfield Tane84e6f92019-08-29 17:28:41 -07004979} // namespace android::inputdispatcher