blob: 92f1750ea7ce6772be86dc10f7486a5be25451d7 [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.
Michael Wright2b3c3302018-03-02 17:19:13 +000081constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Amount of time to allow for all pending events to be processed when an app switch
84// key is on the way. This is used to preempt input dispatch and drop input events
85// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000086constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow for an event to be dispatched (measured since its eventTime)
89// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92// Amount of time to allow touch events to be streamed out to a connection before requiring
93// that the first event be finished. This value extends the ANR timeout by the specified
94// amount. For example, if streaming is allowed to get ahead by one second relative to the
95// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000096constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
98// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000099constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
100
101// Log a warning when an interception call takes longer than this to process.
102constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
104// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
106
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107static inline nsecs_t now() {
108 return systemTime(SYSTEM_TIME_MONOTONIC);
109}
110
111static inline const char* toString(bool value) {
112 return value ? "true" : "false";
113}
114
115static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700116 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
117 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118}
119
120static bool isValidKeyAction(int32_t action) {
121 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700122 case AKEY_EVENT_ACTION_DOWN:
123 case AKEY_EVENT_ACTION_UP:
124 return true;
125 default:
126 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127 }
128}
129
130static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 ALOGE("Key event has invalid action code 0x%x", action);
133 return false;
134 }
135 return true;
136}
137
Michael Wright7b159c92015-05-14 14:48:03 +0100138static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 case AMOTION_EVENT_ACTION_DOWN:
141 case AMOTION_EVENT_ACTION_UP:
142 case AMOTION_EVENT_ACTION_CANCEL:
143 case AMOTION_EVENT_ACTION_MOVE:
144 case AMOTION_EVENT_ACTION_OUTSIDE:
145 case AMOTION_EVENT_ACTION_HOVER_ENTER:
146 case AMOTION_EVENT_ACTION_HOVER_MOVE:
147 case AMOTION_EVENT_ACTION_HOVER_EXIT:
148 case AMOTION_EVENT_ACTION_SCROLL:
149 return true;
150 case AMOTION_EVENT_ACTION_POINTER_DOWN:
151 case AMOTION_EVENT_ACTION_POINTER_UP: {
152 int32_t index = getMotionEventActionPointerIndex(action);
153 return index >= 0 && index < pointerCount;
154 }
155 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
156 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
157 return actionButton != 0;
158 default:
159 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160 }
161}
162
Michael Wright7b159c92015-05-14 14:48:03 +0100163static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 const PointerProperties* pointerProperties) {
165 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 ALOGE("Motion event has invalid action code 0x%x", action);
167 return false;
168 }
169 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000170 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700171 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 return false;
173 }
174 BitSet32 pointerIdBits;
175 for (size_t i = 0; i < pointerCount; i++) {
176 int32_t id = pointerProperties[i].id;
177 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
179 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 return false;
181 }
182 if (pointerIdBits.hasBit(id)) {
183 ALOGE("Motion event has duplicate pointer id %d", id);
184 return false;
185 }
186 pointerIdBits.markBit(id);
187 }
188 return true;
189}
190
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800191static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800193 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 return;
195 }
196
197 bool first = true;
198 Region::const_iterator cur = region.begin();
199 Region::const_iterator const tail = region.end();
200 while (cur != tail) {
201 if (first) {
202 first = false;
203 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800204 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800206 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 cur++;
208 }
209}
210
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700211/**
212 * Find the entry in std::unordered_map by key, and return it.
213 * If the entry is not found, return a default constructed entry.
214 *
215 * Useful when the entries are vectors, since an empty vector will be returned
216 * if the entry is not found.
217 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
218 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700219template <typename K, typename V>
220static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700221 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700222 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800223}
224
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700225/**
226 * Find the entry in std::unordered_map by value, and remove it.
227 * If more than one entry has the same value, then all matching
228 * key-value pairs will be removed.
229 *
230 * Return true if at least one value has been removed.
231 */
232template <typename K, typename V>
233static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
234 bool removed = false;
235 for (auto it = map.begin(); it != map.end();) {
236 if (it->second == value) {
237 it = map.erase(it);
238 removed = true;
239 } else {
240 it++;
241 }
242 }
243 return removed;
244}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245
chaviwaf87b3e2019-10-01 16:59:28 -0700246static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
247 if (first == second) {
248 return true;
249 }
250
251 if (first == nullptr || second == nullptr) {
252 return false;
253 }
254
255 return first->getToken() == second->getToken();
256}
257
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800258static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
259 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
260}
261
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000262static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
263 EventEntry* eventEntry,
264 int32_t inputTargetFlags) {
265 if (inputTarget.useDefaultPointerInfo()) {
266 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
267 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
268 inputTargetFlags, pointerInfo.xOffset,
269 pointerInfo.yOffset, inputTarget.globalScaleFactor,
270 pointerInfo.windowXScale, pointerInfo.windowYScale);
271 }
272
273 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
274 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
275
276 PointerCoords pointerCoords[motionEntry.pointerCount];
277
278 // Use the first pointer information to normalize all other pointers. This could be any pointer
279 // as long as all other pointers are normalized to the same value and the final DispatchEntry
280 // uses the offset and scale for the normalized pointer.
281 const PointerInfo& firstPointerInfo =
282 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
283
284 // Iterate through all pointers in the event to normalize against the first.
285 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
286 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
287 uint32_t pointerId = uint32_t(pointerProperties.id);
288 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
289
290 // The scale factor is the ratio of the current pointers scale to the normalized scale.
291 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
292 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
293
294 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
295 // First apply the current pointers offset to set the window at 0,0
296 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
297 // Next scale the coordinates.
298 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
299 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
300 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
301 -firstPointerInfo.yOffset);
302 }
303
304 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800305 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000306 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
307 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
308 motionEntry.metaState, motionEntry.buttonState,
309 motionEntry.classification, motionEntry.edgeFlags,
310 motionEntry.xPrecision, motionEntry.yPrecision,
311 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
312 motionEntry.downTime, motionEntry.pointerCount,
313 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
314 0 /* yOffset */);
315
316 if (motionEntry.injectionState) {
317 combinedMotionEntry->injectionState = motionEntry.injectionState;
318 combinedMotionEntry->injectionState->refCount += 1;
319 }
320
321 std::unique_ptr<DispatchEntry> dispatchEntry =
322 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
323 inputTargetFlags, firstPointerInfo.xOffset,
324 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
325 firstPointerInfo.windowXScale,
326 firstPointerInfo.windowYScale);
327 combinedMotionEntry->release();
328 return dispatchEntry;
329}
330
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700331static void addGestureMonitors(const std::vector<Monitor>& monitors,
332 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
333 float yOffset = 0) {
334 if (monitors.empty()) {
335 return;
336 }
337 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
338 for (const Monitor& monitor : monitors) {
339 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
340 }
341}
342
Gang Wang342c9272020-01-13 13:15:04 -0500343static std::array<uint8_t, 128> getRandomKey() {
344 std::array<uint8_t, 128> key;
345 if (RAND_bytes(key.data(), key.size()) != 1) {
346 LOG_ALWAYS_FATAL("Can't generate HMAC key");
347 }
348 return key;
349}
350
351// --- HmacKeyManager ---
352
353HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
354
355std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
356 size_t size;
357 switch (event.type) {
358 case VerifiedInputEvent::Type::KEY: {
359 size = sizeof(VerifiedKeyEvent);
360 break;
361 }
362 case VerifiedInputEvent::Type::MOTION: {
363 size = sizeof(VerifiedMotionEvent);
364 break;
365 }
366 }
Gang Wang342c9272020-01-13 13:15:04 -0500367 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700368 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500369}
370
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700371std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500372 // SHA256 always generates 32-bytes result
373 std::array<uint8_t, 32> hash;
374 unsigned int hashLen = 0;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700375 uint8_t* result =
376 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500377 if (result == nullptr) {
378 ALOGE("Could not sign the data using HMAC");
379 return INVALID_HMAC;
380 }
381
382 if (hashLen != hash.size()) {
383 ALOGE("HMAC-SHA256 has unexpected length");
384 return INVALID_HMAC;
385 }
386
387 return hash;
388}
389
Michael Wrightd02c5b62014-02-10 15:10:22 -0800390// --- InputDispatcher ---
391
Garfield Tan00f511d2019-06-12 16:55:40 -0700392InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
393 : mPolicy(policy),
394 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700395 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800396 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700397 mAppSwitchSawKeyDown(false),
398 mAppSwitchDueTime(LONG_LONG_MAX),
399 mNextUnblockedEvent(nullptr),
400 mDispatchEnabled(false),
401 mDispatchFrozen(false),
402 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800403 // mInTouchMode will be initialized by the WindowManager to the default device config.
404 // To avoid leaking stack in case that call never comes, and for tests,
405 // initialize it here anyways.
406 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700407 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
408 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800410 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411
Yi Kong9b14ac62018-07-17 13:48:38 -0700412 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413
414 policy->getDispatcherConfiguration(&mConfig);
415}
416
417InputDispatcher::~InputDispatcher() {
418 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800419 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800420
421 resetKeyRepeatLocked();
422 releasePendingEventLocked();
423 drainInboundQueueLocked();
424 }
425
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700426 while (!mConnectionsByFd.empty()) {
427 sp<Connection> connection = mConnectionsByFd.begin()->second;
428 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800429 }
430}
431
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700432status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700433 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700434 return ALREADY_EXISTS;
435 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700436 mThread = std::make_unique<InputThread>(
437 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
438 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700439}
440
441status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700442 if (mThread && mThread->isCallingThread()) {
443 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700444 return INVALID_OPERATION;
445 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700446 mThread.reset();
447 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700448}
449
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450void InputDispatcher::dispatchOnce() {
451 nsecs_t nextWakeupTime = LONG_LONG_MAX;
452 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800453 std::scoped_lock _l(mLock);
454 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455
456 // Run a dispatch loop if there are no pending commands.
457 // The dispatch loop might enqueue commands to run afterwards.
458 if (!haveCommandsLocked()) {
459 dispatchOnceInnerLocked(&nextWakeupTime);
460 }
461
462 // Run all pending commands if there are any.
463 // If any commands were run then force the next poll to wake up immediately.
464 if (runCommandsLockedInterruptible()) {
465 nextWakeupTime = LONG_LONG_MIN;
466 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800467
468 // We are about to enter an infinitely long sleep, because we have no commands or
469 // pending or queued events
470 if (nextWakeupTime == LONG_LONG_MAX) {
471 mDispatcherEnteredIdle.notify_all();
472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800473 } // release lock
474
475 // Wait for callback or timeout or wake. (make sure we round up, not down)
476 nsecs_t currentTime = now();
477 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
478 mLooper->pollOnce(timeoutMillis);
479}
480
481void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
482 nsecs_t currentTime = now();
483
Jeff Browndc5992e2014-04-11 01:27:26 -0700484 // Reset the key repeat timer whenever normal dispatch is suspended while the
485 // device is in a non-interactive state. This is to ensure that we abort a key
486 // repeat if the device is just coming out of sleep.
487 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488 resetKeyRepeatLocked();
489 }
490
491 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
492 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100493 if (DEBUG_FOCUS) {
494 ALOGD("Dispatch frozen. Waiting some more.");
495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496 return;
497 }
498
499 // Optimize latency of app switches.
500 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
501 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
502 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
503 if (mAppSwitchDueTime < *nextWakeupTime) {
504 *nextWakeupTime = mAppSwitchDueTime;
505 }
506
507 // Ready to start a new event.
508 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700509 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700510 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 if (isAppSwitchDue) {
512 // The inbound queue is empty so the app switch key we were waiting
513 // for will never arrive. Stop waiting for it.
514 resetPendingAppSwitchLocked(false);
515 isAppSwitchDue = false;
516 }
517
518 // Synthesize a key repeat if appropriate.
519 if (mKeyRepeatState.lastKeyEntry) {
520 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
521 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
522 } else {
523 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
524 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
525 }
526 }
527 }
528
529 // Nothing to do if there is no pending event.
530 if (!mPendingEvent) {
531 return;
532 }
533 } else {
534 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700535 mPendingEvent = mInboundQueue.front();
536 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537 traceInboundQueueLengthLocked();
538 }
539
540 // Poke user activity for this event.
541 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700542 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 }
544
545 // Get ready to dispatch the event.
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700546 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547 }
548
549 // Now we have an event to dispatch.
550 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700551 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700553 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700555 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700557 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 }
559
560 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700561 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 }
563
564 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700565 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700566 ConfigurationChangedEntry* typedEntry =
567 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
568 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700569 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700570 break;
571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700573 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700574 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
575 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700576 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700577 break;
578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100580 case EventEntry::Type::FOCUS: {
581 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
582 dispatchFocusLocked(currentTime, typedEntry);
583 done = true;
584 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
585 break;
586 }
587
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700588 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700589 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
590 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700591 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700592 resetPendingAppSwitchLocked(true);
593 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700594 } else if (dropReason == DropReason::NOT_DROPPED) {
595 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700596 }
597 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700598 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700599 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700600 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700601 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
602 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700603 }
604 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
605 break;
606 }
607
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700608 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700609 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700610 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
611 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700613 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700614 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700615 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700616 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
617 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700618 }
619 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
620 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 }
623
624 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700625 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700626 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 }
Michael Wright3a981722015-06-10 15:26:13 +0100628 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629
630 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700631 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 }
633}
634
635bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700636 bool needWake = mInboundQueue.empty();
637 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800638 traceInboundQueueLengthLocked();
639
640 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700641 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700642 // Optimize app switch latency.
643 // If the application takes too long to catch up then we drop all events preceding
644 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700645 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700646 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700647 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700648 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700649 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700650 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700652 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700654 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700655 mAppSwitchSawKeyDown = false;
656 needWake = true;
657 }
658 }
659 }
660 break;
661 }
662
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700663 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700664 // Optimize case where the current application is unresponsive and the user
665 // decides to touch a window in a different application.
666 // If the application takes too long to catch up then we drop all events preceding
667 // the touch into the other window.
668 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
669 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
670 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
671 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
672 mInputTargetWaitApplicationToken != nullptr) {
673 int32_t displayId = motionEntry->displayId;
674 int32_t x =
675 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
676 int32_t y =
677 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
678 sp<InputWindowHandle> touchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700679 findTouchedWindowAtLocked(displayId, x, y, nullptr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 if (touchedWindowHandle != nullptr &&
681 touchedWindowHandle->getApplicationToken() !=
682 mInputTargetWaitApplicationToken) {
683 // User touched a different application than the one we are waiting on.
684 // Flag the event, and start pruning the input queue.
685 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 needWake = true;
687 }
688 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700689 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700691 case EventEntry::Type::CONFIGURATION_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100692 case EventEntry::Type::DEVICE_RESET:
693 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700694 // nothing to do
695 break;
696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 }
698
699 return needWake;
700}
701
702void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
703 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700704 mRecentQueue.push_back(entry);
705 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
706 mRecentQueue.front()->release();
707 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 }
709}
710
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700711sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700712 int32_t y, TouchState* touchState,
713 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700714 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700715 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
716 LOG_ALWAYS_FATAL(
717 "Must provide a valid touch state if adding portal windows or outside targets");
718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800720 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
721 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722 const InputWindowInfo* windowInfo = windowHandle->getInfo();
723 if (windowInfo->displayId == displayId) {
724 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725
726 if (windowInfo->visible) {
727 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700728 bool isTouchModal = (flags &
729 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
730 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800732 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700733 if (portalToDisplayId != ADISPLAY_ID_NONE &&
734 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800735 if (addPortalWindows) {
736 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700737 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800738 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700739 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700740 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 // Found window.
743 return windowHandle;
744 }
745 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800746
747 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700748 touchState->addOrUpdateWindow(windowHandle,
749 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
750 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 }
754 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700755 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756}
757
Garfield Tane84e6f92019-08-29 17:28:41 -0700758std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700759 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000760 std::vector<TouchedMonitor> touchedMonitors;
761
762 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
763 addGestureMonitors(monitors, touchedMonitors);
764 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
765 const InputWindowInfo* windowInfo = portalWindow->getInfo();
766 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700767 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
768 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000769 }
770 return touchedMonitors;
771}
772
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700773void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 const char* reason;
775 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700776 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700778 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700780 reason = "inbound event was dropped because the policy consumed it";
781 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700782 case DropReason::DISABLED:
783 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700784 ALOGI("Dropped event because input dispatch is disabled.");
785 }
786 reason = "inbound event was dropped because input dispatch is disabled";
787 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700788 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700789 ALOGI("Dropped event because of pending overdue app switch.");
790 reason = "inbound event was dropped because of pending overdue app switch";
791 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700792 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700793 ALOGI("Dropped event because the current application is not responding and the user "
794 "has started interacting with a different application.");
795 reason = "inbound event was dropped because the current application is not responding "
796 "and the user has started interacting with a different application";
797 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700798 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700799 ALOGI("Dropped event because it is stale.");
800 reason = "inbound event was dropped because it is stale";
801 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700802 case DropReason::NOT_DROPPED: {
803 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700804 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 }
807
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700808 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700809 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
811 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700814 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700815 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
816 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700817 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
818 synthesizeCancelationEventsForAllConnectionsLocked(options);
819 } else {
820 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
821 synthesizeCancelationEventsForAllConnectionsLocked(options);
822 }
823 break;
824 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100825 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700826 case EventEntry::Type::CONFIGURATION_CHANGED:
827 case EventEntry::Type::DEVICE_RESET: {
828 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
829 break;
830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831 }
832}
833
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800834static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
836 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837}
838
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700839bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
840 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
841 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
842 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843}
844
845bool InputDispatcher::isAppSwitchPendingLocked() {
846 return mAppSwitchDueTime != LONG_LONG_MAX;
847}
848
849void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
850 mAppSwitchDueTime = LONG_LONG_MAX;
851
852#if DEBUG_APP_SWITCH
853 if (handled) {
854 ALOGD("App switch has arrived.");
855 } else {
856 ALOGD("App switch was abandoned.");
857 }
858#endif
859}
860
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700862 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863}
864
865bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700866 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 return false;
868 }
869
870 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700871 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700872 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700874 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875
876 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700877 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 return true;
879}
880
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700881void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
882 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883}
884
885void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700886 while (!mInboundQueue.empty()) {
887 EventEntry* entry = mInboundQueue.front();
888 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 releaseInboundEventLocked(entry);
890 }
891 traceInboundQueueLengthLocked();
892}
893
894void InputDispatcher::releasePendingEventLocked() {
895 if (mPendingEvent) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700896 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700898 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 }
900}
901
902void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
903 InjectionState* injectionState = entry->injectionState;
904 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
905#if DEBUG_DISPATCH_CYCLE
906 ALOGD("Injected inbound event was dropped.");
907#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800908 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 }
910 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700911 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 }
913 addRecentEventLocked(entry);
914 entry->release();
915}
916
917void InputDispatcher::resetKeyRepeatLocked() {
918 if (mKeyRepeatState.lastKeyEntry) {
919 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700920 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921 }
922}
923
Garfield Tane84e6f92019-08-29 17:28:41 -0700924KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
926
927 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700928 uint32_t policyFlags = entry->policyFlags &
929 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 if (entry->refCount == 1) {
931 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800932 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 entry->eventTime = currentTime;
934 entry->policyFlags = policyFlags;
935 entry->repeatCount += 1;
936 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700937 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800938 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800939 entry->displayId, policyFlags, entry->action, entry->flags,
940 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700941 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942
943 mKeyRepeatState.lastKeyEntry = newEntry;
944 entry->release();
945
946 entry = newEntry;
947 }
948 entry->syntheticRepeat = true;
949
950 // Increment reference count since we keep a reference to the event in
951 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
952 entry->refCount += 1;
953
954 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
955 return entry;
956}
957
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700958bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
959 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700961 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962#endif
963
964 // Reset key repeating in case a keyboard device was added or removed or something.
965 resetKeyRepeatLocked();
966
967 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700968 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
969 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700971 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 return true;
973}
974
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700975bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700977 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700978 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979#endif
980
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 options.deviceId = entry->deviceId;
983 synthesizeCancelationEventsForAllConnectionsLocked(options);
984 return true;
985}
986
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100987void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
988 FocusEntry* focusEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800989 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100990 enqueueInboundEventLocked(focusEntry);
991}
992
993void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
994 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
995 if (channel == nullptr) {
996 return; // Window has gone away
997 }
998 InputTarget target;
999 target.inputChannel = channel;
1000 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1001 entry->dispatchInProgress = true;
1002
1003 dispatchEventLocked(currentTime, entry, {target});
1004}
1005
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001007 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001009 if (!entry->dispatchInProgress) {
1010 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1011 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1012 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1013 if (mKeyRepeatState.lastKeyEntry &&
1014 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 // We have seen two identical key downs in a row which indicates that the device
1016 // driver is automatically generating key repeats itself. We take note of the
1017 // repeat here, but we disable our own next key repeat timer since it is clear that
1018 // we will not need to synthesize key repeats ourselves.
1019 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1020 resetKeyRepeatLocked();
1021 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1022 } else {
1023 // Not a repeat. Save key down state in case we do see a repeat later.
1024 resetKeyRepeatLocked();
1025 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1026 }
1027 mKeyRepeatState.lastKeyEntry = entry;
1028 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001029 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 resetKeyRepeatLocked();
1031 }
1032
1033 if (entry->repeatCount == 1) {
1034 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1035 } else {
1036 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1037 }
1038
1039 entry->dispatchInProgress = true;
1040
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001041 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 }
1043
1044 // Handle case where the policy asked us to try again later last time.
1045 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1046 if (currentTime < entry->interceptKeyWakeupTime) {
1047 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1048 *nextWakeupTime = entry->interceptKeyWakeupTime;
1049 }
1050 return false; // wait until next wakeup
1051 }
1052 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1053 entry->interceptKeyWakeupTime = 0;
1054 }
1055
1056 // Give the policy a chance to intercept the key.
1057 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1058 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001059 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001060 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001061 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001062 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001063 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001064 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 }
1066 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001067 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 entry->refCount += 1;
1069 return false; // wait for the command to run
1070 } else {
1071 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1072 }
1073 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001074 if (*dropReason == DropReason::NOT_DROPPED) {
1075 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 }
1077 }
1078
1079 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001080 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001081 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001082 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001083 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001084 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 return true;
1086 }
1087
1088 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001089 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001090 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001091 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1093 return false;
1094 }
1095
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001096 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1098 return true;
1099 }
1100
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001101 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001102 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001103
1104 // Dispatch the key.
1105 dispatchEventLocked(currentTime, entry, inputTargets);
1106 return true;
1107}
1108
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001109void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001111 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001112 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1113 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001114 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1115 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1116 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117#endif
1118}
1119
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001120bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1121 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001122 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001124 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 entry->dispatchInProgress = true;
1126
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001127 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128 }
1129
1130 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001131 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001132 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001133 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001134 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135 return true;
1136 }
1137
1138 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1139
1140 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001141 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142
1143 bool conflictingPointerActions = false;
1144 int32_t injectionResult;
1145 if (isPointerEvent) {
1146 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001147 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001148 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001149 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150 } else {
1151 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001152 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001153 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 }
1155 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1156 return false;
1157 }
1158
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001159 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001161 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001162 CancelationOptions::Mode mode(isPointerEvent
1163 ? CancelationOptions::CANCEL_POINTER_EVENTS
1164 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001165 CancelationOptions options(mode, "input event injection failed");
1166 synthesizeCancelationEventsForMonitorsLocked(options);
1167 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 return true;
1169 }
1170
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001171 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001172 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001174 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001175 std::unordered_map<int32_t, TouchState>::iterator it =
1176 mTouchStatesByDisplay.find(entry->displayId);
1177 if (it != mTouchStatesByDisplay.end()) {
1178 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001179 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001180 // The event has gone through these portal windows, so we add monitoring targets of
1181 // the corresponding displays as well.
1182 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001183 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001184 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001185 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001186 }
1187 }
1188 }
1189 }
1190
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 // Dispatch the motion.
1192 if (conflictingPointerActions) {
1193 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001194 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195 synthesizeCancelationEventsForAllConnectionsLocked(options);
1196 }
1197 dispatchEventLocked(currentTime, entry, inputTargets);
1198 return true;
1199}
1200
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001201void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001203 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001204 ", policyFlags=0x%x, "
1205 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1206 "metaState=0x%x, buttonState=0x%x,"
1207 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001208 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1209 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1210 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001212 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 "x=%f, y=%f, pressure=%f, size=%f, "
1215 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1216 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001217 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1218 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1219 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1220 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1221 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1222 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1223 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1224 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1225 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1226 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 }
1228#endif
1229}
1230
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001231void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1232 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001233 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234#if DEBUG_DISPATCH_CYCLE
1235 ALOGD("dispatchEventToCurrentInputTargets");
1236#endif
1237
1238 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1239
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001240 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001242 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001243 sp<Connection> connection =
1244 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001245 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001246 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001248 if (DEBUG_FOCUS) {
1249 ALOGD("Dropping event delivery to target with channel '%s' because it "
1250 "is no longer registered with the input dispatcher.",
1251 inputTarget.inputChannel->getName().c_str());
1252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 }
1254 }
1255}
1256
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001257int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001258 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001260 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001261 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001263 if (DEBUG_FOCUS) {
1264 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1267 mInputTargetWaitStartTime = currentTime;
1268 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1269 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001270 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 }
1272 } else {
1273 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001274 ALOGI("Waiting for application to become ready for input: %s. Reason: %s",
1275 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001277 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001279 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001280 timeout =
1281 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282 } else {
1283 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1284 }
1285
1286 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1287 mInputTargetWaitStartTime = currentTime;
1288 mInputTargetWaitTimeoutTime = currentTime + timeout;
1289 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001290 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291
Yi Kong9b14ac62018-07-17 13:48:38 -07001292 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001293 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294 }
Robert Carr740167f2018-10-11 19:03:41 -07001295 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1296 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297 }
1298 }
1299 }
1300
1301 if (mInputTargetWaitTimeoutExpired) {
1302 return INPUT_EVENT_INJECTION_TIMED_OUT;
1303 }
1304
1305 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001306 onAnrLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308
1309 // Force poll loop to wake up immediately on next iteration once we get the
1310 // ANR response back from the policy.
1311 *nextWakeupTime = LONG_LONG_MIN;
1312 return INPUT_EVENT_INJECTION_PENDING;
1313 } else {
1314 // Force poll loop to wake up when timeout is due.
1315 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1316 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1317 }
1318 return INPUT_EVENT_INJECTION_PENDING;
1319 }
1320}
1321
Robert Carr803535b2018-08-02 16:38:15 -07001322void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001323 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
1324 TouchState& state = pair.second;
Robert Carr803535b2018-08-02 16:38:15 -07001325 state.removeWindowByToken(token);
1326 }
1327}
1328
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001329void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001330 nsecs_t newTimeout, const sp<IBinder>& inputConnectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 if (newTimeout > 0) {
1332 // Extend the timeout.
1333 mInputTargetWaitTimeoutTime = now() + newTimeout;
1334 } else {
1335 // Give up.
1336 mInputTargetWaitTimeoutExpired = true;
1337
1338 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001339 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001340 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001341 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001343 if (connection->status == Connection::STATUS_NORMAL) {
1344 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1345 "application not responding");
1346 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347 }
1348 }
1349 }
1350}
1351
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001352nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1354 return currentTime - mInputTargetWaitStartTime;
1355 }
1356 return 0;
1357}
1358
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001359void InputDispatcher::resetAnrTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001360 if (DEBUG_FOCUS) {
1361 ALOGD("Resetting ANR timeouts.");
1362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363
1364 // Reset input target wait timeout.
1365 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001366 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367}
1368
Tiger Huang721e26f2018-07-24 22:26:19 +08001369/**
1370 * Get the display id that the given event should go to. If this event specifies a valid display id,
1371 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1372 * Focused display is the display that the user most recently interacted with.
1373 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001374int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001375 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001376 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001377 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001378 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1379 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001380 break;
1381 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001382 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001383 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1384 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001385 break;
1386 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001387 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001388 case EventEntry::Type::CONFIGURATION_CHANGED:
1389 case EventEntry::Type::DEVICE_RESET: {
1390 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001391 return ADISPLAY_ID_NONE;
1392 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001393 }
1394 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1395}
1396
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001399 std::vector<InputTarget>& inputTargets,
1400 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001402 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403
Tiger Huang721e26f2018-07-24 22:26:19 +08001404 int32_t displayId = getTargetDisplayId(entry);
1405 sp<InputWindowHandle> focusedWindowHandle =
1406 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1407 sp<InputApplicationHandle> focusedApplicationHandle =
1408 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1409
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 // If there is no currently focused window and no focused application
1411 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001412 if (focusedWindowHandle == nullptr) {
1413 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001414 injectionResult =
1415 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1416 nullptr, nextWakeupTime,
1417 "Waiting because no window has focus but there is "
1418 "a focused application that may eventually add a "
1419 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420 goto Unresponsive;
1421 }
1422
Arthur Hung3b413f22018-10-26 18:05:34 +08001423 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001424 "%" PRId32 ".",
1425 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1427 goto Failed;
1428 }
1429
1430 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001431 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1433 goto Failed;
1434 }
1435
Jeff Brownffb49772014-10-10 19:01:34 -07001436 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001437 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001438 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001439 injectionResult =
1440 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1441 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 goto Unresponsive;
1443 }
1444
1445 // Success! Output targets.
1446 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001447 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001448 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1449 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450
1451 // Done.
1452Failed:
1453Unresponsive:
1454 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001455 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001456 if (DEBUG_FOCUS) {
1457 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1458 "timeSpentWaitingForApplication=%0.1fms",
1459 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461 return injectionResult;
1462}
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
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001487 // Copy current touch state into tempTouchState.
1488 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1489 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001490 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001491 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001492 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1493 mTouchStatesByDisplay.find(displayId);
1494 if (oldStateIt != mTouchStatesByDisplay.end()) {
1495 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001496 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001497 }
1498
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001499 bool isSplit = tempTouchState.split;
1500 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1501 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1502 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001503 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1504 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1505 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1506 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1507 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001508 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 bool wrongDevice = false;
1510 if (newGesture) {
1511 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001512 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001513 ALOGI("Dropping event because a pointer for a different device is already down "
1514 "in display %" PRId32,
1515 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001516 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1518 switchedDevice = false;
1519 wrongDevice = true;
1520 goto Failed;
1521 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001522 tempTouchState.reset();
1523 tempTouchState.down = down;
1524 tempTouchState.deviceId = entry.deviceId;
1525 tempTouchState.source = entry.source;
1526 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001528 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001529 ALOGI("Dropping move event because a pointer for a different device is already active "
1530 "in display %" PRId32,
1531 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001532 // TODO: test multiple simultaneous input streams.
1533 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1534 switchedDevice = false;
1535 wrongDevice = true;
1536 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 }
1538
1539 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1540 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1541
Garfield Tan00f511d2019-06-12 16:55:40 -07001542 int32_t x;
1543 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001545 // Always dispatch mouse events to cursor position.
1546 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001547 x = int32_t(entry.xCursorPosition);
1548 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001549 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001550 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1551 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001552 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001553 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001554 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001555 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1556 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001557
1558 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001559 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001560 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001563 if (newTouchedWindowHandle != nullptr &&
1564 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001565 // New window supports splitting, but we should never split mouse events.
1566 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 } else if (isSplit) {
1568 // New window does not support splitting but we have already split events.
1569 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001570 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 }
1572
1573 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001574 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001576 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001577 }
1578
1579 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1580 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001581 "(%d, %d) in display %" PRId32 ".",
1582 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001583 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1584 goto Failed;
1585 }
1586
1587 if (newTouchedWindowHandle != nullptr) {
1588 // Set target flags.
1589 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1590 if (isSplit) {
1591 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001593 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1594 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1595 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1596 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1597 }
1598
1599 // Update hover state.
1600 if (isHoverAction) {
1601 newHoverWindowHandle = newTouchedWindowHandle;
1602 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1603 newHoverWindowHandle = mLastHoverWindowHandle;
1604 }
1605
1606 // Update the temporary touch state.
1607 BitSet32 pointerIds;
1608 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001609 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001610 pointerIds.markBit(pointerId);
1611 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001612 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 }
1614
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001615 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 } else {
1617 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1618
1619 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001620 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001621 if (DEBUG_FOCUS) {
1622 ALOGD("Dropping event because the pointer is not down or we previously "
1623 "dropped the pointer down event in display %" PRId32,
1624 displayId);
1625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1627 goto Failed;
1628 }
1629
1630 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001631 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001632 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001633 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1634 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635
1636 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001637 tempTouchState.getFirstForegroundWindowHandle();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001639 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001640 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1641 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001642 if (DEBUG_FOCUS) {
1643 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1644 oldTouchedWindowHandle->getName().c_str(),
1645 newTouchedWindowHandle->getName().c_str(), displayId);
1646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001648 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1649 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1650 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651
1652 // Make a slippery entrance into the new window.
1653 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1654 isSplit = true;
1655 }
1656
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001657 int32_t targetFlags =
1658 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 if (isSplit) {
1660 targetFlags |= InputTarget::FLAG_SPLIT;
1661 }
1662 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1663 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1664 }
1665
1666 BitSet32 pointerIds;
1667 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001668 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001670 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 }
1672 }
1673 }
1674
1675 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1676 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001677 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678#if DEBUG_HOVER
1679 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001680 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001682 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1683 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 }
1685
1686 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001687 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688#if DEBUG_HOVER
1689 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001690 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001692 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1693 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1694 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 }
1696 }
1697
1698 // Check permission to inject into all touched foreground windows and ensure there
1699 // is at least one touched foreground window.
1700 {
1701 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001702 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1704 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001705 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1707 injectionPermission = INJECTION_PERMISSION_DENIED;
1708 goto Failed;
1709 }
1710 }
1711 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001712 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001713 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001714 ALOGI("Dropping event because there is no touched foreground window in display "
1715 "%" PRId32 " or gesture monitor to receive it.",
1716 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1718 goto Failed;
1719 }
1720
1721 // Permission granted to injection into all touched foreground windows.
1722 injectionPermission = INJECTION_PERMISSION_GRANTED;
1723 }
1724
1725 // Check whether windows listening for outside touches are owned by the same UID. If it is
1726 // set the policy flag that we will not reveal coordinate information to this window.
1727 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1728 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001729 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001730 if (foregroundWindowHandle) {
1731 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001732 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001733 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1734 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1735 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001736 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1737 InputTarget::FLAG_ZERO_COORDS,
1738 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001739 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 }
1741 }
1742 }
1743 }
1744
1745 // Ensure all touched foreground windows are ready for new input.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001746 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001748 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001749 std::string reason =
1750 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1751 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001752 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001753 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1754 touchedWindow.windowHandle,
1755 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 goto Unresponsive;
1757 }
1758 }
1759 }
1760
1761 // If this is the first pointer going down and the touched window has a wallpaper
1762 // then also add the touched wallpaper windows so they are locked in for the duration
1763 // of the touch gesture.
1764 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1765 // engine only supports touch events. We would need to add a mechanism similar
1766 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1767 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1768 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001769 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001770 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001771 const std::vector<sp<InputWindowHandle>> windowHandles =
1772 getWindowHandlesLocked(displayId);
1773 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001775 if (info->displayId == displayId &&
1776 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001777 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001778 .addOrUpdateWindow(windowHandle,
1779 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1780 InputTarget::
1781 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1782 InputTarget::FLAG_DISPATCH_AS_IS,
1783 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 }
1785 }
1786 }
1787 }
1788
1789 // Success! Output targets.
1790 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1791
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001792 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001794 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 }
1796
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001797 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001798 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001799 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001800 }
1801
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 // Drop the outside or hover touch windows since we will not care about them
1803 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001804 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805
1806Failed:
1807 // Check injection permission once and for all.
1808 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001809 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 injectionPermission = INJECTION_PERMISSION_GRANTED;
1811 } else {
1812 injectionPermission = INJECTION_PERMISSION_DENIED;
1813 }
1814 }
1815
1816 // Update final pieces of touch state if the injector had permission.
1817 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1818 if (!wrongDevice) {
1819 if (switchedDevice) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001820 if (DEBUG_FOCUS) {
1821 ALOGD("Conflicting pointer actions: Switched to a different device.");
1822 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 *outConflictingPointerActions = true;
1824 }
1825
1826 if (isHoverAction) {
1827 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001828 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001829 if (DEBUG_FOCUS) {
1830 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1831 "down.");
1832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 *outConflictingPointerActions = true;
1834 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001835 tempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001836 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1837 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001838 tempTouchState.deviceId = entry.deviceId;
1839 tempTouchState.source = entry.source;
1840 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001842 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1843 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 // All pointers up or canceled.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001845 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1847 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001848 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001849 if (DEBUG_FOCUS) {
1850 ALOGD("Conflicting pointer actions: Down received while already down.");
1851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 *outConflictingPointerActions = true;
1853 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1855 // One pointer went up.
1856 if (isSplit) {
1857 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001858 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001860 for (size_t i = 0; i < tempTouchState.windows.size();) {
1861 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1863 touchedWindow.pointerIds.clearBit(pointerId);
1864 if (touchedWindow.pointerIds.isEmpty()) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001865 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 continue;
1867 }
1868 }
1869 i += 1;
1870 }
1871 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001872 }
1873
1874 // Save changes unless the action was scroll in which case the temporary touch
1875 // state was only valid for this one action.
1876 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001877 if (tempTouchState.displayId >= 0) {
1878 mTouchStatesByDisplay[displayId] = tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001879 } else {
1880 mTouchStatesByDisplay.erase(displayId);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 }
1883
1884 // Update hover state.
1885 mLastHoverWindowHandle = newHoverWindowHandle;
1886 }
1887 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001888 if (DEBUG_FOCUS) {
1889 ALOGD("Not updating touch focus because injection was denied.");
1890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891 }
1892
1893Unresponsive:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894
1895 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001896 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001897 if (DEBUG_FOCUS) {
1898 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1899 "timeSpentWaitingForApplication=%0.1fms",
1900 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 return injectionResult;
1903}
1904
1905void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001906 int32_t targetFlags, BitSet32 pointerIds,
1907 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001908 std::vector<InputTarget>::iterator it =
1909 std::find_if(inputTargets.begin(), inputTargets.end(),
1910 [&windowHandle](const InputTarget& inputTarget) {
1911 return inputTarget.inputChannel->getConnectionToken() ==
1912 windowHandle->getToken();
1913 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00001914
Chavi Weingarten114b77f2020-01-15 22:35:10 +00001915 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001916
1917 if (it == inputTargets.end()) {
1918 InputTarget inputTarget;
1919 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1920 if (inputChannel == nullptr) {
1921 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1922 return;
1923 }
1924 inputTarget.inputChannel = inputChannel;
1925 inputTarget.flags = targetFlags;
1926 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
1927 inputTargets.push_back(inputTarget);
1928 it = inputTargets.end() - 1;
1929 }
1930
1931 ALOG_ASSERT(it->flags == targetFlags);
1932 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
1933
1934 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
1935 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936}
1937
Michael Wright3dd60e22019-03-27 22:06:44 +00001938void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001939 int32_t displayId, float xOffset,
1940 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001941 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1942 mGlobalMonitorsByDisplay.find(displayId);
1943
1944 if (it != mGlobalMonitorsByDisplay.end()) {
1945 const std::vector<Monitor>& monitors = it->second;
1946 for (const Monitor& monitor : monitors) {
1947 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949 }
1950}
1951
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001952void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1953 float yOffset,
1954 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001955 InputTarget target;
1956 target.inputChannel = monitor.inputChannel;
1957 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001958 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00001959 inputTargets.push_back(target);
1960}
1961
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001963 const InjectionState* injectionState) {
1964 if (injectionState &&
1965 (windowHandle == nullptr ||
1966 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1967 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001968 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001970 "owned by uid %d",
1971 injectionState->injectorPid, injectionState->injectorUid,
1972 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 } else {
1974 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001975 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 }
1977 return false;
1978 }
1979 return true;
1980}
1981
Robert Carrc9bf1d32020-04-13 17:21:08 -07001982/**
1983 * Indicate whether one window handle should be considered as obscuring
1984 * another window handle. We only check a few preconditions. Actually
1985 * checking the bounds is left to the caller.
1986 */
1987static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
1988 const sp<InputWindowHandle>& otherHandle) {
1989 // Compare by token so cloned layers aren't counted
1990 if (haveSameToken(windowHandle, otherHandle)) {
1991 return false;
1992 }
1993 auto info = windowHandle->getInfo();
1994 auto otherInfo = otherHandle->getInfo();
1995 if (!otherInfo->visible) {
1996 return false;
1997 } else if (info->ownerPid == otherInfo->ownerPid && otherHandle->getToken() == nullptr) {
1998 // In general, if ownerPid is the same we don't want to generate occlusion
1999 // events. This line is now necessary since we are including all Surfaces
2000 // in occlusion calculation, so if we didn't check PID like this SurfaceView
2001 // would occlude their parents. On the other hand before we started including
2002 // all surfaces in occlusion calculation and had this line, we would count
2003 // windows with an input channel from the same PID as occluding, and so we
2004 // preserve this behavior with the getToken() == null check.
2005 return false;
2006 } else if (otherInfo->isTrustedOverlay()) {
2007 return false;
2008 } else if (otherInfo->displayId != info->displayId) {
2009 return false;
2010 }
2011 return true;
2012}
2013
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002014bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2015 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002017 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2018 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002019 if (windowHandle == otherHandle) {
2020 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002023 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002024 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 return true;
2026 }
2027 }
2028 return false;
2029}
2030
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002031bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2032 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002033 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002034 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002035 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002036 if (windowHandle == otherHandle) {
2037 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002038 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002039 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002040 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002041 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002042 return true;
2043 }
2044 }
2045 return false;
2046}
2047
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002048std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
2049 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002050 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07002051 // If the window is paused then keep waiting.
2052 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002053 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002054 }
2055
2056 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07002057 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002058 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002059 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002060 "registered with the input dispatcher. The window may be in the "
2061 "process of being removed.",
2062 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002063 }
2064
2065 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07002066 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002067 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002068 "The window may be in the process of being removed.",
2069 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07002070 }
2071
2072 // If the connection is backed up then keep waiting.
2073 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002074 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002075 "Outbound queue length: %zu. Wait queue length: %zu.",
2076 targetType, connection->outboundQueue.size(),
2077 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07002078 }
2079
2080 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002081 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07002082 // If the event is a key event, then we must wait for all previous events to
2083 // complete before delivering it because previous events may have the
2084 // side-effect of transferring focus to a different window and we want to
2085 // ensure that the following keys are sent to the new window.
2086 //
2087 // Suppose the user touches a button in a window then immediately presses "A".
2088 // If the button causes a pop-up window to appear then we want to ensure that
2089 // the "A" key is delivered to the new pop-up window. This is because users
2090 // often anticipate pending UI changes when typing on a keyboard.
2091 // To obtain this behavior, we must serialize key events with respect to all
2092 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002093 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002094 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002095 "finished processing all of the input events that were previously "
2096 "delivered to it. Outbound queue length: %zu. Wait queue length: "
2097 "%zu.",
2098 targetType, connection->outboundQueue.size(),
2099 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100 }
Jeff Brownffb49772014-10-10 19:01:34 -07002101 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 // Touch events can always be sent to a window immediately because the user intended
2103 // to touch whatever was visible at the time. Even if focus changes or a new
2104 // window appears moments later, the touch event was meant to be delivered to
2105 // whatever window happened to be on screen at the time.
2106 //
2107 // Generic motion events, such as trackball or joystick events are a little trickier.
2108 // Like key events, generic motion events are delivered to the focused window.
2109 // Unlike key events, generic motion events don't tend to transfer focus to other
2110 // windows and it is not important for them to be serialized. So we prefer to deliver
2111 // generic motion events as soon as possible to improve efficiency and reduce lag
2112 // through batching.
2113 //
2114 // The one case where we pause input event delivery is when the wait queue is piling
2115 // up with lots of events because the application is not responding.
2116 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002117 if (!connection->waitQueue.empty() &&
2118 currentTime >=
2119 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002120 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002121 "finished processing certain input events that were delivered to "
2122 "it over "
2123 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
2124 "%0.1fms.",
2125 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
2126 connection->waitQueue.size(),
2127 (currentTime - connection->waitQueue.front()->deliveryTime) *
2128 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 }
2130 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002131 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132}
2133
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002134std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 const sp<InputApplicationHandle>& applicationHandle,
2136 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002137 if (applicationHandle != nullptr) {
2138 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002139 std::string label(applicationHandle->getName());
2140 label += " - ";
2141 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 return label;
2143 } else {
2144 return applicationHandle->getName();
2145 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002146 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 return windowHandle->getName();
2148 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002149 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 }
2151}
2152
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002153void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002154 if (eventEntry.type == EventEntry::Type::FOCUS) {
2155 // Focus events are passed to apps, but do not represent user activity.
2156 return;
2157 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002158 int32_t displayId = getTargetDisplayId(eventEntry);
2159 sp<InputWindowHandle> focusedWindowHandle =
2160 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2161 if (focusedWindowHandle != nullptr) {
2162 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2164#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002165 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166#endif
2167 return;
2168 }
2169 }
2170
2171 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002172 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002173 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002174 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2175 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002176 return;
2177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002179 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002180 eventType = USER_ACTIVITY_EVENT_TOUCH;
2181 }
2182 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002184 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002185 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2186 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002187 return;
2188 }
2189 eventType = USER_ACTIVITY_EVENT_BUTTON;
2190 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002192 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002193 case EventEntry::Type::CONFIGURATION_CHANGED:
2194 case EventEntry::Type::DEVICE_RESET: {
2195 LOG_ALWAYS_FATAL("%s events are not user activity",
2196 EventEntry::typeToString(eventEntry.type));
2197 break;
2198 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 }
2200
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002201 std::unique_ptr<CommandEntry> commandEntry =
2202 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002203 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002205 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206}
2207
2208void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002209 const sp<Connection>& connection,
2210 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002211 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002212 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002213 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002214 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002215 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002216 ATRACE_NAME(message.c_str());
2217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218#if DEBUG_DISPATCH_CYCLE
2219 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002220 "globalScaleFactor=%f, pointerIds=0x%x %s",
2221 connection->getInputChannelName().c_str(), inputTarget.flags,
2222 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2223 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224#endif
2225
2226 // Skip this event if the connection status is not normal.
2227 // We don't want to enqueue additional outbound events if the connection is broken.
2228 if (connection->status != Connection::STATUS_NORMAL) {
2229#if DEBUG_DISPATCH_CYCLE
2230 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002231 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232#endif
2233 return;
2234 }
2235
2236 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002237 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2238 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2239 "Entry type %s should not have FLAG_SPLIT",
2240 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002242 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002243 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002244 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002245 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246 if (!splitMotionEntry) {
2247 return; // split event was dropped
2248 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002249 if (DEBUG_FOCUS) {
2250 ALOGD("channel '%s' ~ Split motion event.",
2251 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002252 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002253 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 splitMotionEntry->release();
2256 return;
2257 }
2258 }
2259
2260 // Not splitting. Enqueue dispatch entries for the event as is.
2261 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2262}
2263
2264void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002265 const sp<Connection>& connection,
2266 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002267 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002268 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002269 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002270 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002271 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002272 ATRACE_NAME(message.c_str());
2273 }
2274
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002275 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276
2277 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002278 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002279 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002280 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002281 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002282 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002283 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002284 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002285 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002286 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002287 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002288 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290
2291 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002292 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 startDispatchCycleLocked(currentTime, connection);
2294 }
2295}
2296
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2298 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002299 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002300 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002301 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002302 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2303 connection->getInputChannelName().c_str(),
2304 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002305 ATRACE_NAME(message.c_str());
2306 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002307 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 if (!(inputTargetFlags & dispatchMode)) {
2309 return;
2310 }
2311 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2312
2313 // This is a new event.
2314 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002315 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002316 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002318 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2319 // different EventEntry than what was passed in.
2320 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002322 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002323 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002324 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002325 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002326 dispatchEntry->resolvedAction = keyEntry.action;
2327 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002329 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2330 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002332 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2333 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002335 return; // skip the inconsistent event
2336 }
2337 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002340 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002341 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002342 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2343 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2344 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2345 static_cast<int32_t>(IdGenerator::Source::OTHER);
2346 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002347 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2348 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2349 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2350 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2351 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2352 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2353 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2354 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2355 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2356 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2357 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002358 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002359 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002360 }
2361 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002362 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2363 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002365 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2366 "event",
2367 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002369 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002372 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002373 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2374 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2375 }
2376 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2377 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002380 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2381 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002383 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2384 "event",
2385 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002387 return; // skip the inconsistent event
2388 }
2389
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002390 dispatchEntry->resolvedEventId =
2391 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2392 ? mIdGenerator.nextId()
2393 : motionEntry.id;
2394 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2395 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2396 ") to MotionEvent(id=0x%" PRIx32 ").",
2397 motionEntry.id, dispatchEntry->resolvedEventId);
2398 ATRACE_NAME(message.c_str());
2399 }
2400
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002401 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002402 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002403
2404 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002406 case EventEntry::Type::FOCUS: {
2407 break;
2408 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002409 case EventEntry::Type::CONFIGURATION_CHANGED:
2410 case EventEntry::Type::DEVICE_RESET: {
2411 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002412 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002413 break;
2414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415 }
2416
2417 // Remember that we are waiting for this dispatch to complete.
2418 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002419 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420 }
2421
2422 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002423 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002424 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002425}
2426
chaviwfd6d3512019-03-25 13:23:49 -07002427void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002428 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002429 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002430 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2431 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002432 return;
2433 }
2434
2435 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2436 if (inputWindowHandle == nullptr) {
2437 return;
2438 }
2439
chaviw8c9cf542019-03-25 13:02:48 -07002440 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002441 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002442
2443 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2444
2445 if (!hasFocusChanged) {
2446 return;
2447 }
2448
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002449 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2450 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002451 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002452 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453}
2454
2455void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002456 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002457 if (ATRACE_ENABLED()) {
2458 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002459 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002460 ATRACE_NAME(message.c_str());
2461 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002463 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464#endif
2465
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002466 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2467 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 dispatchEntry->deliveryTime = currentTime;
2469
2470 // Publish the event.
2471 status_t status;
2472 EventEntry* eventEntry = dispatchEntry->eventEntry;
2473 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002474 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002475 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2476 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002478 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002479 status =
2480 connection->inputPublisher
2481 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2482 keyEntry->deviceId, keyEntry->source,
2483 keyEntry->displayId, std::move(hmac),
2484 dispatchEntry->resolvedAction,
2485 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2486 keyEntry->scanCode, keyEntry->metaState,
2487 keyEntry->repeatCount, keyEntry->downTime,
2488 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002489 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 }
2491
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002492 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002493 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002495 PointerCoords scaledCoords[MAX_POINTERS];
2496 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2497
chaviw82357092020-01-28 13:13:06 -08002498 // Set the X and Y offset and X and Y scale depending on the input source.
2499 float xOffset = 0.0f, yOffset = 0.0f;
2500 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002501 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2502 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2503 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002504 xScale = dispatchEntry->windowXScale;
2505 yScale = dispatchEntry->windowYScale;
2506 xOffset = dispatchEntry->xOffset * xScale;
2507 yOffset = dispatchEntry->yOffset * yScale;
2508 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002509 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2510 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002511 // Don't apply window scale here since we don't want scale to affect raw
2512 // coordinates. The scale will be sent back to the client and applied
2513 // later when requesting relative coordinates.
2514 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2515 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002516 }
2517 usingCoords = scaledCoords;
2518 }
2519 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002520 // We don't want the dispatch target to know.
2521 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2522 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2523 scaledCoords[i].clear();
2524 }
2525 usingCoords = scaledCoords;
2526 }
2527 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002528
2529 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002530
2531 // Publish the motion event.
2532 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002533 .publishMotionEvent(dispatchEntry->seq,
2534 dispatchEntry->resolvedEventId,
2535 motionEntry->deviceId, motionEntry->source,
2536 motionEntry->displayId, std::move(hmac),
2537 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002538 motionEntry->actionButton,
2539 dispatchEntry->resolvedFlags,
2540 motionEntry->edgeFlags, motionEntry->metaState,
2541 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002542 motionEntry->classification, xScale, yScale,
2543 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002544 motionEntry->yPrecision,
2545 motionEntry->xCursorPosition,
2546 motionEntry->yCursorPosition,
2547 motionEntry->downTime, motionEntry->eventTime,
2548 motionEntry->pointerCount,
2549 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002550 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002551 break;
2552 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002553 case EventEntry::Type::FOCUS: {
2554 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2555 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002556 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002557 focusEntry->hasFocus,
2558 mInTouchMode);
2559 break;
2560 }
2561
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002562 case EventEntry::Type::CONFIGURATION_CHANGED:
2563 case EventEntry::Type::DEVICE_RESET: {
2564 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2565 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002566 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 }
2569
2570 // Check the result.
2571 if (status) {
2572 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002573 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002575 "This is unexpected because the wait queue is empty, so the pipe "
2576 "should be empty and we shouldn't have any problems writing an "
2577 "event to it, status=%d",
2578 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2580 } else {
2581 // Pipe is full and we are waiting for the app to finish process some events
2582 // before sending more events to it.
2583#if DEBUG_DISPATCH_CYCLE
2584 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002585 "waiting for the application to catch up",
2586 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587#endif
2588 connection->inputPublisherBlocked = true;
2589 }
2590 } else {
2591 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002592 "status=%d",
2593 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2595 }
2596 return;
2597 }
2598
2599 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002600 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2601 connection->outboundQueue.end(),
2602 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002603 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002604 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002605 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606 }
2607}
2608
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002609const std::array<uint8_t, 32> InputDispatcher::getSignature(
2610 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2611 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2612 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2613 // Only sign events up and down events as the purely move events
2614 // are tied to their up/down counterparts so signing would be redundant.
2615 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2616 verifiedEvent.actionMasked = actionMasked;
2617 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2618 return mHmacKeyManager.sign(verifiedEvent);
2619 }
2620 return INVALID_HMAC;
2621}
2622
2623const std::array<uint8_t, 32> InputDispatcher::getSignature(
2624 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2625 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2626 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2627 verifiedEvent.action = dispatchEntry.resolvedAction;
2628 return mHmacKeyManager.sign(verifiedEvent);
2629}
2630
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002632 const sp<Connection>& connection, uint32_t seq,
2633 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634#if DEBUG_DISPATCH_CYCLE
2635 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002636 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637#endif
2638
2639 connection->inputPublisherBlocked = false;
2640
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002641 if (connection->status == Connection::STATUS_BROKEN ||
2642 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 return;
2644 }
2645
2646 // Notify other system components and prepare to start the next dispatch cycle.
2647 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2648}
2649
2650void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002651 const sp<Connection>& connection,
2652 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653#if DEBUG_DISPATCH_CYCLE
2654 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002655 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656#endif
2657
2658 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002659 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002660 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002661 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002662 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663
2664 // The connection appears to be unrecoverably broken.
2665 // Ignore already broken or zombie connections.
2666 if (connection->status == Connection::STATUS_NORMAL) {
2667 connection->status = Connection::STATUS_BROKEN;
2668
2669 if (notify) {
2670 // Notify other system components.
2671 onDispatchCycleBrokenLocked(currentTime, connection);
2672 }
2673 }
2674}
2675
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002676void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2677 while (!queue.empty()) {
2678 DispatchEntry* dispatchEntry = queue.front();
2679 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002680 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681 }
2682}
2683
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002684void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002686 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687 }
2688 delete dispatchEntry;
2689}
2690
2691int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2692 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2693
2694 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002695 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002697 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002699 "fd=%d, events=0x%x",
2700 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 return 0; // remove the callback
2702 }
2703
2704 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002705 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2707 if (!(events & ALOOPER_EVENT_INPUT)) {
2708 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002709 "events=0x%x",
2710 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 return 1;
2712 }
2713
2714 nsecs_t currentTime = now();
2715 bool gotOne = false;
2716 status_t status;
2717 for (;;) {
2718 uint32_t seq;
2719 bool handled;
2720 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2721 if (status) {
2722 break;
2723 }
2724 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2725 gotOne = true;
2726 }
2727 if (gotOne) {
2728 d->runCommandsLockedInterruptible();
2729 if (status == WOULD_BLOCK) {
2730 return 1;
2731 }
2732 }
2733
2734 notify = status != DEAD_OBJECT || !connection->monitor;
2735 if (notify) {
2736 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002737 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738 }
2739 } else {
2740 // Monitor channels are never explicitly unregistered.
2741 // We do it automatically when the remote endpoint is closed so don't warn
2742 // about them.
2743 notify = !connection->monitor;
2744 if (notify) {
2745 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002746 "events=0x%x",
2747 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748 }
2749 }
2750
2751 // Unregister the channel.
2752 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2753 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002754 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755}
2756
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002757void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002759 for (const auto& pair : mConnectionsByFd) {
2760 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761 }
2762}
2763
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002764void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002765 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002766 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2767 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2768}
2769
2770void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2771 const CancelationOptions& options,
2772 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2773 for (const auto& it : monitorsByDisplay) {
2774 const std::vector<Monitor>& monitors = it.second;
2775 for (const Monitor& monitor : monitors) {
2776 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002777 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002778 }
2779}
2780
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2782 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002783 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002784 if (connection == nullptr) {
2785 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002787
2788 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789}
2790
2791void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2792 const sp<Connection>& connection, const CancelationOptions& options) {
2793 if (connection->status == Connection::STATUS_BROKEN) {
2794 return;
2795 }
2796
2797 nsecs_t currentTime = now();
2798
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002799 std::vector<EventEntry*> cancelationEvents =
2800 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002802 if (cancelationEvents.empty()) {
2803 return;
2804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002806 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2807 "with reality: %s, mode=%d.",
2808 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2809 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002811
2812 InputTarget target;
2813 sp<InputWindowHandle> windowHandle =
2814 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2815 if (windowHandle != nullptr) {
2816 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2817 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2818 windowInfo->windowXScale, windowInfo->windowYScale);
2819 target.globalScaleFactor = windowInfo->globalScaleFactor;
2820 }
2821 target.inputChannel = connection->inputChannel;
2822 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2823
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002824 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2825 EventEntry* cancelationEventEntry = cancelationEvents[i];
2826 switch (cancelationEventEntry->type) {
2827 case EventEntry::Type::KEY: {
2828 logOutboundKeyDetails("cancel - ",
2829 static_cast<const KeyEntry&>(*cancelationEventEntry));
2830 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002832 case EventEntry::Type::MOTION: {
2833 logOutboundMotionDetails("cancel - ",
2834 static_cast<const MotionEntry&>(*cancelationEventEntry));
2835 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002837 case EventEntry::Type::FOCUS: {
2838 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2839 break;
2840 }
2841 case EventEntry::Type::CONFIGURATION_CHANGED:
2842 case EventEntry::Type::DEVICE_RESET: {
2843 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2844 EventEntry::typeToString(cancelationEventEntry->type));
2845 break;
2846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 }
2848
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002849 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2850 target, InputTarget::FLAG_DISPATCH_AS_IS);
2851
2852 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002854
2855 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856}
2857
Svet Ganov5d3bc372020-01-26 23:11:07 -08002858void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2859 const sp<Connection>& connection) {
2860 if (connection->status == Connection::STATUS_BROKEN) {
2861 return;
2862 }
2863
2864 nsecs_t currentTime = now();
2865
2866 std::vector<EventEntry*> downEvents =
2867 connection->inputState.synthesizePointerDownEvents(currentTime);
2868
2869 if (downEvents.empty()) {
2870 return;
2871 }
2872
2873#if DEBUG_OUTBOUND_EVENT_DETAILS
2874 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2875 connection->getInputChannelName().c_str(), downEvents.size());
2876#endif
2877
2878 InputTarget target;
2879 sp<InputWindowHandle> windowHandle =
2880 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2881 if (windowHandle != nullptr) {
2882 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2883 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2884 windowInfo->windowXScale, windowInfo->windowYScale);
2885 target.globalScaleFactor = windowInfo->globalScaleFactor;
2886 }
2887 target.inputChannel = connection->inputChannel;
2888 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2889
2890 for (EventEntry* downEventEntry : downEvents) {
2891 switch (downEventEntry->type) {
2892 case EventEntry::Type::MOTION: {
2893 logOutboundMotionDetails("down - ",
2894 static_cast<const MotionEntry&>(*downEventEntry));
2895 break;
2896 }
2897
2898 case EventEntry::Type::KEY:
2899 case EventEntry::Type::FOCUS:
2900 case EventEntry::Type::CONFIGURATION_CHANGED:
2901 case EventEntry::Type::DEVICE_RESET: {
2902 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2903 EventEntry::typeToString(downEventEntry->type));
2904 break;
2905 }
2906 }
2907
2908 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2909 target, InputTarget::FLAG_DISPATCH_AS_IS);
2910
2911 downEventEntry->release();
2912 }
2913
2914 startDispatchCycleLocked(currentTime, connection);
2915}
2916
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002917MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002918 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919 ALOG_ASSERT(pointerIds.value != 0);
2920
2921 uint32_t splitPointerIndexMap[MAX_POINTERS];
2922 PointerProperties splitPointerProperties[MAX_POINTERS];
2923 PointerCoords splitPointerCoords[MAX_POINTERS];
2924
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002925 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926 uint32_t splitPointerCount = 0;
2927
2928 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002931 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932 uint32_t pointerId = uint32_t(pointerProperties.id);
2933 if (pointerIds.hasBit(pointerId)) {
2934 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2935 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2936 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002937 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 splitPointerCount += 1;
2939 }
2940 }
2941
2942 if (splitPointerCount != pointerIds.count()) {
2943 // This is bad. We are missing some of the pointers that we expected to deliver.
2944 // Most likely this indicates that we received an ACTION_MOVE events that has
2945 // different pointer ids than we expected based on the previous ACTION_DOWN
2946 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2947 // in this way.
2948 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002949 "we expected there to be %d pointers. This probably means we received "
2950 "a broken sequence of pointer ids from the input device.",
2951 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002952 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002953 }
2954
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002955 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002957 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2958 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002959 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2960 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002961 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002962 uint32_t pointerId = uint32_t(pointerProperties.id);
2963 if (pointerIds.hasBit(pointerId)) {
2964 if (pointerIds.count() == 1) {
2965 // The first/last pointer went down/up.
2966 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 ? AMOTION_EVENT_ACTION_DOWN
2968 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969 } else {
2970 // A secondary pointer went down/up.
2971 uint32_t splitPointerIndex = 0;
2972 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2973 splitPointerIndex += 1;
2974 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002975 action = maskedAction |
2976 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002977 }
2978 } else {
2979 // An unrelated pointer changed.
2980 action = AMOTION_EVENT_ACTION_MOVE;
2981 }
2982 }
2983
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002984 int32_t newId = mIdGenerator.nextId();
2985 if (ATRACE_ENABLED()) {
2986 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
2987 ") to MotionEvent(id=0x%" PRIx32 ").",
2988 originalMotionEntry.id, newId);
2989 ATRACE_NAME(message.c_str());
2990 }
Garfield Tan00f511d2019-06-12 16:55:40 -07002991 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002992 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
2993 originalMotionEntry.source, originalMotionEntry.displayId,
2994 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002995 originalMotionEntry.actionButton, originalMotionEntry.flags,
2996 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2997 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2998 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2999 originalMotionEntry.xCursorPosition,
3000 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003001 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003003 if (originalMotionEntry.injectionState) {
3004 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 splitMotionEntry->injectionState->refCount += 1;
3006 }
3007
3008 return splitMotionEntry;
3009}
3010
3011void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3012#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003013 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014#endif
3015
3016 bool needWake;
3017 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003018 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019
Prabir Pradhan42611e02018-11-27 14:04:02 -08003020 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003021 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003022 needWake = enqueueInboundEventLocked(newEntry);
3023 } // release lock
3024
3025 if (needWake) {
3026 mLooper->wake();
3027 }
3028}
3029
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003030/**
3031 * If one of the meta shortcuts is detected, process them here:
3032 * Meta + Backspace -> generate BACK
3033 * Meta + Enter -> generate HOME
3034 * This will potentially overwrite keyCode and metaState.
3035 */
3036void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003037 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003038 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3039 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3040 if (keyCode == AKEYCODE_DEL) {
3041 newKeyCode = AKEYCODE_BACK;
3042 } else if (keyCode == AKEYCODE_ENTER) {
3043 newKeyCode = AKEYCODE_HOME;
3044 }
3045 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003046 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003047 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003048 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003049 keyCode = newKeyCode;
3050 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3051 }
3052 } else if (action == AKEY_EVENT_ACTION_UP) {
3053 // In order to maintain a consistent stream of up and down events, check to see if the key
3054 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3055 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003056 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003057 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003058 auto replacementIt = mReplacedKeys.find(replacement);
3059 if (replacementIt != mReplacedKeys.end()) {
3060 keyCode = replacementIt->second;
3061 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003062 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3063 }
3064 }
3065}
3066
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3068#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003069 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3070 "policyFlags=0x%x, action=0x%x, "
3071 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3072 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3073 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3074 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003075#endif
3076 if (!validateKeyEvent(args->action)) {
3077 return;
3078 }
3079
3080 uint32_t policyFlags = args->policyFlags;
3081 int32_t flags = args->flags;
3082 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003083 // InputDispatcher tracks and generates key repeats on behalf of
3084 // whatever notifies it, so repeatCount should always be set to 0
3085 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3087 policyFlags |= POLICY_FLAG_VIRTUAL;
3088 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090 if (policyFlags & POLICY_FLAG_FUNCTION) {
3091 metaState |= AMETA_FUNCTION_ON;
3092 }
3093
3094 policyFlags |= POLICY_FLAG_TRUSTED;
3095
Michael Wright78f24442014-08-06 15:55:28 -07003096 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003097 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003098
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003100 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003101 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3102 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103
Michael Wright2b3c3302018-03-02 17:19:13 +00003104 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003106 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3107 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003108 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111 bool needWake;
3112 { // acquire lock
3113 mLock.lock();
3114
3115 if (shouldSendKeyToInputFilterLocked(args)) {
3116 mLock.unlock();
3117
3118 policyFlags |= POLICY_FLAG_FILTERED;
3119 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3120 return; // event was consumed by the filter
3121 }
3122
3123 mLock.lock();
3124 }
3125
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003127 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003128 args->displayId, policyFlags, args->action, flags, keyCode,
3129 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130
3131 needWake = enqueueInboundEventLocked(newEntry);
3132 mLock.unlock();
3133 } // release lock
3134
3135 if (needWake) {
3136 mLooper->wake();
3137 }
3138}
3139
3140bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3141 return mInputFilterEnabled;
3142}
3143
3144void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3145#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003146 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3147 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003148 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3149 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003150 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003151 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3152 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3153 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3154 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155 for (uint32_t i = 0; i < args->pointerCount; i++) {
3156 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003157 "x=%f, y=%f, pressure=%f, size=%f, "
3158 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3159 "orientation=%f",
3160 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3161 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3162 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3163 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3164 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3165 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3166 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3167 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3168 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3169 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 }
3171#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003172 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3173 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 return;
3175 }
3176
3177 uint32_t policyFlags = args->policyFlags;
3178 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003179
3180 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003181 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003182 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3183 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186
3187 bool needWake;
3188 { // acquire lock
3189 mLock.lock();
3190
3191 if (shouldSendMotionToInputFilterLocked(args)) {
3192 mLock.unlock();
3193
3194 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003195 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3196 args->action, args->actionButton, args->flags, args->edgeFlags,
3197 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3198 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3199 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3200 args->downTime, args->eventTime, args->pointerCount,
3201 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202
3203 policyFlags |= POLICY_FLAG_FILTERED;
3204 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3205 return; // event was consumed by the filter
3206 }
3207
3208 mLock.lock();
3209 }
3210
3211 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003212 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003213 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003214 args->displayId, policyFlags, args->action, args->actionButton,
3215 args->flags, args->metaState, args->buttonState,
3216 args->classification, args->edgeFlags, args->xPrecision,
3217 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3218 args->downTime, args->pointerCount, args->pointerProperties,
3219 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220
3221 needWake = enqueueInboundEventLocked(newEntry);
3222 mLock.unlock();
3223 } // release lock
3224
3225 if (needWake) {
3226 mLooper->wake();
3227 }
3228}
3229
3230bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003231 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232}
3233
3234void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3235#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003236 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003237 "switchMask=0x%08x",
3238 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239#endif
3240
3241 uint32_t policyFlags = args->policyFlags;
3242 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244}
3245
3246void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3247#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003248 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3249 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250#endif
3251
3252 bool needWake;
3253 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003254 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255
Prabir Pradhan42611e02018-11-27 14:04:02 -08003256 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003257 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258 needWake = enqueueInboundEventLocked(newEntry);
3259 } // release lock
3260
3261 if (needWake) {
3262 mLooper->wake();
3263 }
3264}
3265
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003266int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3267 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003268 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269#if DEBUG_INBOUND_EVENT_DETAILS
3270 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003271 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3272 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273#endif
3274
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003275 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276
3277 policyFlags |= POLICY_FLAG_INJECTED;
3278 if (hasInjectionPermission(injectorPid, injectorUid)) {
3279 policyFlags |= POLICY_FLAG_TRUSTED;
3280 }
3281
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003282 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003284 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003285 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3286 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003287 if (!validateKeyEvent(action)) {
3288 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003291 int32_t flags = incomingKey.getFlags();
3292 int32_t keyCode = incomingKey.getKeyCode();
3293 int32_t metaState = incomingKey.getMetaState();
3294 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003295 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003296 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003297 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003298 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3299 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3300 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003302 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3303 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003304 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003305
3306 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3307 android::base::Timer t;
3308 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3309 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3310 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3311 std::to_string(t.duration().count()).c_str());
3312 }
3313 }
3314
3315 mLock.lock();
3316 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003317 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3318 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003319 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3320 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003321 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 injectedEntries.push(injectedEntry);
3323 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324 }
3325
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003326 case AINPUT_EVENT_TYPE_MOTION: {
3327 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3328 int32_t action = motionEvent->getAction();
3329 size_t pointerCount = motionEvent->getPointerCount();
3330 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3331 int32_t actionButton = motionEvent->getActionButton();
3332 int32_t displayId = motionEvent->getDisplayId();
3333 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3334 return INPUT_EVENT_INJECTION_FAILED;
3335 }
3336
3337 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3338 nsecs_t eventTime = motionEvent->getEventTime();
3339 android::base::Timer t;
3340 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3341 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3342 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3343 std::to_string(t.duration().count()).c_str());
3344 }
3345 }
3346
3347 mLock.lock();
3348 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3349 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3350 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003351 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3352 motionEvent->getSource(), motionEvent->getDisplayId(),
3353 policyFlags, action, actionButton, motionEvent->getFlags(),
3354 motionEvent->getMetaState(), motionEvent->getButtonState(),
3355 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3356 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003357 motionEvent->getRawXCursorPosition(),
3358 motionEvent->getRawYCursorPosition(),
3359 motionEvent->getDownTime(), uint32_t(pointerCount),
3360 pointerProperties, samplePointerCoords,
3361 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003362 injectedEntries.push(injectedEntry);
3363 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3364 sampleEventTimes += 1;
3365 samplePointerCoords += pointerCount;
3366 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003367 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003368 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003369 motionEvent->getDisplayId(), policyFlags, action,
3370 actionButton, motionEvent->getFlags(),
3371 motionEvent->getMetaState(), motionEvent->getButtonState(),
3372 motionEvent->getClassification(),
3373 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3374 motionEvent->getYPrecision(),
3375 motionEvent->getRawXCursorPosition(),
3376 motionEvent->getRawYCursorPosition(),
3377 motionEvent->getDownTime(), uint32_t(pointerCount),
3378 pointerProperties, samplePointerCoords,
3379 motionEvent->getXOffset(), motionEvent->getYOffset());
3380 injectedEntries.push(nextInjectedEntry);
3381 }
3382 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003386 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003387 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 }
3389
3390 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3391 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3392 injectionState->injectionIsAsync = true;
3393 }
3394
3395 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003396 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397
3398 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003399 while (!injectedEntries.empty()) {
3400 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3401 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402 }
3403
3404 mLock.unlock();
3405
3406 if (needWake) {
3407 mLooper->wake();
3408 }
3409
3410 int32_t injectionResult;
3411 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003412 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413
3414 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3415 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3416 } else {
3417 for (;;) {
3418 injectionResult = injectionState->injectionResult;
3419 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3420 break;
3421 }
3422
3423 nsecs_t remainingTimeout = endTime - now();
3424 if (remainingTimeout <= 0) {
3425#if DEBUG_INJECTION
3426 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003427 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428#endif
3429 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3430 break;
3431 }
3432
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003433 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434 }
3435
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003436 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3437 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 while (injectionState->pendingForegroundDispatches != 0) {
3439#if DEBUG_INJECTION
3440 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003441 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442#endif
3443 nsecs_t remainingTimeout = endTime - now();
3444 if (remainingTimeout <= 0) {
3445#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003446 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3447 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448#endif
3449 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3450 break;
3451 }
3452
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003453 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454 }
3455 }
3456 }
3457
3458 injectionState->release();
3459 } // release lock
3460
3461#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003462 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003463 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003464#endif
3465
3466 return injectionResult;
3467}
3468
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003469std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003470 std::array<uint8_t, 32> calculatedHmac;
3471 std::unique_ptr<VerifiedInputEvent> result;
3472 switch (event.getType()) {
3473 case AINPUT_EVENT_TYPE_KEY: {
3474 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3475 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3476 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3477 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3478 break;
3479 }
3480 case AINPUT_EVENT_TYPE_MOTION: {
3481 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3482 VerifiedMotionEvent verifiedMotionEvent =
3483 verifiedMotionEventFromMotionEvent(motionEvent);
3484 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3485 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3486 break;
3487 }
3488 default: {
3489 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3490 return nullptr;
3491 }
3492 }
3493 if (calculatedHmac == INVALID_HMAC) {
3494 return nullptr;
3495 }
3496 if (calculatedHmac != event.getHmac()) {
3497 return nullptr;
3498 }
3499 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003500}
3501
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003503 return injectorUid == 0 ||
3504 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505}
3506
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003507void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 InjectionState* injectionState = entry->injectionState;
3509 if (injectionState) {
3510#if DEBUG_INJECTION
3511 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003512 "injectorPid=%d, injectorUid=%d",
3513 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514#endif
3515
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003516 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 // Log the outcome since the injector did not wait for the injection result.
3518 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003519 case INPUT_EVENT_INJECTION_SUCCEEDED:
3520 ALOGV("Asynchronous input event injection succeeded.");
3521 break;
3522 case INPUT_EVENT_INJECTION_FAILED:
3523 ALOGW("Asynchronous input event injection failed.");
3524 break;
3525 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3526 ALOGW("Asynchronous input event injection permission denied.");
3527 break;
3528 case INPUT_EVENT_INJECTION_TIMED_OUT:
3529 ALOGW("Asynchronous input event injection timed out.");
3530 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 }
3532 }
3533
3534 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003535 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 }
3537}
3538
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003539void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 InjectionState* injectionState = entry->injectionState;
3541 if (injectionState) {
3542 injectionState->pendingForegroundDispatches += 1;
3543 }
3544}
3545
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003546void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003547 InjectionState* injectionState = entry->injectionState;
3548 if (injectionState) {
3549 injectionState->pendingForegroundDispatches -= 1;
3550
3551 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003552 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553 }
3554 }
3555}
3556
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003557std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3558 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003559 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003560}
3561
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003563 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003564 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003565 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3566 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003567 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003568 return windowHandle;
3569 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570 }
3571 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003572 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573}
3574
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003575bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003576 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003577 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3578 for (const sp<InputWindowHandle>& handle : windowHandles) {
3579 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003580 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003581 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003582 ", but it should belong to display %" PRId32,
3583 windowHandle->getName().c_str(), it.first,
3584 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003585 }
3586 return true;
3587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 }
3589 }
3590 return false;
3591}
3592
Robert Carr5c8a0262018-10-03 16:30:44 -07003593sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3594 size_t count = mInputChannelsByToken.count(token);
3595 if (count == 0) {
3596 return nullptr;
3597 }
3598 return mInputChannelsByToken.at(token);
3599}
3600
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003601void InputDispatcher::updateWindowHandlesForDisplayLocked(
3602 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3603 if (inputWindowHandles.empty()) {
3604 // Remove all handles on a display if there are no windows left.
3605 mWindowHandlesByDisplay.erase(displayId);
3606 return;
3607 }
3608
3609 // Since we compare the pointer of input window handles across window updates, we need
3610 // to make sure the handle object for the same window stays unchanged across updates.
3611 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003612 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003613 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003614 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003615 }
3616
3617 std::vector<sp<InputWindowHandle>> newHandles;
3618 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3619 if (!handle->updateInfo()) {
3620 // handle no longer valid
3621 continue;
3622 }
3623
3624 const InputWindowInfo* info = handle->getInfo();
3625 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3626 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3627 const bool noInputChannel =
3628 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3629 const bool canReceiveInput =
3630 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3631 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3632 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003633 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003634 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003635 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003636 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003637 }
3638
3639 if (info->displayId != displayId) {
3640 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3641 handle->getName().c_str(), displayId, info->displayId);
3642 continue;
3643 }
3644
chaviwaf87b3e2019-10-01 16:59:28 -07003645 if (oldHandlesById.find(handle->getId()) != oldHandlesById.end()) {
3646 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003647 oldHandle->updateFrom(handle);
3648 newHandles.push_back(oldHandle);
3649 } else {
3650 newHandles.push_back(handle);
3651 }
3652 }
3653
3654 // Insert or replace
3655 mWindowHandlesByDisplay[displayId] = newHandles;
3656}
3657
Arthur Hung72d8dc32020-03-28 00:48:39 +00003658void InputDispatcher::setInputWindows(
3659 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3660 { // acquire lock
3661 std::scoped_lock _l(mLock);
3662 for (auto const& i : handlesPerDisplay) {
3663 setInputWindowsLocked(i.second, i.first);
3664 }
3665 }
3666 // Wake up poll loop since it may need to make new input dispatching choices.
3667 mLooper->wake();
3668}
3669
Arthur Hungb92218b2018-08-14 12:00:21 +08003670/**
3671 * Called from InputManagerService, update window handle list by displayId that can receive input.
3672 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3673 * If set an empty list, remove all handles from the specific display.
3674 * For focused handle, check if need to change and send a cancel event to previous one.
3675 * For removed handle, check if need to send a cancel event if already in touch.
3676 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003677void InputDispatcher::setInputWindowsLocked(
3678 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003679 if (DEBUG_FOCUS) {
3680 std::string windowList;
3681 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3682 windowList += iwh->getName() + " ";
3683 }
3684 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686
Arthur Hung72d8dc32020-03-28 00:48:39 +00003687 // Copy old handles for release if they are no longer present.
3688 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689
Arthur Hung72d8dc32020-03-28 00:48:39 +00003690 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003691
Arthur Hung72d8dc32020-03-28 00:48:39 +00003692 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3693 bool foundHoveredWindow = false;
3694 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3695 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3696 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3697 windowHandle->getInfo()->visible) {
3698 newFocusedWindowHandle = windowHandle;
3699 }
3700 if (windowHandle == mLastHoverWindowHandle) {
3701 foundHoveredWindow = true;
3702 }
3703 }
3704
3705 if (!foundHoveredWindow) {
3706 mLastHoverWindowHandle = nullptr;
3707 }
3708
3709 sp<InputWindowHandle> oldFocusedWindowHandle =
3710 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3711
3712 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3713 if (oldFocusedWindowHandle != nullptr) {
3714 if (DEBUG_FOCUS) {
3715 ALOGD("Focus left window: %s in display %" PRId32,
3716 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003717 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003718 sp<InputChannel> focusedInputChannel =
3719 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3720 if (focusedInputChannel != nullptr) {
3721 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3722 "focus left window");
3723 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3724 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003725 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003726 mFocusedWindowHandlesByDisplay.erase(displayId);
3727 }
3728 if (newFocusedWindowHandle != nullptr) {
3729 if (DEBUG_FOCUS) {
3730 ALOGD("Focus entered window: %s in display %" PRId32,
3731 newFocusedWindowHandle->getName().c_str(), displayId);
3732 }
3733 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3734 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735 }
3736
Arthur Hung72d8dc32020-03-28 00:48:39 +00003737 if (mFocusedDisplayId == displayId) {
3738 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003740 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003742 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3743 mTouchStatesByDisplay.find(displayId);
3744 if (stateIt != mTouchStatesByDisplay.end()) {
3745 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003746 for (size_t i = 0; i < state.windows.size();) {
3747 TouchedWindow& touchedWindow = state.windows[i];
3748 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003749 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003750 ALOGD("Touched window was removed: %s in display %" PRId32,
3751 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003752 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003753 sp<InputChannel> touchedInputChannel =
3754 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3755 if (touchedInputChannel != nullptr) {
3756 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3757 "touched window was removed");
3758 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003760 state.windows.erase(state.windows.begin() + i);
3761 } else {
3762 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763 }
3764 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003765 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003766
Arthur Hung72d8dc32020-03-28 00:48:39 +00003767 // Release information for windows that are no longer present.
3768 // This ensures that unused input channels are released promptly.
3769 // Otherwise, they might stick around until the window handle is destroyed
3770 // which might not happen until the next GC.
3771 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3772 if (!hasWindowHandleLocked(oldWindowHandle)) {
3773 if (DEBUG_FOCUS) {
3774 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003775 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003776 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003777 }
chaviw291d88a2019-02-14 10:33:58 -08003778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779}
3780
3781void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003782 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003783 if (DEBUG_FOCUS) {
3784 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3785 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003788 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789
Tiger Huang721e26f2018-07-24 22:26:19 +08003790 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3791 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003792 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003793 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3794 if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003795 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003797 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003799 } else if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003800 resetAnrTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003801 oldFocusedApplicationHandle.clear();
3802 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 } // release lock
3805
3806 // Wake up poll loop since it may need to make new input dispatching choices.
3807 mLooper->wake();
3808}
3809
Tiger Huang721e26f2018-07-24 22:26:19 +08003810/**
3811 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3812 * the display not specified.
3813 *
3814 * We track any unreleased events for each window. If a window loses the ability to receive the
3815 * released event, we will send a cancel event to it. So when the focused display is changed, we
3816 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3817 * display. The display-specified events won't be affected.
3818 */
3819void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003820 if (DEBUG_FOCUS) {
3821 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3822 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003823 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003824 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003825
3826 if (mFocusedDisplayId != displayId) {
3827 sp<InputWindowHandle> oldFocusedWindowHandle =
3828 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3829 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003830 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003831 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003832 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003833 CancelationOptions
3834 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3835 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003836 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003837 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3838 }
3839 }
3840 mFocusedDisplayId = displayId;
3841
3842 // Sanity check
3843 sp<InputWindowHandle> newFocusedWindowHandle =
3844 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003845 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003846
Tiger Huang721e26f2018-07-24 22:26:19 +08003847 if (newFocusedWindowHandle == nullptr) {
3848 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3849 if (!mFocusedWindowHandlesByDisplay.empty()) {
3850 ALOGE("But another display has a focused window:");
3851 for (auto& it : mFocusedWindowHandlesByDisplay) {
3852 const int32_t displayId = it.first;
3853 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003854 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3855 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003856 }
3857 }
3858 }
3859 }
3860
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003861 if (DEBUG_FOCUS) {
3862 logDispatchStateLocked();
3863 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003864 } // release lock
3865
3866 // Wake up poll loop since it may need to make new input dispatching choices.
3867 mLooper->wake();
3868}
3869
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003871 if (DEBUG_FOCUS) {
3872 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874
3875 bool changed;
3876 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003877 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878
3879 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3880 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003881 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882 }
3883
3884 if (mDispatchEnabled && !enabled) {
3885 resetAndDropEverythingLocked("dispatcher is being disabled");
3886 }
3887
3888 mDispatchEnabled = enabled;
3889 mDispatchFrozen = frozen;
3890 changed = true;
3891 } else {
3892 changed = false;
3893 }
3894
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003895 if (DEBUG_FOCUS) {
3896 logDispatchStateLocked();
3897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 } // release lock
3899
3900 if (changed) {
3901 // Wake up poll loop since it may need to make new input dispatching choices.
3902 mLooper->wake();
3903 }
3904}
3905
3906void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003907 if (DEBUG_FOCUS) {
3908 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910
3911 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003912 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913
3914 if (mInputFilterEnabled == enabled) {
3915 return;
3916 }
3917
3918 mInputFilterEnabled = enabled;
3919 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3920 } // release lock
3921
3922 // Wake up poll loop since there might be work to do to drop everything.
3923 mLooper->wake();
3924}
3925
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003926void InputDispatcher::setInTouchMode(bool inTouchMode) {
3927 std::scoped_lock lock(mLock);
3928 mInTouchMode = inTouchMode;
3929}
3930
chaviwfbe5d9c2018-12-26 12:23:37 -08003931bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3932 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003933 if (DEBUG_FOCUS) {
3934 ALOGD("Trivial transfer to same window.");
3935 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003936 return true;
3937 }
3938
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003940 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941
chaviwfbe5d9c2018-12-26 12:23:37 -08003942 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3943 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003944 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003945 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946 return false;
3947 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003948 if (DEBUG_FOCUS) {
3949 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3950 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003953 if (DEBUG_FOCUS) {
3954 ALOGD("Cannot transfer focus because windows are on different displays.");
3955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 return false;
3957 }
3958
3959 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003960 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
3961 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003962 for (size_t i = 0; i < state.windows.size(); i++) {
3963 const TouchedWindow& touchedWindow = state.windows[i];
3964 if (touchedWindow.windowHandle == fromWindowHandle) {
3965 int32_t oldTargetFlags = touchedWindow.targetFlags;
3966 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003968 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003970 int32_t newTargetFlags = oldTargetFlags &
3971 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3972 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003973 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974
Jeff Brownf086ddb2014-02-11 14:28:48 -08003975 found = true;
3976 goto Found;
3977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 }
3979 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003980 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003982 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003983 if (DEBUG_FOCUS) {
3984 ALOGD("Focus transfer failed because from window did not have focus.");
3985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 return false;
3987 }
3988
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003989 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3990 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003991 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003992 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003993 CancelationOptions
3994 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3995 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003997 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998 }
3999
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004000 if (DEBUG_FOCUS) {
4001 logDispatchStateLocked();
4002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003 } // release lock
4004
4005 // Wake up poll loop since it may need to make new input dispatching choices.
4006 mLooper->wake();
4007 return true;
4008}
4009
4010void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004011 if (DEBUG_FOCUS) {
4012 ALOGD("Resetting and dropping all events (%s).", reason);
4013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014
4015 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4016 synthesizeCancelationEventsForAllConnectionsLocked(options);
4017
4018 resetKeyRepeatLocked();
4019 releasePendingEventLocked();
4020 drainInboundQueueLocked();
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004021 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022
Jeff Brownf086ddb2014-02-11 14:28:48 -08004023 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004025 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026}
4027
4028void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004029 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030 dumpDispatchStateLocked(dump);
4031
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004032 std::istringstream stream(dump);
4033 std::string line;
4034
4035 while (std::getline(stream, line, '\n')) {
4036 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037 }
4038}
4039
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004040void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004041 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4042 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4043 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004044 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045
Tiger Huang721e26f2018-07-24 22:26:19 +08004046 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4047 dump += StringPrintf(INDENT "FocusedApplications:\n");
4048 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4049 const int32_t displayId = it.first;
4050 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004051 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4052 ", name='%s', dispatchingTimeout=%0.3fms\n",
4053 displayId, applicationHandle->getName().c_str(),
4054 applicationHandle->getDispatchingTimeout(
4055 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
4056 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08004057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004059 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004061
4062 if (!mFocusedWindowHandlesByDisplay.empty()) {
4063 dump += StringPrintf(INDENT "FocusedWindows:\n");
4064 for (auto& it : mFocusedWindowHandlesByDisplay) {
4065 const int32_t displayId = it.first;
4066 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004067 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4068 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004069 }
4070 } else {
4071 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004074 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004075 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004076 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4077 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004078 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004079 state.displayId, toString(state.down), toString(state.split),
4080 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004081 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004082 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004083 for (size_t i = 0; i < state.windows.size(); i++) {
4084 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004085 dump += StringPrintf(INDENT4
4086 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4087 i, touchedWindow.windowHandle->getName().c_str(),
4088 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004089 }
4090 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004091 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004092 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004093 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004094 dump += INDENT3 "Portal windows:\n";
4095 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004096 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004097 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4098 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004099 }
4100 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101 }
4102 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004103 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104 }
4105
Arthur Hungb92218b2018-08-14 12:00:21 +08004106 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004107 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004108 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004109 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004110 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004111 dump += INDENT2 "Windows:\n";
4112 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004113 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004114 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115
Arthur Hungb92218b2018-08-14 12:00:21 +08004116 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004117 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004118 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4119 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004120 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004121 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004122 i, windowInfo->name.c_str(), windowInfo->displayId,
4123 windowInfo->portalToDisplayId,
4124 toString(windowInfo->paused),
4125 toString(windowInfo->hasFocus),
4126 toString(windowInfo->hasWallpaper),
4127 toString(windowInfo->visible),
4128 toString(windowInfo->canReceiveKeys),
4129 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004130 windowInfo->layoutParamsType, windowInfo->frameLeft,
4131 windowInfo->frameTop, windowInfo->frameRight,
4132 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4133 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004134 dumpRegion(dump, windowInfo->touchableRegion);
4135 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
4136 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004137 windowInfo->ownerPid, windowInfo->ownerUid,
4138 windowInfo->dispatchingTimeout / 1000000.0);
Siarhei Vishniakou67d44502020-04-09 11:09:29 -07004139 dump += StringPrintf(INDENT4 " flags: %s\n",
4140 inputWindowFlagsToString(windowInfo->layoutParamsFlags)
4141 .c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004142 }
4143 } else {
4144 dump += INDENT2 "Windows: <none>\n";
4145 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 }
4147 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004148 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149 }
4150
Michael Wright3dd60e22019-03-27 22:06:44 +00004151 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004152 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004153 const std::vector<Monitor>& monitors = it.second;
4154 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4155 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004156 }
4157 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004158 const std::vector<Monitor>& monitors = it.second;
4159 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4160 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004163 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 }
4165
4166 nsecs_t currentTime = now();
4167
4168 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004169 if (!mRecentQueue.empty()) {
4170 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4171 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004172 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004174 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 }
4176 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004177 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 }
4179
4180 // Dump event currently being dispatched.
4181 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004182 dump += INDENT "PendingEvent:\n";
4183 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004185 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004186 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004188 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 }
4190
4191 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004192 if (!mInboundQueue.empty()) {
4193 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4194 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004195 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 }
4199 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004200 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201 }
4202
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004203 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004204 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004205 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4206 const KeyReplacement& replacement = pair.first;
4207 int32_t newKeyCode = pair.second;
4208 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004209 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004210 }
4211 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004212 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004213 }
4214
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004215 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004216 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004217 for (const auto& pair : mConnectionsByFd) {
4218 const sp<Connection>& connection = pair.second;
4219 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
4220 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
4221 pair.first, connection->getInputChannelName().c_str(),
4222 connection->getWindowName().c_str(), connection->getStatusLabel(),
4223 toString(connection->monitor),
4224 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004226 if (!connection->outboundQueue.empty()) {
4227 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4228 connection->outboundQueue.size());
4229 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230 dump.append(INDENT4);
4231 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004232 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 entry->targetFlags, entry->resolvedAction,
4234 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 }
4236 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004237 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 }
4239
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004240 if (!connection->waitQueue.empty()) {
4241 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4242 connection->waitQueue.size());
4243 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004244 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004246 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004247 "age=%0.1fms, wait=%0.1fms\n",
4248 entry->targetFlags, entry->resolvedAction,
4249 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
4250 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 }
4252 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004253 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254 }
4255 }
4256 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004257 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 }
4259
4260 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004261 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004262 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004264 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 }
4266
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004267 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004269 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004270 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271}
4272
Michael Wright3dd60e22019-03-27 22:06:44 +00004273void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4274 const size_t numMonitors = monitors.size();
4275 for (size_t i = 0; i < numMonitors; i++) {
4276 const Monitor& monitor = monitors[i];
4277 const sp<InputChannel>& channel = monitor.inputChannel;
4278 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4279 dump += "\n";
4280 }
4281}
4282
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004283status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004285 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286#endif
4287
4288 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004289 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004290 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004291 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004293 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 return BAD_VALUE;
4295 }
4296
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004297 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298
4299 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004300 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004301 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4304 } // release lock
4305
4306 // Wake the looper because some connections have changed.
4307 mLooper->wake();
4308 return OK;
4309}
4310
Michael Wright3dd60e22019-03-27 22:06:44 +00004311status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004312 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004313 { // acquire lock
4314 std::scoped_lock _l(mLock);
4315
4316 if (displayId < 0) {
4317 ALOGW("Attempted to register input monitor without a specified display.");
4318 return BAD_VALUE;
4319 }
4320
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004321 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004322 ALOGW("Attempted to register input monitor without an identifying token.");
4323 return BAD_VALUE;
4324 }
4325
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004326 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004327
4328 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004329 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004330 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004331
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004332 auto& monitorsByDisplay =
4333 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004334 monitorsByDisplay[displayId].emplace_back(inputChannel);
4335
4336 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004337 }
4338 // Wake the looper because some connections have changed.
4339 mLooper->wake();
4340 return OK;
4341}
4342
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4344#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004345 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346#endif
4347
4348 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004349 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350
4351 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4352 if (status) {
4353 return status;
4354 }
4355 } // release lock
4356
4357 // Wake the poll loop because removing the connection may have changed the current
4358 // synchronization state.
4359 mLooper->wake();
4360 return OK;
4361}
4362
4363status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004364 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004365 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004366 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004368 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 return BAD_VALUE;
4370 }
4371
John Recke0710582019-09-26 13:46:12 -07004372 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004373 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004374 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004375
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 if (connection->monitor) {
4377 removeMonitorChannelLocked(inputChannel);
4378 }
4379
4380 mLooper->removeFd(inputChannel->getFd());
4381
4382 nsecs_t currentTime = now();
4383 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4384
4385 connection->status = Connection::STATUS_ZOMBIE;
4386 return OK;
4387}
4388
4389void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004390 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4391 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4392}
4393
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004394void InputDispatcher::removeMonitorChannelLocked(
4395 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004396 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004397 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004398 std::vector<Monitor>& monitors = it->second;
4399 const size_t numMonitors = monitors.size();
4400 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004401 if (monitors[i].inputChannel == inputChannel) {
4402 monitors.erase(monitors.begin() + i);
4403 break;
4404 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004405 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004406 if (monitors.empty()) {
4407 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004408 } else {
4409 ++it;
4410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004411 }
4412}
4413
Michael Wright3dd60e22019-03-27 22:06:44 +00004414status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4415 { // acquire lock
4416 std::scoped_lock _l(mLock);
4417 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4418
4419 if (!foundDisplayId) {
4420 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4421 return BAD_VALUE;
4422 }
4423 int32_t displayId = foundDisplayId.value();
4424
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004425 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4426 mTouchStatesByDisplay.find(displayId);
4427 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004428 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4429 return BAD_VALUE;
4430 }
4431
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004432 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004433 std::optional<int32_t> foundDeviceId;
4434 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004435 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004436 foundDeviceId = state.deviceId;
4437 }
4438 }
4439 if (!foundDeviceId || !state.down) {
4440 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004441 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004442 return BAD_VALUE;
4443 }
4444 int32_t deviceId = foundDeviceId.value();
4445
4446 // Send cancel events to all the input channels we're stealing from.
4447 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004448 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004449 options.deviceId = deviceId;
4450 options.displayId = displayId;
4451 for (const TouchedWindow& window : state.windows) {
4452 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004453 if (channel != nullptr) {
4454 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4455 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004456 }
4457 // Then clear the current touch state so we stop dispatching to them as well.
4458 state.filterNonMonitors();
4459 }
4460 return OK;
4461}
4462
Michael Wright3dd60e22019-03-27 22:06:44 +00004463std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4464 const sp<IBinder>& token) {
4465 for (const auto& it : mGestureMonitorsByDisplay) {
4466 const std::vector<Monitor>& monitors = it.second;
4467 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004468 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004469 return it.first;
4470 }
4471 }
4472 }
4473 return std::nullopt;
4474}
4475
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004476sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4477 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004478 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004479 }
4480
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004481 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004482 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004483 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004484 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485 }
4486 }
Robert Carr4e670e52018-08-15 13:26:12 -07004487
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004488 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489}
4490
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004491void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4492 const sp<Connection>& connection, uint32_t seq,
4493 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004494 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4495 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 commandEntry->connection = connection;
4497 commandEntry->eventTime = currentTime;
4498 commandEntry->seq = seq;
4499 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004500 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501}
4502
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004503void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4504 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004506 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004508 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4509 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004511 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512}
4513
chaviw0c06c6e2019-01-09 13:27:07 -08004514void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004515 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004516 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4517 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004518 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4519 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004520 commandEntry->oldToken = oldToken;
4521 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004522 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004523}
4524
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004525void InputDispatcher::onAnrLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004526 const sp<InputApplicationHandle>& applicationHandle,
4527 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4528 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4530 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4531 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004532 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4533 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4534 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535
4536 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004537 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 struct tm tm;
4539 localtime_r(&t, &tm);
4540 char timestr[64];
4541 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004542 mLastAnrState.clear();
4543 mLastAnrState += INDENT "ANR:\n";
4544 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
4545 mLastAnrState +=
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004546 StringPrintf(INDENT2 "Window: %s\n",
4547 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004548 mLastAnrState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4549 mLastAnrState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4550 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason);
4551 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004553 std::unique_ptr<CommandEntry> commandEntry =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004554 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004556 commandEntry->inputChannel =
4557 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004559 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560}
4561
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004562void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 mLock.unlock();
4564
4565 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4566
4567 mLock.lock();
4568}
4569
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004570void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571 sp<Connection> connection = commandEntry->connection;
4572
4573 if (connection->status != Connection::STATUS_ZOMBIE) {
4574 mLock.unlock();
4575
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004576 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577
4578 mLock.lock();
4579 }
4580}
4581
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004582void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004583 sp<IBinder> oldToken = commandEntry->oldToken;
4584 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004585 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004586 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004587 mLock.lock();
4588}
4589
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004590void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004591 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004592 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593 mLock.unlock();
4594
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004595 nsecs_t newTimeout =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004596 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597
4598 mLock.lock();
4599
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004600 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601}
4602
4603void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4604 CommandEntry* commandEntry) {
4605 KeyEntry* entry = commandEntry->keyEntry;
4606
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004607 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608
4609 mLock.unlock();
4610
Michael Wright2b3c3302018-03-02 17:19:13 +00004611 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004612 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004613 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004614 : nullptr;
4615 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004616 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4617 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004618 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620
4621 mLock.lock();
4622
4623 if (delay < 0) {
4624 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4625 } else if (!delay) {
4626 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4627 } else {
4628 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4629 entry->interceptKeyWakeupTime = now() + delay;
4630 }
4631 entry->release();
4632}
4633
chaviwfd6d3512019-03-25 13:23:49 -07004634void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4635 mLock.unlock();
4636 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4637 mLock.lock();
4638}
4639
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004640void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004642 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004644 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645
4646 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004647 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004648 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004649 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004651 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004652
4653 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4654 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4655 std::string msg =
4656 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4657 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4658 dispatchEntry->eventEntry->appendDescription(msg);
4659 ALOGI("%s", msg.c_str());
4660 }
4661
4662 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004663 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004664 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4665 restartEvent =
4666 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004667 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004668 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4669 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4670 handled);
4671 } else {
4672 restartEvent = false;
4673 }
4674
4675 // Dequeue the event and start the next cycle.
4676 // Note that because the lock might have been released, it is possible that the
4677 // contents of the wait queue to have been drained, so we need to double-check
4678 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004679 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4680 if (dispatchEntryIt != connection->waitQueue.end()) {
4681 dispatchEntry = *dispatchEntryIt;
4682 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004683 traceWaitQueueLength(connection);
4684 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004685 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004686 traceOutboundQueueLength(connection);
4687 } else {
4688 releaseDispatchEntry(dispatchEntry);
4689 }
4690 }
4691
4692 // Start the next dispatch cycle for this connection.
4693 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694}
4695
4696bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004697 DispatchEntry* dispatchEntry,
4698 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004699 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004700 if (!handled) {
4701 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004702 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004703 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004704 return false;
4705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004707 // Get the fallback key state.
4708 // Clear it out after dispatching the UP.
4709 int32_t originalKeyCode = keyEntry->keyCode;
4710 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4711 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4712 connection->inputState.removeFallbackKey(originalKeyCode);
4713 }
4714
4715 if (handled || !dispatchEntry->hasForegroundTarget()) {
4716 // If the application handles the original key for which we previously
4717 // generated a fallback or if the window is not a foreground window,
4718 // then cancel the associated fallback key, if any.
4719 if (fallbackKeyCode != -1) {
4720 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004722 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004723 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4724 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4725 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004727 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004728 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729
4730 mLock.unlock();
4731
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004732 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004733 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734
4735 mLock.lock();
4736
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004737 // Cancel the fallback key.
4738 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004740 "application handled the original non-fallback key "
4741 "or is no longer a foreground target, "
4742 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 options.keyCode = fallbackKeyCode;
4744 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004746 connection->inputState.removeFallbackKey(originalKeyCode);
4747 }
4748 } else {
4749 // If the application did not handle a non-fallback key, first check
4750 // that we are in a good state to perform unhandled key event processing
4751 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004752 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004753 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004755 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004756 "since this is not an initial down. "
4757 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4758 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004760 return false;
4761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004763 // Dispatch the unhandled key to the policy.
4764#if DEBUG_OUTBOUND_EVENT_DETAILS
4765 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004766 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4767 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004768#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004769 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004770
4771 mLock.unlock();
4772
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004773 bool fallback =
4774 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4775 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004776
4777 mLock.lock();
4778
4779 if (connection->status != Connection::STATUS_NORMAL) {
4780 connection->inputState.removeFallbackKey(originalKeyCode);
4781 return false;
4782 }
4783
4784 // Latch the fallback keycode for this key on an initial down.
4785 // The fallback keycode cannot change at any other point in the lifecycle.
4786 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004788 fallbackKeyCode = event.getKeyCode();
4789 } else {
4790 fallbackKeyCode = AKEYCODE_UNKNOWN;
4791 }
4792 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4793 }
4794
4795 ALOG_ASSERT(fallbackKeyCode != -1);
4796
4797 // Cancel the fallback key if the policy decides not to send it anymore.
4798 // We will continue to dispatch the key to the policy but we will no
4799 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004800 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4801 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004802#if DEBUG_OUTBOUND_EVENT_DETAILS
4803 if (fallback) {
4804 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004805 "as a fallback for %d, but on the DOWN it had requested "
4806 "to send %d instead. Fallback canceled.",
4807 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004808 } else {
4809 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004810 "but on the DOWN it had requested to send %d. "
4811 "Fallback canceled.",
4812 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004813 }
4814#endif
4815
4816 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4817 "canceling fallback, policy no longer desires it");
4818 options.keyCode = fallbackKeyCode;
4819 synthesizeCancelationEventsForConnectionLocked(connection, options);
4820
4821 fallback = false;
4822 fallbackKeyCode = AKEYCODE_UNKNOWN;
4823 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004824 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004825 }
4826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827
4828#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004829 {
4830 std::string msg;
4831 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4832 connection->inputState.getFallbackKeys();
4833 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004834 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004836 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004837 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004838 }
4839#endif
4840
4841 if (fallback) {
4842 // Restart the dispatch cycle using the fallback key.
4843 keyEntry->eventTime = event.getEventTime();
4844 keyEntry->deviceId = event.getDeviceId();
4845 keyEntry->source = event.getSource();
4846 keyEntry->displayId = event.getDisplayId();
4847 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4848 keyEntry->keyCode = fallbackKeyCode;
4849 keyEntry->scanCode = event.getScanCode();
4850 keyEntry->metaState = event.getMetaState();
4851 keyEntry->repeatCount = event.getRepeatCount();
4852 keyEntry->downTime = event.getDownTime();
4853 keyEntry->syntheticRepeat = false;
4854
4855#if DEBUG_OUTBOUND_EVENT_DETAILS
4856 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004857 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4858 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004859#endif
4860 return true; // restart the event
4861 } else {
4862#if DEBUG_OUTBOUND_EVENT_DETAILS
4863 ALOGD("Unhandled key event: No fallback key.");
4864#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004865
4866 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004867 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 }
4869 }
4870 return false;
4871}
4872
4873bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004874 DispatchEntry* dispatchEntry,
4875 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 return false;
4877}
4878
4879void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4880 mLock.unlock();
4881
4882 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4883
4884 mLock.lock();
4885}
4886
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004887KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4888 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004889 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004890 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
4891 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004892 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893}
4894
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004895void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004896 int32_t injectionResult,
4897 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898 // TODO Write some statistics about how long we spend waiting.
4899}
4900
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004901/**
4902 * Report the touch event latency to the statsd server.
4903 * Input events are reported for statistics if:
4904 * - This is a touchscreen event
4905 * - InputFilter is not enabled
4906 * - Event is not injected or synthesized
4907 *
4908 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4909 * from getting aggregated with the "old" data.
4910 */
4911void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4912 REQUIRES(mLock) {
4913 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4914 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4915 if (!reportForStatistics) {
4916 return;
4917 }
4918
4919 if (mTouchStatistics.shouldReport()) {
4920 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4921 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4922 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4923 mTouchStatistics.reset();
4924 }
4925 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4926 mTouchStatistics.addValue(latencyMicros);
4927}
4928
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929void InputDispatcher::traceInboundQueueLengthLocked() {
4930 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004931 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932 }
4933}
4934
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004935void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936 if (ATRACE_ENABLED()) {
4937 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004938 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004939 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940 }
4941}
4942
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004943void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 if (ATRACE_ENABLED()) {
4945 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004946 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004947 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948 }
4949}
4950
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004951void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004952 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004954 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955 dumpDispatchStateLocked(dump);
4956
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004957 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004958 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004959 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960 }
4961}
4962
4963void InputDispatcher::monitor() {
4964 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004965 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004966 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004967 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968}
4969
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004970/**
4971 * Wake up the dispatcher and wait until it processes all events and commands.
4972 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4973 * this method can be safely called from any thread, as long as you've ensured that
4974 * the work you are interested in completing has already been queued.
4975 */
4976bool InputDispatcher::waitForIdle() {
4977 /**
4978 * Timeout should represent the longest possible time that a device might spend processing
4979 * events and commands.
4980 */
4981 constexpr std::chrono::duration TIMEOUT = 100ms;
4982 std::unique_lock lock(mLock);
4983 mLooper->wake();
4984 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4985 return result == std::cv_status::no_timeout;
4986}
4987
Garfield Tane84e6f92019-08-29 17:28:41 -07004988} // namespace android::inputdispatcher