blob: 6d8f0367c9b4347bf4b46381db95609f0eb0751c [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);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001160 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1161 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1162 return true;
1163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001165 CancelationOptions::Mode mode(isPointerEvent
1166 ? CancelationOptions::CANCEL_POINTER_EVENTS
1167 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1168 CancelationOptions options(mode, "input event injection failed");
1169 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 return true;
1171 }
1172
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001173 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001174 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001176 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001177 std::unordered_map<int32_t, TouchState>::iterator it =
1178 mTouchStatesByDisplay.find(entry->displayId);
1179 if (it != mTouchStatesByDisplay.end()) {
1180 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001181 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001182 // The event has gone through these portal windows, so we add monitoring targets of
1183 // the corresponding displays as well.
1184 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001185 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001186 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001187 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001188 }
1189 }
1190 }
1191 }
1192
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 // Dispatch the motion.
1194 if (conflictingPointerActions) {
1195 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001196 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 synthesizeCancelationEventsForAllConnectionsLocked(options);
1198 }
1199 dispatchEventLocked(currentTime, entry, inputTargets);
1200 return true;
1201}
1202
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001203void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001205 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001206 ", policyFlags=0x%x, "
1207 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1208 "metaState=0x%x, buttonState=0x%x,"
1209 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001210 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1211 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1212 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001214 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001216 "x=%f, y=%f, pressure=%f, size=%f, "
1217 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1218 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001219 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1220 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1221 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1222 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1223 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1224 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1225 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1226 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1227 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1228 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 }
1230#endif
1231}
1232
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001233void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1234 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001235 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236#if DEBUG_DISPATCH_CYCLE
1237 ALOGD("dispatchEventToCurrentInputTargets");
1238#endif
1239
1240 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1241
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001242 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001244 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001245 sp<Connection> connection =
1246 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001247 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001248 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001250 if (DEBUG_FOCUS) {
1251 ALOGD("Dropping event delivery to target with channel '%s' because it "
1252 "is no longer registered with the input dispatcher.",
1253 inputTarget.inputChannel->getName().c_str());
1254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 }
1256 }
1257}
1258
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001259int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001260 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001262 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001263 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001265 if (DEBUG_FOCUS) {
1266 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1267 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1269 mInputTargetWaitStartTime = currentTime;
1270 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1271 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001272 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 }
1274 } else {
1275 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001276 ALOGI("Waiting for application to become ready for input: %s. Reason: %s",
1277 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001279 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001281 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001282 timeout =
1283 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 } else {
1285 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1286 }
1287
1288 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1289 mInputTargetWaitStartTime = currentTime;
1290 mInputTargetWaitTimeoutTime = currentTime + timeout;
1291 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001292 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293
Yi Kong9b14ac62018-07-17 13:48:38 -07001294 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001295 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 }
Robert Carr740167f2018-10-11 19:03:41 -07001297 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1298 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 }
1300 }
1301 }
1302
1303 if (mInputTargetWaitTimeoutExpired) {
1304 return INPUT_EVENT_INJECTION_TIMED_OUT;
1305 }
1306
1307 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001308 onAnrLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001309 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310
1311 // Force poll loop to wake up immediately on next iteration once we get the
1312 // ANR response back from the policy.
1313 *nextWakeupTime = LONG_LONG_MIN;
1314 return INPUT_EVENT_INJECTION_PENDING;
1315 } else {
1316 // Force poll loop to wake up when timeout is due.
1317 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1318 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1319 }
1320 return INPUT_EVENT_INJECTION_PENDING;
1321 }
1322}
1323
Robert Carr803535b2018-08-02 16:38:15 -07001324void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001325 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
1326 TouchState& state = pair.second;
Robert Carr803535b2018-08-02 16:38:15 -07001327 state.removeWindowByToken(token);
1328 }
1329}
1330
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001331void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001332 nsecs_t newTimeout, const sp<IBinder>& inputConnectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333 if (newTimeout > 0) {
1334 // Extend the timeout.
1335 mInputTargetWaitTimeoutTime = now() + newTimeout;
1336 } else {
1337 // Give up.
1338 mInputTargetWaitTimeoutExpired = true;
1339
1340 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001341 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001342 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001343 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001345 if (connection->status == Connection::STATUS_NORMAL) {
1346 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1347 "application not responding");
1348 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 }
1350 }
1351 }
1352}
1353
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07001354void InputDispatcher::resetAnrTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001355 if (DEBUG_FOCUS) {
1356 ALOGD("Resetting ANR timeouts.");
1357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358
1359 // Reset input target wait timeout.
1360 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001361 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362}
1363
Tiger Huang721e26f2018-07-24 22:26:19 +08001364/**
1365 * Get the display id that the given event should go to. If this event specifies a valid display id,
1366 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1367 * Focused display is the display that the user most recently interacted with.
1368 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001369int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001370 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001371 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001372 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001373 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1374 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001375 break;
1376 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001377 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001378 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1379 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001380 break;
1381 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001382 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001383 case EventEntry::Type::CONFIGURATION_CHANGED:
1384 case EventEntry::Type::DEVICE_RESET: {
1385 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001386 return ADISPLAY_ID_NONE;
1387 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001388 }
1389 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1390}
1391
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001393 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001394 std::vector<InputTarget>& inputTargets,
1395 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001396 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397
Tiger Huang721e26f2018-07-24 22:26:19 +08001398 int32_t displayId = getTargetDisplayId(entry);
1399 sp<InputWindowHandle> focusedWindowHandle =
1400 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1401 sp<InputApplicationHandle> focusedApplicationHandle =
1402 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1403
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404 // If there is no currently focused window and no focused application
1405 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001406 if (focusedWindowHandle == nullptr) {
1407 if (focusedApplicationHandle != nullptr) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001408 return handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1409 nullptr, nextWakeupTime,
1410 "Waiting because no window has focus but there is "
1411 "a focused application that may eventually add a "
1412 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413 }
1414
Arthur Hung3b413f22018-10-26 18:05:34 +08001415 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001416 "%" PRId32 ".",
1417 displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001418 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 }
1420
1421 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001422 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001423 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 }
1425
Jeff Brownffb49772014-10-10 19:01:34 -07001426 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001427 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001428 if (!reason.empty()) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001429 return handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1430 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431 }
1432
1433 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001434 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001435 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1436 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437
1438 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001439 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440}
1441
1442int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001443 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001444 std::vector<InputTarget>& inputTargets,
1445 nsecs_t* nextWakeupTime,
1446 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001447 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 enum InjectionPermission {
1449 INJECTION_PERMISSION_UNKNOWN,
1450 INJECTION_PERMISSION_GRANTED,
1451 INJECTION_PERMISSION_DENIED
1452 };
1453
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 // For security reasons, we defer updating the touch state until we are sure that
1455 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001456 int32_t displayId = entry.displayId;
1457 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1459
1460 // Update the touch state as needed based on the properties of the touch event.
1461 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1462 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1463 sp<InputWindowHandle> newHoverWindowHandle;
1464
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001465 // Copy current touch state into tempTouchState.
1466 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1467 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001468 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001469 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001470 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1471 mTouchStatesByDisplay.find(displayId);
1472 if (oldStateIt != mTouchStatesByDisplay.end()) {
1473 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001474 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001475 }
1476
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001477 bool isSplit = tempTouchState.split;
1478 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1479 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1480 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001481 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1482 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1483 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1484 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1485 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001486 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 bool wrongDevice = false;
1488 if (newGesture) {
1489 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001490 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001491 ALOGI("Dropping event because a pointer for a different device is already down "
1492 "in display %" PRId32,
1493 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001494 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1496 switchedDevice = false;
1497 wrongDevice = true;
1498 goto Failed;
1499 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001500 tempTouchState.reset();
1501 tempTouchState.down = down;
1502 tempTouchState.deviceId = entry.deviceId;
1503 tempTouchState.source = entry.source;
1504 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001506 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001507 ALOGI("Dropping move event because a pointer for a different device is already active "
1508 "in display %" PRId32,
1509 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001510 // TODO: test multiple simultaneous input streams.
1511 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1512 switchedDevice = false;
1513 wrongDevice = true;
1514 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 }
1516
1517 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1518 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1519
Garfield Tan00f511d2019-06-12 16:55:40 -07001520 int32_t x;
1521 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001523 // Always dispatch mouse events to cursor position.
1524 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001525 x = int32_t(entry.xCursorPosition);
1526 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001527 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001528 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1529 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001530 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001531 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001532 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001533 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1534 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001535
1536 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001537 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001538 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001541 if (newTouchedWindowHandle != nullptr &&
1542 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001543 // New window supports splitting, but we should never split mouse events.
1544 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 } else if (isSplit) {
1546 // New window does not support splitting but we have already split events.
1547 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001548 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 }
1550
1551 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001552 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001554 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001555 }
1556
1557 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1558 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001559 "(%d, %d) in display %" PRId32 ".",
1560 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001561 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1562 goto Failed;
1563 }
1564
1565 if (newTouchedWindowHandle != nullptr) {
1566 // Set target flags.
1567 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1568 if (isSplit) {
1569 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001571 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1572 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1573 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1574 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1575 }
1576
1577 // Update hover state.
1578 if (isHoverAction) {
1579 newHoverWindowHandle = newTouchedWindowHandle;
1580 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1581 newHoverWindowHandle = mLastHoverWindowHandle;
1582 }
1583
1584 // Update the temporary touch state.
1585 BitSet32 pointerIds;
1586 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001587 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001588 pointerIds.markBit(pointerId);
1589 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001590 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 }
1592
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001593 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 } else {
1595 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1596
1597 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001598 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001599 if (DEBUG_FOCUS) {
1600 ALOGD("Dropping event because the pointer is not down or we previously "
1601 "dropped the pointer down event in display %" PRId32,
1602 displayId);
1603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1605 goto Failed;
1606 }
1607
1608 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001609 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001610 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001611 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1612 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613
1614 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001615 tempTouchState.getFirstForegroundWindowHandle();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001617 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001618 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1619 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001620 if (DEBUG_FOCUS) {
1621 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1622 oldTouchedWindowHandle->getName().c_str(),
1623 newTouchedWindowHandle->getName().c_str(), displayId);
1624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001626 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1627 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1628 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629
1630 // Make a slippery entrance into the new window.
1631 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1632 isSplit = true;
1633 }
1634
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001635 int32_t targetFlags =
1636 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 if (isSplit) {
1638 targetFlags |= InputTarget::FLAG_SPLIT;
1639 }
1640 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1641 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1642 }
1643
1644 BitSet32 pointerIds;
1645 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001646 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001648 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 }
1650 }
1651 }
1652
1653 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1654 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001655 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656#if DEBUG_HOVER
1657 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001658 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001660 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1661 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 }
1663
1664 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001665 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666#if DEBUG_HOVER
1667 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001668 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001670 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1671 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1672 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 }
1674 }
1675
1676 // Check permission to inject into all touched foreground windows and ensure there
1677 // is at least one touched foreground window.
1678 {
1679 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001680 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1682 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001683 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1685 injectionPermission = INJECTION_PERMISSION_DENIED;
1686 goto Failed;
1687 }
1688 }
1689 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001690 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001691 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001692 ALOGI("Dropping event because there is no touched foreground window in display "
1693 "%" PRId32 " or gesture monitor to receive it.",
1694 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1696 goto Failed;
1697 }
1698
1699 // Permission granted to injection into all touched foreground windows.
1700 injectionPermission = INJECTION_PERMISSION_GRANTED;
1701 }
1702
1703 // Check whether windows listening for outside touches are owned by the same UID. If it is
1704 // set the policy flag that we will not reveal coordinate information to this window.
1705 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1706 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001707 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001708 if (foregroundWindowHandle) {
1709 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001710 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001711 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1712 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1713 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001714 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1715 InputTarget::FLAG_ZERO_COORDS,
1716 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 }
1719 }
1720 }
1721 }
1722
1723 // Ensure all touched foreground windows are ready for new input.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001724 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001726 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001727 std::string reason =
1728 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1729 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001730 if (!reason.empty()) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001731 return handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1732 touchedWindow.windowHandle, nextWakeupTime,
1733 reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 }
1735 }
1736 }
1737
1738 // If this is the first pointer going down and the touched window has a wallpaper
1739 // then also add the touched wallpaper windows so they are locked in for the duration
1740 // of the touch gesture.
1741 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1742 // engine only supports touch events. We would need to add a mechanism similar
1743 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1744 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1745 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001746 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001747 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001748 const std::vector<sp<InputWindowHandle>> windowHandles =
1749 getWindowHandlesLocked(displayId);
1750 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001752 if (info->displayId == displayId &&
1753 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001754 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001755 .addOrUpdateWindow(windowHandle,
1756 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1757 InputTarget::
1758 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1759 InputTarget::FLAG_DISPATCH_AS_IS,
1760 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 }
1762 }
1763 }
1764 }
1765
1766 // Success! Output targets.
1767 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1768
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001769 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001771 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 }
1773
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001774 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001775 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001776 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001777 }
1778
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779 // Drop the outside or hover touch windows since we will not care about them
1780 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001781 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782
1783Failed:
1784 // Check injection permission once and for all.
1785 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001786 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 injectionPermission = INJECTION_PERMISSION_GRANTED;
1788 } else {
1789 injectionPermission = INJECTION_PERMISSION_DENIED;
1790 }
1791 }
1792
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001793 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1794 return injectionResult;
1795 }
1796
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001798 if (!wrongDevice) {
1799 if (switchedDevice) {
1800 if (DEBUG_FOCUS) {
1801 ALOGD("Conflicting pointer actions: Switched to a different device.");
1802 }
1803 *outConflictingPointerActions = true;
1804 }
1805
1806 if (isHoverAction) {
1807 // Started hovering, therefore no longer down.
1808 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001809 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001810 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1811 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 *outConflictingPointerActions = true;
1814 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001815 tempTouchState.reset();
1816 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1817 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1818 tempTouchState.deviceId = entry.deviceId;
1819 tempTouchState.source = entry.source;
1820 tempTouchState.displayId = displayId;
1821 }
1822 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1823 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1824 // All pointers up or canceled.
1825 tempTouchState.reset();
1826 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1827 // First pointer went down.
1828 if (oldState && oldState->down) {
1829 if (DEBUG_FOCUS) {
1830 ALOGD("Conflicting pointer actions: Down received while already down.");
1831 }
1832 *outConflictingPointerActions = true;
1833 }
1834 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1835 // One pointer went up.
1836 if (isSplit) {
1837 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1838 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001840 for (size_t i = 0; i < tempTouchState.windows.size();) {
1841 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1842 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1843 touchedWindow.pointerIds.clearBit(pointerId);
1844 if (touchedWindow.pointerIds.isEmpty()) {
1845 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1846 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001849 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001851 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001852 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001853
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001854 // Save changes unless the action was scroll in which case the temporary touch
1855 // state was only valid for this one action.
1856 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1857 if (tempTouchState.displayId >= 0) {
1858 mTouchStatesByDisplay[displayId] = tempTouchState;
1859 } else {
1860 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001862 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001864 // Update hover state.
1865 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 }
1867
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 return injectionResult;
1869}
1870
1871void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001872 int32_t targetFlags, BitSet32 pointerIds,
1873 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001874 std::vector<InputTarget>::iterator it =
1875 std::find_if(inputTargets.begin(), inputTargets.end(),
1876 [&windowHandle](const InputTarget& inputTarget) {
1877 return inputTarget.inputChannel->getConnectionToken() ==
1878 windowHandle->getToken();
1879 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00001880
Chavi Weingarten114b77f2020-01-15 22:35:10 +00001881 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001882
1883 if (it == inputTargets.end()) {
1884 InputTarget inputTarget;
1885 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1886 if (inputChannel == nullptr) {
1887 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1888 return;
1889 }
1890 inputTarget.inputChannel = inputChannel;
1891 inputTarget.flags = targetFlags;
1892 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
1893 inputTargets.push_back(inputTarget);
1894 it = inputTargets.end() - 1;
1895 }
1896
1897 ALOG_ASSERT(it->flags == targetFlags);
1898 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
1899
1900 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
1901 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902}
1903
Michael Wright3dd60e22019-03-27 22:06:44 +00001904void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001905 int32_t displayId, float xOffset,
1906 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001907 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1908 mGlobalMonitorsByDisplay.find(displayId);
1909
1910 if (it != mGlobalMonitorsByDisplay.end()) {
1911 const std::vector<Monitor>& monitors = it->second;
1912 for (const Monitor& monitor : monitors) {
1913 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 }
1916}
1917
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001918void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1919 float yOffset,
1920 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001921 InputTarget target;
1922 target.inputChannel = monitor.inputChannel;
1923 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001924 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00001925 inputTargets.push_back(target);
1926}
1927
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001929 const InjectionState* injectionState) {
1930 if (injectionState &&
1931 (windowHandle == nullptr ||
1932 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1933 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001934 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001936 "owned by uid %d",
1937 injectionState->injectorPid, injectionState->injectorUid,
1938 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 } else {
1940 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001941 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942 }
1943 return false;
1944 }
1945 return true;
1946}
1947
Robert Carrc9bf1d32020-04-13 17:21:08 -07001948/**
1949 * Indicate whether one window handle should be considered as obscuring
1950 * another window handle. We only check a few preconditions. Actually
1951 * checking the bounds is left to the caller.
1952 */
1953static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
1954 const sp<InputWindowHandle>& otherHandle) {
1955 // Compare by token so cloned layers aren't counted
1956 if (haveSameToken(windowHandle, otherHandle)) {
1957 return false;
1958 }
1959 auto info = windowHandle->getInfo();
1960 auto otherInfo = otherHandle->getInfo();
1961 if (!otherInfo->visible) {
1962 return false;
1963 } else if (info->ownerPid == otherInfo->ownerPid && otherHandle->getToken() == nullptr) {
1964 // In general, if ownerPid is the same we don't want to generate occlusion
1965 // events. This line is now necessary since we are including all Surfaces
1966 // in occlusion calculation, so if we didn't check PID like this SurfaceView
1967 // would occlude their parents. On the other hand before we started including
1968 // all surfaces in occlusion calculation and had this line, we would count
1969 // windows with an input channel from the same PID as occluding, and so we
1970 // preserve this behavior with the getToken() == null check.
1971 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07001972 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07001973 return false;
1974 } else if (otherInfo->displayId != info->displayId) {
1975 return false;
1976 }
1977 return true;
1978}
1979
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001980bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1981 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001983 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1984 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07001985 if (windowHandle == otherHandle) {
1986 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07001989 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08001990 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 return true;
1992 }
1993 }
1994 return false;
1995}
1996
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001997bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1998 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001999 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002000 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002001 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002002 if (windowHandle == otherHandle) {
2003 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002004 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002005 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002006 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002007 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002008 return true;
2009 }
2010 }
2011 return false;
2012}
2013
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002014std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
2015 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002016 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07002017 // If the window is paused then keep waiting.
2018 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002019 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002020 }
2021
2022 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07002023 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002024 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002025 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002026 "registered with the input dispatcher. The window may be in the "
2027 "process of being removed.",
2028 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002029 }
2030
2031 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07002032 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002033 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002034 "The window may be in the process of being removed.",
2035 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07002036 }
2037
2038 // If the connection is backed up then keep waiting.
2039 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002040 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002041 "Outbound queue length: %zu. Wait queue length: %zu.",
2042 targetType, connection->outboundQueue.size(),
2043 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07002044 }
2045
2046 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002047 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07002048 // If the event is a key event, then we must wait for all previous events to
2049 // complete before delivering it because previous events may have the
2050 // side-effect of transferring focus to a different window and we want to
2051 // ensure that the following keys are sent to the new window.
2052 //
2053 // Suppose the user touches a button in a window then immediately presses "A".
2054 // If the button causes a pop-up window to appear then we want to ensure that
2055 // the "A" key is delivered to the new pop-up window. This is because users
2056 // often anticipate pending UI changes when typing on a keyboard.
2057 // To obtain this behavior, we must serialize key events with respect to all
2058 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002059 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002060 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002061 "finished processing all of the input events that were previously "
2062 "delivered to it. Outbound queue length: %zu. Wait queue length: "
2063 "%zu.",
2064 targetType, connection->outboundQueue.size(),
2065 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066 }
Jeff Brownffb49772014-10-10 19:01:34 -07002067 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068 // Touch events can always be sent to a window immediately because the user intended
2069 // to touch whatever was visible at the time. Even if focus changes or a new
2070 // window appears moments later, the touch event was meant to be delivered to
2071 // whatever window happened to be on screen at the time.
2072 //
2073 // Generic motion events, such as trackball or joystick events are a little trickier.
2074 // Like key events, generic motion events are delivered to the focused window.
2075 // Unlike key events, generic motion events don't tend to transfer focus to other
2076 // windows and it is not important for them to be serialized. So we prefer to deliver
2077 // generic motion events as soon as possible to improve efficiency and reduce lag
2078 // through batching.
2079 //
2080 // The one case where we pause input event delivery is when the wait queue is piling
2081 // up with lots of events because the application is not responding.
2082 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002083 if (!connection->waitQueue.empty() &&
2084 currentTime >=
2085 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002086 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002087 "finished processing certain input events that were delivered to "
2088 "it over "
2089 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
2090 "%0.1fms.",
2091 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
2092 connection->waitQueue.size(),
2093 (currentTime - connection->waitQueue.front()->deliveryTime) *
2094 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095 }
2096 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002097 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098}
2099
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002100std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 const sp<InputApplicationHandle>& applicationHandle,
2102 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002103 if (applicationHandle != nullptr) {
2104 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002105 std::string label(applicationHandle->getName());
2106 label += " - ";
2107 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 return label;
2109 } else {
2110 return applicationHandle->getName();
2111 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002112 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 return windowHandle->getName();
2114 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002115 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116 }
2117}
2118
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002119void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002120 if (eventEntry.type == EventEntry::Type::FOCUS) {
2121 // Focus events are passed to apps, but do not represent user activity.
2122 return;
2123 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002124 int32_t displayId = getTargetDisplayId(eventEntry);
2125 sp<InputWindowHandle> focusedWindowHandle =
2126 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2127 if (focusedWindowHandle != nullptr) {
2128 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2130#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002131 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132#endif
2133 return;
2134 }
2135 }
2136
2137 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002138 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002139 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002140 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2141 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002142 return;
2143 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002145 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002146 eventType = USER_ACTIVITY_EVENT_TOUCH;
2147 }
2148 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002150 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002151 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2152 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002153 return;
2154 }
2155 eventType = USER_ACTIVITY_EVENT_BUTTON;
2156 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002158 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002159 case EventEntry::Type::CONFIGURATION_CHANGED:
2160 case EventEntry::Type::DEVICE_RESET: {
2161 LOG_ALWAYS_FATAL("%s events are not user activity",
2162 EventEntry::typeToString(eventEntry.type));
2163 break;
2164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 }
2166
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002167 std::unique_ptr<CommandEntry> commandEntry =
2168 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002169 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002171 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172}
2173
2174void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002175 const sp<Connection>& connection,
2176 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002177 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002178 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002179 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002180 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002181 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002182 ATRACE_NAME(message.c_str());
2183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184#if DEBUG_DISPATCH_CYCLE
2185 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002186 "globalScaleFactor=%f, pointerIds=0x%x %s",
2187 connection->getInputChannelName().c_str(), inputTarget.flags,
2188 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2189 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190#endif
2191
2192 // Skip this event if the connection status is not normal.
2193 // We don't want to enqueue additional outbound events if the connection is broken.
2194 if (connection->status != Connection::STATUS_NORMAL) {
2195#if DEBUG_DISPATCH_CYCLE
2196 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002197 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198#endif
2199 return;
2200 }
2201
2202 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002203 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2204 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2205 "Entry type %s should not have FLAG_SPLIT",
2206 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002208 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002209 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002210 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002211 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212 if (!splitMotionEntry) {
2213 return; // split event was dropped
2214 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002215 if (DEBUG_FOCUS) {
2216 ALOGD("channel '%s' ~ Split motion event.",
2217 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002218 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002219 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002220 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 splitMotionEntry->release();
2222 return;
2223 }
2224 }
2225
2226 // Not splitting. Enqueue dispatch entries for the event as is.
2227 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2228}
2229
2230void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002231 const sp<Connection>& connection,
2232 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002233 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002234 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002235 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002236 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002237 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002238 ATRACE_NAME(message.c_str());
2239 }
2240
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002241 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242
2243 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002244 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002245 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002246 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002247 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002248 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002249 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002250 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002251 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002252 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002253 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002254 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002255 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256
2257 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002258 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259 startDispatchCycleLocked(currentTime, connection);
2260 }
2261}
2262
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002263void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2264 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002265 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002266 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002267 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002268 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2269 connection->getInputChannelName().c_str(),
2270 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002271 ATRACE_NAME(message.c_str());
2272 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002273 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 if (!(inputTargetFlags & dispatchMode)) {
2275 return;
2276 }
2277 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2278
2279 // This is a new event.
2280 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002281 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002282 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002284 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2285 // different EventEntry than what was passed in.
2286 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002288 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002289 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002290 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002291 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002292 dispatchEntry->resolvedAction = keyEntry.action;
2293 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2296 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002298 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2299 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002301 return; // skip the inconsistent event
2302 }
2303 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002306 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002307 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002308 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2309 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2310 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2311 static_cast<int32_t>(IdGenerator::Source::OTHER);
2312 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002313 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2314 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2315 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2316 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2317 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2318 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2319 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2320 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2321 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2322 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2323 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002324 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002325 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002326 }
2327 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002328 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2329 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002331 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2332 "event",
2333 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002335 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2336 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002338 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002339 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2340 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2341 }
2342 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2343 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002346 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2347 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002349 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2350 "event",
2351 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002353 return; // skip the inconsistent event
2354 }
2355
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002356 dispatchEntry->resolvedEventId =
2357 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2358 ? mIdGenerator.nextId()
2359 : motionEntry.id;
2360 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2361 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2362 ") to MotionEvent(id=0x%" PRIx32 ").",
2363 motionEntry.id, dispatchEntry->resolvedEventId);
2364 ATRACE_NAME(message.c_str());
2365 }
2366
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002367 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002368 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002369
2370 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002372 case EventEntry::Type::FOCUS: {
2373 break;
2374 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002375 case EventEntry::Type::CONFIGURATION_CHANGED:
2376 case EventEntry::Type::DEVICE_RESET: {
2377 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002378 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002379 break;
2380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381 }
2382
2383 // Remember that we are waiting for this dispatch to complete.
2384 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002385 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 }
2387
2388 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002389 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002390 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002391}
2392
chaviwfd6d3512019-03-25 13:23:49 -07002393void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002394 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002395 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002396 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2397 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002398 return;
2399 }
2400
2401 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2402 if (inputWindowHandle == nullptr) {
2403 return;
2404 }
2405
chaviw8c9cf542019-03-25 13:02:48 -07002406 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002407 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002408
2409 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2410
2411 if (!hasFocusChanged) {
2412 return;
2413 }
2414
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002415 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2416 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002417 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002418 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419}
2420
2421void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002422 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002423 if (ATRACE_ENABLED()) {
2424 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002425 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002426 ATRACE_NAME(message.c_str());
2427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002429 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430#endif
2431
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002432 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2433 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434 dispatchEntry->deliveryTime = currentTime;
2435
2436 // Publish the event.
2437 status_t status;
2438 EventEntry* eventEntry = dispatchEntry->eventEntry;
2439 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002440 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002441 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2442 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002444 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002445 status =
2446 connection->inputPublisher
2447 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2448 keyEntry->deviceId, keyEntry->source,
2449 keyEntry->displayId, std::move(hmac),
2450 dispatchEntry->resolvedAction,
2451 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2452 keyEntry->scanCode, keyEntry->metaState,
2453 keyEntry->repeatCount, keyEntry->downTime,
2454 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002455 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 }
2457
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002458 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002459 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002461 PointerCoords scaledCoords[MAX_POINTERS];
2462 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2463
chaviw82357092020-01-28 13:13:06 -08002464 // Set the X and Y offset and X and Y scale depending on the input source.
2465 float xOffset = 0.0f, yOffset = 0.0f;
2466 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002467 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2468 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2469 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002470 xScale = dispatchEntry->windowXScale;
2471 yScale = dispatchEntry->windowYScale;
2472 xOffset = dispatchEntry->xOffset * xScale;
2473 yOffset = dispatchEntry->yOffset * yScale;
2474 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002475 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2476 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002477 // Don't apply window scale here since we don't want scale to affect raw
2478 // coordinates. The scale will be sent back to the client and applied
2479 // later when requesting relative coordinates.
2480 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2481 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002482 }
2483 usingCoords = scaledCoords;
2484 }
2485 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002486 // We don't want the dispatch target to know.
2487 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2488 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2489 scaledCoords[i].clear();
2490 }
2491 usingCoords = scaledCoords;
2492 }
2493 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002494
2495 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002496
2497 // Publish the motion event.
2498 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002499 .publishMotionEvent(dispatchEntry->seq,
2500 dispatchEntry->resolvedEventId,
2501 motionEntry->deviceId, motionEntry->source,
2502 motionEntry->displayId, std::move(hmac),
2503 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002504 motionEntry->actionButton,
2505 dispatchEntry->resolvedFlags,
2506 motionEntry->edgeFlags, motionEntry->metaState,
2507 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002508 motionEntry->classification, xScale, yScale,
2509 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002510 motionEntry->yPrecision,
2511 motionEntry->xCursorPosition,
2512 motionEntry->yCursorPosition,
2513 motionEntry->downTime, motionEntry->eventTime,
2514 motionEntry->pointerCount,
2515 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002516 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002517 break;
2518 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002519 case EventEntry::Type::FOCUS: {
2520 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2521 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002522 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002523 focusEntry->hasFocus,
2524 mInTouchMode);
2525 break;
2526 }
2527
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002528 case EventEntry::Type::CONFIGURATION_CHANGED:
2529 case EventEntry::Type::DEVICE_RESET: {
2530 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2531 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002532 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 }
2535
2536 // Check the result.
2537 if (status) {
2538 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002539 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002541 "This is unexpected because the wait queue is empty, so the pipe "
2542 "should be empty and we shouldn't have any problems writing an "
2543 "event to it, status=%d",
2544 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2546 } else {
2547 // Pipe is full and we are waiting for the app to finish process some events
2548 // before sending more events to it.
2549#if DEBUG_DISPATCH_CYCLE
2550 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002551 "waiting for the application to catch up",
2552 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553#endif
2554 connection->inputPublisherBlocked = true;
2555 }
2556 } else {
2557 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002558 "status=%d",
2559 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002560 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2561 }
2562 return;
2563 }
2564
2565 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002566 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2567 connection->outboundQueue.end(),
2568 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002569 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002570 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002571 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 }
2573}
2574
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002575const std::array<uint8_t, 32> InputDispatcher::getSignature(
2576 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2577 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2578 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2579 // Only sign events up and down events as the purely move events
2580 // are tied to their up/down counterparts so signing would be redundant.
2581 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2582 verifiedEvent.actionMasked = actionMasked;
2583 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2584 return mHmacKeyManager.sign(verifiedEvent);
2585 }
2586 return INVALID_HMAC;
2587}
2588
2589const std::array<uint8_t, 32> InputDispatcher::getSignature(
2590 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2591 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2592 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2593 verifiedEvent.action = dispatchEntry.resolvedAction;
2594 return mHmacKeyManager.sign(verifiedEvent);
2595}
2596
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002598 const sp<Connection>& connection, uint32_t seq,
2599 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600#if DEBUG_DISPATCH_CYCLE
2601 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002602 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603#endif
2604
2605 connection->inputPublisherBlocked = false;
2606
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002607 if (connection->status == Connection::STATUS_BROKEN ||
2608 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 return;
2610 }
2611
2612 // Notify other system components and prepare to start the next dispatch cycle.
2613 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2614}
2615
2616void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002617 const sp<Connection>& connection,
2618 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619#if DEBUG_DISPATCH_CYCLE
2620 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002621 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622#endif
2623
2624 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002625 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002626 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002627 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002628 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629
2630 // The connection appears to be unrecoverably broken.
2631 // Ignore already broken or zombie connections.
2632 if (connection->status == Connection::STATUS_NORMAL) {
2633 connection->status = Connection::STATUS_BROKEN;
2634
2635 if (notify) {
2636 // Notify other system components.
2637 onDispatchCycleBrokenLocked(currentTime, connection);
2638 }
2639 }
2640}
2641
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002642void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2643 while (!queue.empty()) {
2644 DispatchEntry* dispatchEntry = queue.front();
2645 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002646 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 }
2648}
2649
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002650void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002652 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 }
2654 delete dispatchEntry;
2655}
2656
2657int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2658 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2659
2660 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002661 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002663 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002665 "fd=%d, events=0x%x",
2666 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667 return 0; // remove the callback
2668 }
2669
2670 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002671 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2673 if (!(events & ALOOPER_EVENT_INPUT)) {
2674 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002675 "events=0x%x",
2676 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677 return 1;
2678 }
2679
2680 nsecs_t currentTime = now();
2681 bool gotOne = false;
2682 status_t status;
2683 for (;;) {
2684 uint32_t seq;
2685 bool handled;
2686 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2687 if (status) {
2688 break;
2689 }
2690 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2691 gotOne = true;
2692 }
2693 if (gotOne) {
2694 d->runCommandsLockedInterruptible();
2695 if (status == WOULD_BLOCK) {
2696 return 1;
2697 }
2698 }
2699
2700 notify = status != DEAD_OBJECT || !connection->monitor;
2701 if (notify) {
2702 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002703 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704 }
2705 } else {
2706 // Monitor channels are never explicitly unregistered.
2707 // We do it automatically when the remote endpoint is closed so don't warn
2708 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002709 const bool stillHaveWindowHandle =
2710 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2711 nullptr;
2712 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713 if (notify) {
2714 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002715 "events=0x%x",
2716 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717 }
2718 }
2719
2720 // Unregister the channel.
2721 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2722 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002723 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724}
2725
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002726void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002728 for (const auto& pair : mConnectionsByFd) {
2729 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 }
2731}
2732
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002733void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002734 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002735 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2736 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2737}
2738
2739void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2740 const CancelationOptions& options,
2741 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2742 for (const auto& it : monitorsByDisplay) {
2743 const std::vector<Monitor>& monitors = it.second;
2744 for (const Monitor& monitor : monitors) {
2745 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002746 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002747 }
2748}
2749
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2751 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002752 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002753 if (connection == nullptr) {
2754 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002756
2757 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758}
2759
2760void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2761 const sp<Connection>& connection, const CancelationOptions& options) {
2762 if (connection->status == Connection::STATUS_BROKEN) {
2763 return;
2764 }
2765
2766 nsecs_t currentTime = now();
2767
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002768 std::vector<EventEntry*> cancelationEvents =
2769 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002771 if (cancelationEvents.empty()) {
2772 return;
2773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002775 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2776 "with reality: %s, mode=%d.",
2777 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2778 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002780
2781 InputTarget target;
2782 sp<InputWindowHandle> windowHandle =
2783 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2784 if (windowHandle != nullptr) {
2785 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2786 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2787 windowInfo->windowXScale, windowInfo->windowYScale);
2788 target.globalScaleFactor = windowInfo->globalScaleFactor;
2789 }
2790 target.inputChannel = connection->inputChannel;
2791 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2792
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002793 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2794 EventEntry* cancelationEventEntry = cancelationEvents[i];
2795 switch (cancelationEventEntry->type) {
2796 case EventEntry::Type::KEY: {
2797 logOutboundKeyDetails("cancel - ",
2798 static_cast<const KeyEntry&>(*cancelationEventEntry));
2799 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002801 case EventEntry::Type::MOTION: {
2802 logOutboundMotionDetails("cancel - ",
2803 static_cast<const MotionEntry&>(*cancelationEventEntry));
2804 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002806 case EventEntry::Type::FOCUS: {
2807 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2808 break;
2809 }
2810 case EventEntry::Type::CONFIGURATION_CHANGED:
2811 case EventEntry::Type::DEVICE_RESET: {
2812 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2813 EventEntry::typeToString(cancelationEventEntry->type));
2814 break;
2815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816 }
2817
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002818 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2819 target, InputTarget::FLAG_DISPATCH_AS_IS);
2820
2821 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002823
2824 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825}
2826
Svet Ganov5d3bc372020-01-26 23:11:07 -08002827void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2828 const sp<Connection>& connection) {
2829 if (connection->status == Connection::STATUS_BROKEN) {
2830 return;
2831 }
2832
2833 nsecs_t currentTime = now();
2834
2835 std::vector<EventEntry*> downEvents =
2836 connection->inputState.synthesizePointerDownEvents(currentTime);
2837
2838 if (downEvents.empty()) {
2839 return;
2840 }
2841
2842#if DEBUG_OUTBOUND_EVENT_DETAILS
2843 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2844 connection->getInputChannelName().c_str(), downEvents.size());
2845#endif
2846
2847 InputTarget target;
2848 sp<InputWindowHandle> windowHandle =
2849 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2850 if (windowHandle != nullptr) {
2851 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2852 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2853 windowInfo->windowXScale, windowInfo->windowYScale);
2854 target.globalScaleFactor = windowInfo->globalScaleFactor;
2855 }
2856 target.inputChannel = connection->inputChannel;
2857 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2858
2859 for (EventEntry* downEventEntry : downEvents) {
2860 switch (downEventEntry->type) {
2861 case EventEntry::Type::MOTION: {
2862 logOutboundMotionDetails("down - ",
2863 static_cast<const MotionEntry&>(*downEventEntry));
2864 break;
2865 }
2866
2867 case EventEntry::Type::KEY:
2868 case EventEntry::Type::FOCUS:
2869 case EventEntry::Type::CONFIGURATION_CHANGED:
2870 case EventEntry::Type::DEVICE_RESET: {
2871 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2872 EventEntry::typeToString(downEventEntry->type));
2873 break;
2874 }
2875 }
2876
2877 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2878 target, InputTarget::FLAG_DISPATCH_AS_IS);
2879
2880 downEventEntry->release();
2881 }
2882
2883 startDispatchCycleLocked(currentTime, connection);
2884}
2885
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002886MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002887 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888 ALOG_ASSERT(pointerIds.value != 0);
2889
2890 uint32_t splitPointerIndexMap[MAX_POINTERS];
2891 PointerProperties splitPointerProperties[MAX_POINTERS];
2892 PointerCoords splitPointerCoords[MAX_POINTERS];
2893
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002894 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895 uint32_t splitPointerCount = 0;
2896
2897 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002898 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002900 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901 uint32_t pointerId = uint32_t(pointerProperties.id);
2902 if (pointerIds.hasBit(pointerId)) {
2903 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2904 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2905 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002906 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907 splitPointerCount += 1;
2908 }
2909 }
2910
2911 if (splitPointerCount != pointerIds.count()) {
2912 // This is bad. We are missing some of the pointers that we expected to deliver.
2913 // Most likely this indicates that we received an ACTION_MOVE events that has
2914 // different pointer ids than we expected based on the previous ACTION_DOWN
2915 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2916 // in this way.
2917 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002918 "we expected there to be %d pointers. This probably means we received "
2919 "a broken sequence of pointer ids from the input device.",
2920 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002921 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922 }
2923
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002924 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002926 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2927 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2929 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002930 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 uint32_t pointerId = uint32_t(pointerProperties.id);
2932 if (pointerIds.hasBit(pointerId)) {
2933 if (pointerIds.count() == 1) {
2934 // The first/last pointer went down/up.
2935 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002936 ? AMOTION_EVENT_ACTION_DOWN
2937 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 } else {
2939 // A secondary pointer went down/up.
2940 uint32_t splitPointerIndex = 0;
2941 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2942 splitPointerIndex += 1;
2943 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002944 action = maskedAction |
2945 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946 }
2947 } else {
2948 // An unrelated pointer changed.
2949 action = AMOTION_EVENT_ACTION_MOVE;
2950 }
2951 }
2952
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002953 int32_t newId = mIdGenerator.nextId();
2954 if (ATRACE_ENABLED()) {
2955 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
2956 ") to MotionEvent(id=0x%" PRIx32 ").",
2957 originalMotionEntry.id, newId);
2958 ATRACE_NAME(message.c_str());
2959 }
Garfield Tan00f511d2019-06-12 16:55:40 -07002960 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002961 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
2962 originalMotionEntry.source, originalMotionEntry.displayId,
2963 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002964 originalMotionEntry.actionButton, originalMotionEntry.flags,
2965 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2966 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2967 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2968 originalMotionEntry.xCursorPosition,
2969 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002970 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002972 if (originalMotionEntry.injectionState) {
2973 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974 splitMotionEntry->injectionState->refCount += 1;
2975 }
2976
2977 return splitMotionEntry;
2978}
2979
2980void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2981#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002982 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002983#endif
2984
2985 bool needWake;
2986 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002987 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988
Prabir Pradhan42611e02018-11-27 14:04:02 -08002989 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002990 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002991 needWake = enqueueInboundEventLocked(newEntry);
2992 } // release lock
2993
2994 if (needWake) {
2995 mLooper->wake();
2996 }
2997}
2998
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002999/**
3000 * If one of the meta shortcuts is detected, process them here:
3001 * Meta + Backspace -> generate BACK
3002 * Meta + Enter -> generate HOME
3003 * This will potentially overwrite keyCode and metaState.
3004 */
3005void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003006 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003007 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3008 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3009 if (keyCode == AKEYCODE_DEL) {
3010 newKeyCode = AKEYCODE_BACK;
3011 } else if (keyCode == AKEYCODE_ENTER) {
3012 newKeyCode = AKEYCODE_HOME;
3013 }
3014 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003015 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003016 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003017 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003018 keyCode = newKeyCode;
3019 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3020 }
3021 } else if (action == AKEY_EVENT_ACTION_UP) {
3022 // In order to maintain a consistent stream of up and down events, check to see if the key
3023 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3024 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003025 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003026 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003027 auto replacementIt = mReplacedKeys.find(replacement);
3028 if (replacementIt != mReplacedKeys.end()) {
3029 keyCode = replacementIt->second;
3030 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003031 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3032 }
3033 }
3034}
3035
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3037#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003038 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3039 "policyFlags=0x%x, action=0x%x, "
3040 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3041 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3042 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3043 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044#endif
3045 if (!validateKeyEvent(args->action)) {
3046 return;
3047 }
3048
3049 uint32_t policyFlags = args->policyFlags;
3050 int32_t flags = args->flags;
3051 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003052 // InputDispatcher tracks and generates key repeats on behalf of
3053 // whatever notifies it, so repeatCount should always be set to 0
3054 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3056 policyFlags |= POLICY_FLAG_VIRTUAL;
3057 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059 if (policyFlags & POLICY_FLAG_FUNCTION) {
3060 metaState |= AMETA_FUNCTION_ON;
3061 }
3062
3063 policyFlags |= POLICY_FLAG_TRUSTED;
3064
Michael Wright78f24442014-08-06 15:55:28 -07003065 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003066 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003067
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003069 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003070 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3071 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003072
Michael Wright2b3c3302018-03-02 17:19:13 +00003073 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003075 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3076 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003077 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080 bool needWake;
3081 { // acquire lock
3082 mLock.lock();
3083
3084 if (shouldSendKeyToInputFilterLocked(args)) {
3085 mLock.unlock();
3086
3087 policyFlags |= POLICY_FLAG_FILTERED;
3088 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3089 return; // event was consumed by the filter
3090 }
3091
3092 mLock.lock();
3093 }
3094
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003095 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003096 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003097 args->displayId, policyFlags, args->action, flags, keyCode,
3098 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099
3100 needWake = enqueueInboundEventLocked(newEntry);
3101 mLock.unlock();
3102 } // release lock
3103
3104 if (needWake) {
3105 mLooper->wake();
3106 }
3107}
3108
3109bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3110 return mInputFilterEnabled;
3111}
3112
3113void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3114#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003115 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3116 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003117 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3118 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003119 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003120 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3121 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3122 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3123 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124 for (uint32_t i = 0; i < args->pointerCount; i++) {
3125 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 "x=%f, y=%f, pressure=%f, size=%f, "
3127 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3128 "orientation=%f",
3129 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3130 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3131 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3132 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3133 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3134 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3135 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3136 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3137 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3138 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139 }
3140#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003141 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3142 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143 return;
3144 }
3145
3146 uint32_t policyFlags = args->policyFlags;
3147 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003148
3149 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003150 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003151 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3152 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003153 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155
3156 bool needWake;
3157 { // acquire lock
3158 mLock.lock();
3159
3160 if (shouldSendMotionToInputFilterLocked(args)) {
3161 mLock.unlock();
3162
3163 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003164 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3165 args->action, args->actionButton, args->flags, args->edgeFlags,
3166 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3167 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3168 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3169 args->downTime, args->eventTime, args->pointerCount,
3170 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171
3172 policyFlags |= POLICY_FLAG_FILTERED;
3173 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3174 return; // event was consumed by the filter
3175 }
3176
3177 mLock.lock();
3178 }
3179
3180 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003181 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003182 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003183 args->displayId, policyFlags, args->action, args->actionButton,
3184 args->flags, args->metaState, args->buttonState,
3185 args->classification, args->edgeFlags, args->xPrecision,
3186 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3187 args->downTime, args->pointerCount, args->pointerProperties,
3188 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189
3190 needWake = enqueueInboundEventLocked(newEntry);
3191 mLock.unlock();
3192 } // release lock
3193
3194 if (needWake) {
3195 mLooper->wake();
3196 }
3197}
3198
3199bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003200 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201}
3202
3203void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3204#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003205 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003206 "switchMask=0x%08x",
3207 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003208#endif
3209
3210 uint32_t policyFlags = args->policyFlags;
3211 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213}
3214
3215void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3216#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003217 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3218 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219#endif
3220
3221 bool needWake;
3222 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003223 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224
Prabir Pradhan42611e02018-11-27 14:04:02 -08003225 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003226 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 needWake = enqueueInboundEventLocked(newEntry);
3228 } // release lock
3229
3230 if (needWake) {
3231 mLooper->wake();
3232 }
3233}
3234
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003235int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3236 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003237 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238#if DEBUG_INBOUND_EVENT_DETAILS
3239 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003240 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3241 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242#endif
3243
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003244 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245
3246 policyFlags |= POLICY_FLAG_INJECTED;
3247 if (hasInjectionPermission(injectorPid, injectorUid)) {
3248 policyFlags |= POLICY_FLAG_TRUSTED;
3249 }
3250
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003251 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003253 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003254 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3255 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003256 if (!validateKeyEvent(action)) {
3257 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003260 int32_t flags = incomingKey.getFlags();
3261 int32_t keyCode = incomingKey.getKeyCode();
3262 int32_t metaState = incomingKey.getMetaState();
3263 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003264 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003265 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003266 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003267 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3268 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3269 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003271 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3272 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003273 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003274
3275 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3276 android::base::Timer t;
3277 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3278 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3279 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3280 std::to_string(t.duration().count()).c_str());
3281 }
3282 }
3283
3284 mLock.lock();
3285 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003286 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3287 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003288 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3289 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003290 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003291 injectedEntries.push(injectedEntry);
3292 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293 }
3294
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003295 case AINPUT_EVENT_TYPE_MOTION: {
3296 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3297 int32_t action = motionEvent->getAction();
3298 size_t pointerCount = motionEvent->getPointerCount();
3299 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3300 int32_t actionButton = motionEvent->getActionButton();
3301 int32_t displayId = motionEvent->getDisplayId();
3302 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3303 return INPUT_EVENT_INJECTION_FAILED;
3304 }
3305
3306 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3307 nsecs_t eventTime = motionEvent->getEventTime();
3308 android::base::Timer t;
3309 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3310 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3311 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3312 std::to_string(t.duration().count()).c_str());
3313 }
3314 }
3315
3316 mLock.lock();
3317 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3318 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3319 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003320 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3321 motionEvent->getSource(), motionEvent->getDisplayId(),
3322 policyFlags, action, actionButton, motionEvent->getFlags(),
3323 motionEvent->getMetaState(), motionEvent->getButtonState(),
3324 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3325 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003326 motionEvent->getRawXCursorPosition(),
3327 motionEvent->getRawYCursorPosition(),
3328 motionEvent->getDownTime(), uint32_t(pointerCount),
3329 pointerProperties, samplePointerCoords,
3330 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331 injectedEntries.push(injectedEntry);
3332 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3333 sampleEventTimes += 1;
3334 samplePointerCoords += pointerCount;
3335 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003336 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003337 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338 motionEvent->getDisplayId(), policyFlags, action,
3339 actionButton, motionEvent->getFlags(),
3340 motionEvent->getMetaState(), motionEvent->getButtonState(),
3341 motionEvent->getClassification(),
3342 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3343 motionEvent->getYPrecision(),
3344 motionEvent->getRawXCursorPosition(),
3345 motionEvent->getRawYCursorPosition(),
3346 motionEvent->getDownTime(), uint32_t(pointerCount),
3347 pointerProperties, samplePointerCoords,
3348 motionEvent->getXOffset(), motionEvent->getYOffset());
3349 injectedEntries.push(nextInjectedEntry);
3350 }
3351 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003354 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003355 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003356 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 }
3358
3359 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3360 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3361 injectionState->injectionIsAsync = true;
3362 }
3363
3364 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003365 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366
3367 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003368 while (!injectedEntries.empty()) {
3369 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3370 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 }
3372
3373 mLock.unlock();
3374
3375 if (needWake) {
3376 mLooper->wake();
3377 }
3378
3379 int32_t injectionResult;
3380 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003381 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382
3383 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3384 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3385 } else {
3386 for (;;) {
3387 injectionResult = injectionState->injectionResult;
3388 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3389 break;
3390 }
3391
3392 nsecs_t remainingTimeout = endTime - now();
3393 if (remainingTimeout <= 0) {
3394#if DEBUG_INJECTION
3395 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003396 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397#endif
3398 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3399 break;
3400 }
3401
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003402 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403 }
3404
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003405 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3406 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 while (injectionState->pendingForegroundDispatches != 0) {
3408#if DEBUG_INJECTION
3409 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003410 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411#endif
3412 nsecs_t remainingTimeout = endTime - now();
3413 if (remainingTimeout <= 0) {
3414#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003415 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3416 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417#endif
3418 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3419 break;
3420 }
3421
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003422 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 }
3424 }
3425 }
3426
3427 injectionState->release();
3428 } // release lock
3429
3430#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003431 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003432 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433#endif
3434
3435 return injectionResult;
3436}
3437
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003438std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003439 std::array<uint8_t, 32> calculatedHmac;
3440 std::unique_ptr<VerifiedInputEvent> result;
3441 switch (event.getType()) {
3442 case AINPUT_EVENT_TYPE_KEY: {
3443 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3444 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3445 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3446 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3447 break;
3448 }
3449 case AINPUT_EVENT_TYPE_MOTION: {
3450 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3451 VerifiedMotionEvent verifiedMotionEvent =
3452 verifiedMotionEventFromMotionEvent(motionEvent);
3453 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3454 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3455 break;
3456 }
3457 default: {
3458 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3459 return nullptr;
3460 }
3461 }
3462 if (calculatedHmac == INVALID_HMAC) {
3463 return nullptr;
3464 }
3465 if (calculatedHmac != event.getHmac()) {
3466 return nullptr;
3467 }
3468 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003469}
3470
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003472 return injectorUid == 0 ||
3473 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474}
3475
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003476void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477 InjectionState* injectionState = entry->injectionState;
3478 if (injectionState) {
3479#if DEBUG_INJECTION
3480 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003481 "injectorPid=%d, injectorUid=%d",
3482 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483#endif
3484
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003485 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 // Log the outcome since the injector did not wait for the injection result.
3487 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003488 case INPUT_EVENT_INJECTION_SUCCEEDED:
3489 ALOGV("Asynchronous input event injection succeeded.");
3490 break;
3491 case INPUT_EVENT_INJECTION_FAILED:
3492 ALOGW("Asynchronous input event injection failed.");
3493 break;
3494 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3495 ALOGW("Asynchronous input event injection permission denied.");
3496 break;
3497 case INPUT_EVENT_INJECTION_TIMED_OUT:
3498 ALOGW("Asynchronous input event injection timed out.");
3499 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500 }
3501 }
3502
3503 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003504 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 }
3506}
3507
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003508void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 InjectionState* injectionState = entry->injectionState;
3510 if (injectionState) {
3511 injectionState->pendingForegroundDispatches += 1;
3512 }
3513}
3514
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003515void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516 InjectionState* injectionState = entry->injectionState;
3517 if (injectionState) {
3518 injectionState->pendingForegroundDispatches -= 1;
3519
3520 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003521 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522 }
3523 }
3524}
3525
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003526std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3527 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003528 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003529}
3530
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003532 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003533 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003534 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3535 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003536 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003537 return windowHandle;
3538 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539 }
3540 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003541 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542}
3543
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003544bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003545 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003546 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3547 for (const sp<InputWindowHandle>& handle : windowHandles) {
3548 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003549 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003550 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003551 ", but it should belong to display %" PRId32,
3552 windowHandle->getName().c_str(), it.first,
3553 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003554 }
3555 return true;
3556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 }
3558 }
3559 return false;
3560}
3561
Robert Carr5c8a0262018-10-03 16:30:44 -07003562sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3563 size_t count = mInputChannelsByToken.count(token);
3564 if (count == 0) {
3565 return nullptr;
3566 }
3567 return mInputChannelsByToken.at(token);
3568}
3569
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003570void InputDispatcher::updateWindowHandlesForDisplayLocked(
3571 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3572 if (inputWindowHandles.empty()) {
3573 // Remove all handles on a display if there are no windows left.
3574 mWindowHandlesByDisplay.erase(displayId);
3575 return;
3576 }
3577
3578 // Since we compare the pointer of input window handles across window updates, we need
3579 // to make sure the handle object for the same window stays unchanged across updates.
3580 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003581 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003582 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003583 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003584 }
3585
3586 std::vector<sp<InputWindowHandle>> newHandles;
3587 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3588 if (!handle->updateInfo()) {
3589 // handle no longer valid
3590 continue;
3591 }
3592
3593 const InputWindowInfo* info = handle->getInfo();
3594 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3595 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3596 const bool noInputChannel =
3597 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3598 const bool canReceiveInput =
3599 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3600 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3601 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003602 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003603 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003604 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003605 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003606 }
3607
3608 if (info->displayId != displayId) {
3609 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3610 handle->getName().c_str(), displayId, info->displayId);
3611 continue;
3612 }
3613
chaviwaf87b3e2019-10-01 16:59:28 -07003614 if (oldHandlesById.find(handle->getId()) != oldHandlesById.end()) {
3615 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003616 oldHandle->updateFrom(handle);
3617 newHandles.push_back(oldHandle);
3618 } else {
3619 newHandles.push_back(handle);
3620 }
3621 }
3622
3623 // Insert or replace
3624 mWindowHandlesByDisplay[displayId] = newHandles;
3625}
3626
Arthur Hung72d8dc32020-03-28 00:48:39 +00003627void InputDispatcher::setInputWindows(
3628 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3629 { // acquire lock
3630 std::scoped_lock _l(mLock);
3631 for (auto const& i : handlesPerDisplay) {
3632 setInputWindowsLocked(i.second, i.first);
3633 }
3634 }
3635 // Wake up poll loop since it may need to make new input dispatching choices.
3636 mLooper->wake();
3637}
3638
Arthur Hungb92218b2018-08-14 12:00:21 +08003639/**
3640 * Called from InputManagerService, update window handle list by displayId that can receive input.
3641 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3642 * If set an empty list, remove all handles from the specific display.
3643 * For focused handle, check if need to change and send a cancel event to previous one.
3644 * For removed handle, check if need to send a cancel event if already in touch.
3645 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003646void InputDispatcher::setInputWindowsLocked(
3647 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003648 if (DEBUG_FOCUS) {
3649 std::string windowList;
3650 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3651 windowList += iwh->getName() + " ";
3652 }
3653 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655
Arthur Hung72d8dc32020-03-28 00:48:39 +00003656 // Copy old handles for release if they are no longer present.
3657 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658
Arthur Hung72d8dc32020-03-28 00:48:39 +00003659 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003660
Arthur Hung72d8dc32020-03-28 00:48:39 +00003661 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3662 bool foundHoveredWindow = false;
3663 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3664 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3665 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3666 windowHandle->getInfo()->visible) {
3667 newFocusedWindowHandle = windowHandle;
3668 }
3669 if (windowHandle == mLastHoverWindowHandle) {
3670 foundHoveredWindow = true;
3671 }
3672 }
3673
3674 if (!foundHoveredWindow) {
3675 mLastHoverWindowHandle = nullptr;
3676 }
3677
3678 sp<InputWindowHandle> oldFocusedWindowHandle =
3679 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3680
3681 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3682 if (oldFocusedWindowHandle != nullptr) {
3683 if (DEBUG_FOCUS) {
3684 ALOGD("Focus left window: %s in display %" PRId32,
3685 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003686 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003687 sp<InputChannel> focusedInputChannel =
3688 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3689 if (focusedInputChannel != nullptr) {
3690 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3691 "focus left window");
3692 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3693 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003694 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003695 mFocusedWindowHandlesByDisplay.erase(displayId);
3696 }
3697 if (newFocusedWindowHandle != nullptr) {
3698 if (DEBUG_FOCUS) {
3699 ALOGD("Focus entered window: %s in display %" PRId32,
3700 newFocusedWindowHandle->getName().c_str(), displayId);
3701 }
3702 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3703 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 }
3705
Arthur Hung72d8dc32020-03-28 00:48:39 +00003706 if (mFocusedDisplayId == displayId) {
3707 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003711 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3712 mTouchStatesByDisplay.find(displayId);
3713 if (stateIt != mTouchStatesByDisplay.end()) {
3714 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003715 for (size_t i = 0; i < state.windows.size();) {
3716 TouchedWindow& touchedWindow = state.windows[i];
3717 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003718 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003719 ALOGD("Touched window was removed: %s in display %" PRId32,
3720 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003721 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003722 sp<InputChannel> touchedInputChannel =
3723 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3724 if (touchedInputChannel != nullptr) {
3725 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3726 "touched window was removed");
3727 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003729 state.windows.erase(state.windows.begin() + i);
3730 } else {
3731 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 }
3733 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003734 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003735
Arthur Hung72d8dc32020-03-28 00:48:39 +00003736 // Release information for windows that are no longer present.
3737 // This ensures that unused input channels are released promptly.
3738 // Otherwise, they might stick around until the window handle is destroyed
3739 // which might not happen until the next GC.
3740 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3741 if (!hasWindowHandleLocked(oldWindowHandle)) {
3742 if (DEBUG_FOCUS) {
3743 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003744 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003745 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003746 }
chaviw291d88a2019-02-14 10:33:58 -08003747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748}
3749
3750void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003751 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003752 if (DEBUG_FOCUS) {
3753 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3754 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003757 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758
Tiger Huang721e26f2018-07-24 22:26:19 +08003759 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3760 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003761 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003762 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3763 if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003764 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003766 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003768 } else if (oldFocusedApplicationHandle != nullptr) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003769 resetAnrTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003770 oldFocusedApplicationHandle.clear();
3771 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 } // release lock
3774
3775 // Wake up poll loop since it may need to make new input dispatching choices.
3776 mLooper->wake();
3777}
3778
Tiger Huang721e26f2018-07-24 22:26:19 +08003779/**
3780 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3781 * the display not specified.
3782 *
3783 * We track any unreleased events for each window. If a window loses the ability to receive the
3784 * released event, we will send a cancel event to it. So when the focused display is changed, we
3785 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3786 * display. The display-specified events won't be affected.
3787 */
3788void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003789 if (DEBUG_FOCUS) {
3790 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3791 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003792 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003793 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003794
3795 if (mFocusedDisplayId != displayId) {
3796 sp<InputWindowHandle> oldFocusedWindowHandle =
3797 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3798 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003799 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003800 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003801 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003802 CancelationOptions
3803 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3804 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003805 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003806 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3807 }
3808 }
3809 mFocusedDisplayId = displayId;
3810
3811 // Sanity check
3812 sp<InputWindowHandle> newFocusedWindowHandle =
3813 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003814 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003815
Tiger Huang721e26f2018-07-24 22:26:19 +08003816 if (newFocusedWindowHandle == nullptr) {
3817 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3818 if (!mFocusedWindowHandlesByDisplay.empty()) {
3819 ALOGE("But another display has a focused window:");
3820 for (auto& it : mFocusedWindowHandlesByDisplay) {
3821 const int32_t displayId = it.first;
3822 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003823 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3824 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003825 }
3826 }
3827 }
3828 }
3829
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003830 if (DEBUG_FOCUS) {
3831 logDispatchStateLocked();
3832 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003833 } // release lock
3834
3835 // Wake up poll loop since it may need to make new input dispatching choices.
3836 mLooper->wake();
3837}
3838
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003840 if (DEBUG_FOCUS) {
3841 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843
3844 bool changed;
3845 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003846 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847
3848 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3849 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003850 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851 }
3852
3853 if (mDispatchEnabled && !enabled) {
3854 resetAndDropEverythingLocked("dispatcher is being disabled");
3855 }
3856
3857 mDispatchEnabled = enabled;
3858 mDispatchFrozen = frozen;
3859 changed = true;
3860 } else {
3861 changed = false;
3862 }
3863
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003864 if (DEBUG_FOCUS) {
3865 logDispatchStateLocked();
3866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 } // release lock
3868
3869 if (changed) {
3870 // Wake up poll loop since it may need to make new input dispatching choices.
3871 mLooper->wake();
3872 }
3873}
3874
3875void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003876 if (DEBUG_FOCUS) {
3877 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3878 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879
3880 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003881 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882
3883 if (mInputFilterEnabled == enabled) {
3884 return;
3885 }
3886
3887 mInputFilterEnabled = enabled;
3888 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3889 } // release lock
3890
3891 // Wake up poll loop since there might be work to do to drop everything.
3892 mLooper->wake();
3893}
3894
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003895void InputDispatcher::setInTouchMode(bool inTouchMode) {
3896 std::scoped_lock lock(mLock);
3897 mInTouchMode = inTouchMode;
3898}
3899
chaviwfbe5d9c2018-12-26 12:23:37 -08003900bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3901 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003902 if (DEBUG_FOCUS) {
3903 ALOGD("Trivial transfer to same window.");
3904 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003905 return true;
3906 }
3907
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003909 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910
chaviwfbe5d9c2018-12-26 12:23:37 -08003911 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3912 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003913 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003914 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 return false;
3916 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003917 if (DEBUG_FOCUS) {
3918 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3919 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003922 if (DEBUG_FOCUS) {
3923 ALOGD("Cannot transfer focus because windows are on different displays.");
3924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 return false;
3926 }
3927
3928 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003929 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
3930 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003931 for (size_t i = 0; i < state.windows.size(); i++) {
3932 const TouchedWindow& touchedWindow = state.windows[i];
3933 if (touchedWindow.windowHandle == fromWindowHandle) {
3934 int32_t oldTargetFlags = touchedWindow.targetFlags;
3935 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003937 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003939 int32_t newTargetFlags = oldTargetFlags &
3940 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3941 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003942 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943
Jeff Brownf086ddb2014-02-11 14:28:48 -08003944 found = true;
3945 goto Found;
3946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 }
3948 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003949 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003951 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003952 if (DEBUG_FOCUS) {
3953 ALOGD("Focus transfer failed because from window did not have focus.");
3954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955 return false;
3956 }
3957
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003958 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3959 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003960 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003961 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962 CancelationOptions
3963 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3964 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003966 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 }
3968
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003969 if (DEBUG_FOCUS) {
3970 logDispatchStateLocked();
3971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 } // release lock
3973
3974 // Wake up poll loop since it may need to make new input dispatching choices.
3975 mLooper->wake();
3976 return true;
3977}
3978
3979void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003980 if (DEBUG_FOCUS) {
3981 ALOGD("Resetting and dropping all events (%s).", reason);
3982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983
3984 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3985 synthesizeCancelationEventsForAllConnectionsLocked(options);
3986
3987 resetKeyRepeatLocked();
3988 releasePendingEventLocked();
3989 drainInboundQueueLocked();
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07003990 resetAnrTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991
Jeff Brownf086ddb2014-02-11 14:28:48 -08003992 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003994 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995}
3996
3997void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003998 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999 dumpDispatchStateLocked(dump);
4000
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004001 std::istringstream stream(dump);
4002 std::string line;
4003
4004 while (std::getline(stream, line, '\n')) {
4005 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006 }
4007}
4008
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004009void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004010 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4011 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4012 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004013 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014
Tiger Huang721e26f2018-07-24 22:26:19 +08004015 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4016 dump += StringPrintf(INDENT "FocusedApplications:\n");
4017 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4018 const int32_t displayId = it.first;
4019 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004020 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4021 ", name='%s', dispatchingTimeout=%0.3fms\n",
4022 displayId, applicationHandle->getName().c_str(),
4023 applicationHandle->getDispatchingTimeout(
4024 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
4025 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08004026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004028 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004030
4031 if (!mFocusedWindowHandlesByDisplay.empty()) {
4032 dump += StringPrintf(INDENT "FocusedWindows:\n");
4033 for (auto& it : mFocusedWindowHandlesByDisplay) {
4034 const int32_t displayId = it.first;
4035 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004036 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4037 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004038 }
4039 } else {
4040 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004043 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004044 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004045 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4046 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004047 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004048 state.displayId, toString(state.down), toString(state.split),
4049 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004050 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004051 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004052 for (size_t i = 0; i < state.windows.size(); i++) {
4053 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004054 dump += StringPrintf(INDENT4
4055 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4056 i, touchedWindow.windowHandle->getName().c_str(),
4057 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004058 }
4059 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004060 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004061 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004062 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004063 dump += INDENT3 "Portal windows:\n";
4064 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004065 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004066 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4067 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004068 }
4069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 }
4071 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004072 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073 }
4074
Arthur Hungb92218b2018-08-14 12:00:21 +08004075 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004076 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004077 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004078 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004079 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004080 dump += INDENT2 "Windows:\n";
4081 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004082 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004083 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084
Arthur Hungb92218b2018-08-14 12:00:21 +08004085 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004086 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004087 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4088 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004089 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004090 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004091 i, windowInfo->name.c_str(), windowInfo->displayId,
4092 windowInfo->portalToDisplayId,
4093 toString(windowInfo->paused),
4094 toString(windowInfo->hasFocus),
4095 toString(windowInfo->hasWallpaper),
4096 toString(windowInfo->visible),
4097 toString(windowInfo->canReceiveKeys),
4098 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004099 windowInfo->layoutParamsType, windowInfo->frameLeft,
4100 windowInfo->frameTop, windowInfo->frameRight,
4101 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4102 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004103 dumpRegion(dump, windowInfo->touchableRegion);
4104 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
4105 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004106 windowInfo->ownerPid, windowInfo->ownerUid,
4107 windowInfo->dispatchingTimeout / 1000000.0);
Siarhei Vishniakou67d44502020-04-09 11:09:29 -07004108 dump += StringPrintf(INDENT4 " flags: %s\n",
4109 inputWindowFlagsToString(windowInfo->layoutParamsFlags)
4110 .c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004111 }
4112 } else {
4113 dump += INDENT2 "Windows: <none>\n";
4114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115 }
4116 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004117 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 }
4119
Michael Wright3dd60e22019-03-27 22:06:44 +00004120 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004121 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004122 const std::vector<Monitor>& monitors = it.second;
4123 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4124 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004125 }
4126 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004127 const std::vector<Monitor>& monitors = it.second;
4128 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4129 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004130 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004132 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 }
4134
4135 nsecs_t currentTime = now();
4136
4137 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004138 if (!mRecentQueue.empty()) {
4139 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4140 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004141 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004143 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 }
4145 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004146 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 }
4148
4149 // Dump event currently being dispatched.
4150 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004151 dump += INDENT "PendingEvent:\n";
4152 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004154 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004155 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004157 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 }
4159
4160 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004161 if (!mInboundQueue.empty()) {
4162 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4163 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004164 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004166 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167 }
4168 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004169 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 }
4171
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004172 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004173 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004174 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4175 const KeyReplacement& replacement = pair.first;
4176 int32_t newKeyCode = pair.second;
4177 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004178 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004179 }
4180 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004181 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004182 }
4183
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004184 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004185 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004186 for (const auto& pair : mConnectionsByFd) {
4187 const sp<Connection>& connection = pair.second;
4188 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
4189 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
4190 pair.first, connection->getInputChannelName().c_str(),
4191 connection->getWindowName().c_str(), connection->getStatusLabel(),
4192 toString(connection->monitor),
4193 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004195 if (!connection->outboundQueue.empty()) {
4196 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4197 connection->outboundQueue.size());
4198 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 dump.append(INDENT4);
4200 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004201 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 entry->targetFlags, entry->resolvedAction,
4203 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 }
4205 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004206 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 }
4208
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004209 if (!connection->waitQueue.empty()) {
4210 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4211 connection->waitQueue.size());
4212 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004213 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004215 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004216 "age=%0.1fms, wait=%0.1fms\n",
4217 entry->targetFlags, entry->resolvedAction,
4218 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
4219 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 }
4221 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004222 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 }
4224 }
4225 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004226 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 }
4228
4229 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004230 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004231 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004233 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 }
4235
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004236 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004237 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004238 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004239 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240}
4241
Michael Wright3dd60e22019-03-27 22:06:44 +00004242void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4243 const size_t numMonitors = monitors.size();
4244 for (size_t i = 0; i < numMonitors; i++) {
4245 const Monitor& monitor = monitors[i];
4246 const sp<InputChannel>& channel = monitor.inputChannel;
4247 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4248 dump += "\n";
4249 }
4250}
4251
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004252status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004254 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255#endif
4256
4257 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004258 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004259 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004260 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004262 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 return BAD_VALUE;
4264 }
4265
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004266 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267
4268 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004269 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004270 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4273 } // release lock
4274
4275 // Wake the looper because some connections have changed.
4276 mLooper->wake();
4277 return OK;
4278}
4279
Michael Wright3dd60e22019-03-27 22:06:44 +00004280status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004281 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004282 { // acquire lock
4283 std::scoped_lock _l(mLock);
4284
4285 if (displayId < 0) {
4286 ALOGW("Attempted to register input monitor without a specified display.");
4287 return BAD_VALUE;
4288 }
4289
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004290 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004291 ALOGW("Attempted to register input monitor without an identifying token.");
4292 return BAD_VALUE;
4293 }
4294
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004295 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004296
4297 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004298 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004299 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004300
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004301 auto& monitorsByDisplay =
4302 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004303 monitorsByDisplay[displayId].emplace_back(inputChannel);
4304
4305 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004306 }
4307 // Wake the looper because some connections have changed.
4308 mLooper->wake();
4309 return OK;
4310}
4311
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4313#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004314 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315#endif
4316
4317 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004318 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319
4320 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4321 if (status) {
4322 return status;
4323 }
4324 } // release lock
4325
4326 // Wake the poll loop because removing the connection may have changed the current
4327 // synchronization state.
4328 mLooper->wake();
4329 return OK;
4330}
4331
4332status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004333 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004334 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004335 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004337 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 return BAD_VALUE;
4339 }
4340
John Recke0710582019-09-26 13:46:12 -07004341 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004342 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004343 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004344
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 if (connection->monitor) {
4346 removeMonitorChannelLocked(inputChannel);
4347 }
4348
4349 mLooper->removeFd(inputChannel->getFd());
4350
4351 nsecs_t currentTime = now();
4352 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4353
4354 connection->status = Connection::STATUS_ZOMBIE;
4355 return OK;
4356}
4357
4358void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004359 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4360 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4361}
4362
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004363void InputDispatcher::removeMonitorChannelLocked(
4364 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004365 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004366 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004367 std::vector<Monitor>& monitors = it->second;
4368 const size_t numMonitors = monitors.size();
4369 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004370 if (monitors[i].inputChannel == inputChannel) {
4371 monitors.erase(monitors.begin() + i);
4372 break;
4373 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004374 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004375 if (monitors.empty()) {
4376 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004377 } else {
4378 ++it;
4379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 }
4381}
4382
Michael Wright3dd60e22019-03-27 22:06:44 +00004383status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4384 { // acquire lock
4385 std::scoped_lock _l(mLock);
4386 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4387
4388 if (!foundDisplayId) {
4389 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4390 return BAD_VALUE;
4391 }
4392 int32_t displayId = foundDisplayId.value();
4393
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004394 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4395 mTouchStatesByDisplay.find(displayId);
4396 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004397 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4398 return BAD_VALUE;
4399 }
4400
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004401 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004402 std::optional<int32_t> foundDeviceId;
4403 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004404 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004405 foundDeviceId = state.deviceId;
4406 }
4407 }
4408 if (!foundDeviceId || !state.down) {
4409 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004410 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004411 return BAD_VALUE;
4412 }
4413 int32_t deviceId = foundDeviceId.value();
4414
4415 // Send cancel events to all the input channels we're stealing from.
4416 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004417 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004418 options.deviceId = deviceId;
4419 options.displayId = displayId;
4420 for (const TouchedWindow& window : state.windows) {
4421 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004422 if (channel != nullptr) {
4423 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4424 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004425 }
4426 // Then clear the current touch state so we stop dispatching to them as well.
4427 state.filterNonMonitors();
4428 }
4429 return OK;
4430}
4431
Michael Wright3dd60e22019-03-27 22:06:44 +00004432std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4433 const sp<IBinder>& token) {
4434 for (const auto& it : mGestureMonitorsByDisplay) {
4435 const std::vector<Monitor>& monitors = it.second;
4436 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004437 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004438 return it.first;
4439 }
4440 }
4441 }
4442 return std::nullopt;
4443}
4444
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004445sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4446 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004447 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004448 }
4449
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004450 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004451 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004452 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004453 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 }
4455 }
Robert Carr4e670e52018-08-15 13:26:12 -07004456
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004457 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458}
4459
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004460void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4461 const sp<Connection>& connection, uint32_t seq,
4462 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004463 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4464 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004465 commandEntry->connection = connection;
4466 commandEntry->eventTime = currentTime;
4467 commandEntry->seq = seq;
4468 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004469 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470}
4471
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004472void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4473 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004475 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004477 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4478 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004480 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481}
4482
chaviw0c06c6e2019-01-09 13:27:07 -08004483void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004484 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004485 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4486 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004487 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4488 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004489 commandEntry->oldToken = oldToken;
4490 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004491 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004492}
4493
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004494void InputDispatcher::onAnrLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004495 const sp<InputApplicationHandle>& applicationHandle,
4496 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4497 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4499 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4500 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004501 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4502 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4503 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504
4505 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004506 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507 struct tm tm;
4508 localtime_r(&t, &tm);
4509 char timestr[64];
4510 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004511 mLastAnrState.clear();
4512 mLastAnrState += INDENT "ANR:\n";
4513 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
4514 mLastAnrState +=
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004515 StringPrintf(INDENT2 "Window: %s\n",
4516 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004517 mLastAnrState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4518 mLastAnrState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4519 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason);
4520 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004522 std::unique_ptr<CommandEntry> commandEntry =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004523 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004525 commandEntry->inputChannel =
4526 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004528 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529}
4530
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004531void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532 mLock.unlock();
4533
4534 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4535
4536 mLock.lock();
4537}
4538
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004539void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540 sp<Connection> connection = commandEntry->connection;
4541
4542 if (connection->status != Connection::STATUS_ZOMBIE) {
4543 mLock.unlock();
4544
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004545 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546
4547 mLock.lock();
4548 }
4549}
4550
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004551void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004552 sp<IBinder> oldToken = commandEntry->oldToken;
4553 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004554 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004555 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004556 mLock.lock();
4557}
4558
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004559void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004560 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004561 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562 mLock.unlock();
4563
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004564 nsecs_t newTimeout =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004565 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566
4567 mLock.lock();
4568
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004569 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570}
4571
4572void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4573 CommandEntry* commandEntry) {
4574 KeyEntry* entry = commandEntry->keyEntry;
4575
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004576 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577
4578 mLock.unlock();
4579
Michael Wright2b3c3302018-03-02 17:19:13 +00004580 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004581 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004582 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004583 : nullptr;
4584 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004585 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4586 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004587 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589
4590 mLock.lock();
4591
4592 if (delay < 0) {
4593 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4594 } else if (!delay) {
4595 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4596 } else {
4597 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4598 entry->interceptKeyWakeupTime = now() + delay;
4599 }
4600 entry->release();
4601}
4602
chaviwfd6d3512019-03-25 13:23:49 -07004603void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4604 mLock.unlock();
4605 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4606 mLock.lock();
4607}
4608
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004609void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004611 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004613 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614
4615 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004616 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004617 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004618 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004620 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004621
4622 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4623 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4624 std::string msg =
4625 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4626 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4627 dispatchEntry->eventEntry->appendDescription(msg);
4628 ALOGI("%s", msg.c_str());
4629 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004630 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004631
4632 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004633 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004634 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4635 restartEvent =
4636 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004637 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004638 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4639 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4640 handled);
4641 } else {
4642 restartEvent = false;
4643 }
4644
4645 // Dequeue the event and start the next cycle.
4646 // Note that because the lock might have been released, it is possible that the
4647 // contents of the wait queue to have been drained, so we need to double-check
4648 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004649 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4650 if (dispatchEntryIt != connection->waitQueue.end()) {
4651 dispatchEntry = *dispatchEntryIt;
4652 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004653 traceWaitQueueLength(connection);
4654 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004655 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004656 traceOutboundQueueLength(connection);
4657 } else {
4658 releaseDispatchEntry(dispatchEntry);
4659 }
4660 }
4661
4662 // Start the next dispatch cycle for this connection.
4663 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004664}
4665
4666bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004667 DispatchEntry* dispatchEntry,
4668 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004669 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004670 if (!handled) {
4671 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004672 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004673 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004674 return false;
4675 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004676
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004677 // Get the fallback key state.
4678 // Clear it out after dispatching the UP.
4679 int32_t originalKeyCode = keyEntry->keyCode;
4680 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4681 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4682 connection->inputState.removeFallbackKey(originalKeyCode);
4683 }
4684
4685 if (handled || !dispatchEntry->hasForegroundTarget()) {
4686 // If the application handles the original key for which we previously
4687 // generated a fallback or if the window is not a foreground window,
4688 // then cancel the associated fallback key, if any.
4689 if (fallbackKeyCode != -1) {
4690 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004692 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004693 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4694 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4695 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004697 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004698 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699
4700 mLock.unlock();
4701
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004702 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004703 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704
4705 mLock.lock();
4706
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004707 // Cancel the fallback key.
4708 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004710 "application handled the original non-fallback key "
4711 "or is no longer a foreground target, "
4712 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 options.keyCode = fallbackKeyCode;
4714 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004716 connection->inputState.removeFallbackKey(originalKeyCode);
4717 }
4718 } else {
4719 // If the application did not handle a non-fallback key, first check
4720 // that we are in a good state to perform unhandled key event processing
4721 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004722 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004723 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004725 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004726 "since this is not an initial down. "
4727 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4728 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004730 return false;
4731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004733 // Dispatch the unhandled key to the policy.
4734#if DEBUG_OUTBOUND_EVENT_DETAILS
4735 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004736 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4737 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004738#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004739 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004740
4741 mLock.unlock();
4742
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004743 bool fallback =
4744 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4745 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004746
4747 mLock.lock();
4748
4749 if (connection->status != Connection::STATUS_NORMAL) {
4750 connection->inputState.removeFallbackKey(originalKeyCode);
4751 return false;
4752 }
4753
4754 // Latch the fallback keycode for this key on an initial down.
4755 // The fallback keycode cannot change at any other point in the lifecycle.
4756 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004758 fallbackKeyCode = event.getKeyCode();
4759 } else {
4760 fallbackKeyCode = AKEYCODE_UNKNOWN;
4761 }
4762 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4763 }
4764
4765 ALOG_ASSERT(fallbackKeyCode != -1);
4766
4767 // Cancel the fallback key if the policy decides not to send it anymore.
4768 // We will continue to dispatch the key to the policy but we will no
4769 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004770 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4771 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004772#if DEBUG_OUTBOUND_EVENT_DETAILS
4773 if (fallback) {
4774 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004775 "as a fallback for %d, but on the DOWN it had requested "
4776 "to send %d instead. Fallback canceled.",
4777 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004778 } else {
4779 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004780 "but on the DOWN it had requested to send %d. "
4781 "Fallback canceled.",
4782 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004783 }
4784#endif
4785
4786 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4787 "canceling fallback, policy no longer desires it");
4788 options.keyCode = fallbackKeyCode;
4789 synthesizeCancelationEventsForConnectionLocked(connection, options);
4790
4791 fallback = false;
4792 fallbackKeyCode = AKEYCODE_UNKNOWN;
4793 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004794 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004795 }
4796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797
4798#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004799 {
4800 std::string msg;
4801 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4802 connection->inputState.getFallbackKeys();
4803 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004804 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004806 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004807 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004808 }
4809#endif
4810
4811 if (fallback) {
4812 // Restart the dispatch cycle using the fallback key.
4813 keyEntry->eventTime = event.getEventTime();
4814 keyEntry->deviceId = event.getDeviceId();
4815 keyEntry->source = event.getSource();
4816 keyEntry->displayId = event.getDisplayId();
4817 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4818 keyEntry->keyCode = fallbackKeyCode;
4819 keyEntry->scanCode = event.getScanCode();
4820 keyEntry->metaState = event.getMetaState();
4821 keyEntry->repeatCount = event.getRepeatCount();
4822 keyEntry->downTime = event.getDownTime();
4823 keyEntry->syntheticRepeat = false;
4824
4825#if DEBUG_OUTBOUND_EVENT_DETAILS
4826 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004827 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4828 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004829#endif
4830 return true; // restart the event
4831 } else {
4832#if DEBUG_OUTBOUND_EVENT_DETAILS
4833 ALOGD("Unhandled key event: No fallback key.");
4834#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004835
4836 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004837 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838 }
4839 }
4840 return false;
4841}
4842
4843bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004844 DispatchEntry* dispatchEntry,
4845 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846 return false;
4847}
4848
4849void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4850 mLock.unlock();
4851
4852 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4853
4854 mLock.lock();
4855}
4856
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004857KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4858 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004859 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004860 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
4861 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004862 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863}
4864
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004865void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
4866 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 // TODO Write some statistics about how long we spend waiting.
4868}
4869
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004870/**
4871 * Report the touch event latency to the statsd server.
4872 * Input events are reported for statistics if:
4873 * - This is a touchscreen event
4874 * - InputFilter is not enabled
4875 * - Event is not injected or synthesized
4876 *
4877 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4878 * from getting aggregated with the "old" data.
4879 */
4880void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4881 REQUIRES(mLock) {
4882 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4883 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4884 if (!reportForStatistics) {
4885 return;
4886 }
4887
4888 if (mTouchStatistics.shouldReport()) {
4889 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4890 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4891 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4892 mTouchStatistics.reset();
4893 }
4894 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4895 mTouchStatistics.addValue(latencyMicros);
4896}
4897
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898void InputDispatcher::traceInboundQueueLengthLocked() {
4899 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004900 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901 }
4902}
4903
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004904void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905 if (ATRACE_ENABLED()) {
4906 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004907 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004908 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909 }
4910}
4911
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004912void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913 if (ATRACE_ENABLED()) {
4914 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004915 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004916 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917 }
4918}
4919
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004920void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004921 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004923 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 dumpDispatchStateLocked(dump);
4925
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004926 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004927 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004928 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929 }
4930}
4931
4932void InputDispatcher::monitor() {
4933 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004934 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004936 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004937}
4938
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004939/**
4940 * Wake up the dispatcher and wait until it processes all events and commands.
4941 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4942 * this method can be safely called from any thread, as long as you've ensured that
4943 * the work you are interested in completing has already been queued.
4944 */
4945bool InputDispatcher::waitForIdle() {
4946 /**
4947 * Timeout should represent the longest possible time that a device might spend processing
4948 * events and commands.
4949 */
4950 constexpr std::chrono::duration TIMEOUT = 100ms;
4951 std::unique_lock lock(mLock);
4952 mLooper->wake();
4953 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4954 return result == std::cv_status::no_timeout;
4955}
4956
Garfield Tane84e6f92019-08-29 17:28:41 -07004957} // namespace android::inputdispatcher