blob: 2658f783ac838d1a405ba6ef085c2215665ff11f [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 }
367 std::vector<uint8_t> data;
368 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
369 data.assign(start, start + size);
370 return sign(data);
371}
372
373std::array<uint8_t, 32> HmacKeyManager::sign(const std::vector<uint8_t>& data) const {
374 // SHA256 always generates 32-bytes result
375 std::array<uint8_t, 32> hash;
376 unsigned int hashLen = 0;
377 uint8_t* result = HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data.data(), data.size(),
378 hash.data(), &hashLen);
379 if (result == nullptr) {
380 ALOGE("Could not sign the data using HMAC");
381 return INVALID_HMAC;
382 }
383
384 if (hashLen != hash.size()) {
385 ALOGE("HMAC-SHA256 has unexpected length");
386 return INVALID_HMAC;
387 }
388
389 return hash;
390}
391
Michael Wrightd02c5b62014-02-10 15:10:22 -0800392// --- InputDispatcher ---
393
Garfield Tan00f511d2019-06-12 16:55:40 -0700394InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
395 : mPolicy(policy),
396 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700397 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800398 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700399 mAppSwitchSawKeyDown(false),
400 mAppSwitchDueTime(LONG_LONG_MAX),
401 mNextUnblockedEvent(nullptr),
402 mDispatchEnabled(false),
403 mDispatchFrozen(false),
404 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800405 // mInTouchMode will be initialized by the WindowManager to the default device config.
406 // To avoid leaking stack in case that call never comes, and for tests,
407 // initialize it here anyways.
408 mInTouchMode(true),
Garfield Tan00f511d2019-06-12 16:55:40 -0700409 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
410 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800412 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413
Yi Kong9b14ac62018-07-17 13:48:38 -0700414 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800415
416 policy->getDispatcherConfiguration(&mConfig);
417}
418
419InputDispatcher::~InputDispatcher() {
420 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800421 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800422
423 resetKeyRepeatLocked();
424 releasePendingEventLocked();
425 drainInboundQueueLocked();
426 }
427
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700428 while (!mConnectionsByFd.empty()) {
429 sp<Connection> connection = mConnectionsByFd.begin()->second;
430 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 }
432}
433
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700434status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700435 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700436 return ALREADY_EXISTS;
437 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700438 mThread = std::make_unique<InputThread>(
439 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
440 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700441}
442
443status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700444 if (mThread && mThread->isCallingThread()) {
445 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700446 return INVALID_OPERATION;
447 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700448 mThread.reset();
449 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700450}
451
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452void InputDispatcher::dispatchOnce() {
453 nsecs_t nextWakeupTime = LONG_LONG_MAX;
454 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800455 std::scoped_lock _l(mLock);
456 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800457
458 // Run a dispatch loop if there are no pending commands.
459 // The dispatch loop might enqueue commands to run afterwards.
460 if (!haveCommandsLocked()) {
461 dispatchOnceInnerLocked(&nextWakeupTime);
462 }
463
464 // Run all pending commands if there are any.
465 // If any commands were run then force the next poll to wake up immediately.
466 if (runCommandsLockedInterruptible()) {
467 nextWakeupTime = LONG_LONG_MIN;
468 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800469
470 // We are about to enter an infinitely long sleep, because we have no commands or
471 // pending or queued events
472 if (nextWakeupTime == LONG_LONG_MAX) {
473 mDispatcherEnteredIdle.notify_all();
474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800475 } // release lock
476
477 // Wait for callback or timeout or wake. (make sure we round up, not down)
478 nsecs_t currentTime = now();
479 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
480 mLooper->pollOnce(timeoutMillis);
481}
482
483void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
484 nsecs_t currentTime = now();
485
Jeff Browndc5992e2014-04-11 01:27:26 -0700486 // Reset the key repeat timer whenever normal dispatch is suspended while the
487 // device is in a non-interactive state. This is to ensure that we abort a key
488 // repeat if the device is just coming out of sleep.
489 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490 resetKeyRepeatLocked();
491 }
492
493 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
494 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100495 if (DEBUG_FOCUS) {
496 ALOGD("Dispatch frozen. Waiting some more.");
497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800498 return;
499 }
500
501 // Optimize latency of app switches.
502 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
503 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
504 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
505 if (mAppSwitchDueTime < *nextWakeupTime) {
506 *nextWakeupTime = mAppSwitchDueTime;
507 }
508
509 // Ready to start a new event.
510 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700511 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700512 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513 if (isAppSwitchDue) {
514 // The inbound queue is empty so the app switch key we were waiting
515 // for will never arrive. Stop waiting for it.
516 resetPendingAppSwitchLocked(false);
517 isAppSwitchDue = false;
518 }
519
520 // Synthesize a key repeat if appropriate.
521 if (mKeyRepeatState.lastKeyEntry) {
522 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
523 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
524 } else {
525 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
526 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
527 }
528 }
529 }
530
531 // Nothing to do if there is no pending event.
532 if (!mPendingEvent) {
533 return;
534 }
535 } else {
536 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700537 mPendingEvent = mInboundQueue.front();
538 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539 traceInboundQueueLengthLocked();
540 }
541
542 // Poke user activity for this event.
543 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700544 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 }
546
547 // Get ready to dispatch the event.
548 resetANRTimeoutsLocked();
549 }
550
551 // Now we have an event to dispatch.
552 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700553 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700555 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700557 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700559 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560 }
561
562 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700563 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564 }
565
566 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700567 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700568 ConfigurationChangedEntry* typedEntry =
569 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
570 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700571 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700572 break;
573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700575 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700576 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
577 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700578 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700579 break;
580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100582 case EventEntry::Type::FOCUS: {
583 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
584 dispatchFocusLocked(currentTime, typedEntry);
585 done = true;
586 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
587 break;
588 }
589
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700590 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700591 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
592 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700593 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700594 resetPendingAppSwitchLocked(true);
595 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700596 } else if (dropReason == DropReason::NOT_DROPPED) {
597 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700598 }
599 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700600 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700601 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700602 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700603 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
604 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700605 }
606 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
607 break;
608 }
609
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700610 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700611 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700612 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
613 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800614 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700615 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700616 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700617 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700618 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
619 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700620 }
621 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
622 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 }
625
626 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700627 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700628 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 }
Michael Wright3a981722015-06-10 15:26:13 +0100630 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631
632 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700633 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634 }
635}
636
637bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700638 bool needWake = mInboundQueue.empty();
639 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640 traceInboundQueueLengthLocked();
641
642 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700643 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700644 // Optimize app switch latency.
645 // If the application takes too long to catch up then we drop all events preceding
646 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700647 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700648 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700649 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700650 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700651 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700652 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700654 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700656 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700657 mAppSwitchSawKeyDown = false;
658 needWake = true;
659 }
660 }
661 }
662 break;
663 }
664
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700665 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700666 // Optimize case where the current application is unresponsive and the user
667 // decides to touch a window in a different application.
668 // If the application takes too long to catch up then we drop all events preceding
669 // the touch into the other window.
670 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
671 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
672 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
673 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
674 mInputTargetWaitApplicationToken != nullptr) {
675 int32_t displayId = motionEntry->displayId;
676 int32_t x =
677 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
678 int32_t y =
679 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
680 sp<InputWindowHandle> touchedWindowHandle =
681 findTouchedWindowAtLocked(displayId, x, y);
682 if (touchedWindowHandle != nullptr &&
683 touchedWindowHandle->getApplicationToken() !=
684 mInputTargetWaitApplicationToken) {
685 // User touched a different application than the one we are waiting on.
686 // Flag the event, and start pruning the input queue.
687 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 needWake = true;
689 }
690 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700691 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700693 case EventEntry::Type::CONFIGURATION_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100694 case EventEntry::Type::DEVICE_RESET:
695 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700696 // nothing to do
697 break;
698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699 }
700
701 return needWake;
702}
703
704void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
705 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700706 mRecentQueue.push_back(entry);
707 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
708 mRecentQueue.front()->release();
709 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710 }
711}
712
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700713sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
714 int32_t y, bool addOutsideTargets,
715 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800717 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
718 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719 const InputWindowInfo* windowInfo = windowHandle->getInfo();
720 if (windowInfo->displayId == displayId) {
721 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722
723 if (windowInfo->visible) {
724 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700725 bool isTouchModal = (flags &
726 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
727 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800729 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700730 if (portalToDisplayId != ADISPLAY_ID_NONE &&
731 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800732 if (addPortalWindows) {
733 // For the monitoring channels of the display.
734 mTempTouchState.addPortalWindow(windowHandle);
735 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700736 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
737 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800739 // Found window.
740 return windowHandle;
741 }
742 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800743
744 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700745 mTempTouchState.addOrUpdateWindow(windowHandle,
746 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
747 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800748 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 }
751 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700752 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753}
754
Garfield Tane84e6f92019-08-29 17:28:41 -0700755std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700756 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000757 std::vector<TouchedMonitor> touchedMonitors;
758
759 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
760 addGestureMonitors(monitors, touchedMonitors);
761 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
762 const InputWindowInfo* windowInfo = portalWindow->getInfo();
763 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700764 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
765 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000766 }
767 return touchedMonitors;
768}
769
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700770void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771 const char* reason;
772 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700773 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700775 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 reason = "inbound event was dropped because the policy consumed it";
778 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700779 case DropReason::DISABLED:
780 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700781 ALOGI("Dropped event because input dispatch is disabled.");
782 }
783 reason = "inbound event was dropped because input dispatch is disabled";
784 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700785 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700786 ALOGI("Dropped event because of pending overdue app switch.");
787 reason = "inbound event was dropped because of pending overdue app switch";
788 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700789 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700790 ALOGI("Dropped event because the current application is not responding and the user "
791 "has started interacting with a different application.");
792 reason = "inbound event was dropped because the current application is not responding "
793 "and the user has started interacting with a different application";
794 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700795 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700796 ALOGI("Dropped event because it is stale.");
797 reason = "inbound event was dropped because it is stale";
798 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700799 case DropReason::NOT_DROPPED: {
800 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700801 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 }
804
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700805 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700806 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800807 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
808 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700811 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700812 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
813 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700814 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
815 synthesizeCancelationEventsForAllConnectionsLocked(options);
816 } else {
817 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
818 synthesizeCancelationEventsForAllConnectionsLocked(options);
819 }
820 break;
821 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100822 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700823 case EventEntry::Type::CONFIGURATION_CHANGED:
824 case EventEntry::Type::DEVICE_RESET: {
825 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
826 break;
827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800828 }
829}
830
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800831static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700832 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
833 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834}
835
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700836bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
837 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
838 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
839 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840}
841
842bool InputDispatcher::isAppSwitchPendingLocked() {
843 return mAppSwitchDueTime != LONG_LONG_MAX;
844}
845
846void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
847 mAppSwitchDueTime = LONG_LONG_MAX;
848
849#if DEBUG_APP_SWITCH
850 if (handled) {
851 ALOGD("App switch has arrived.");
852 } else {
853 ALOGD("App switch was abandoned.");
854 }
855#endif
856}
857
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700859 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860}
861
862bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700863 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 return false;
865 }
866
867 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700868 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700869 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700871 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872
873 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700874 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 return true;
876}
877
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700878void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
879 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880}
881
882void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700883 while (!mInboundQueue.empty()) {
884 EventEntry* entry = mInboundQueue.front();
885 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 releaseInboundEventLocked(entry);
887 }
888 traceInboundQueueLengthLocked();
889}
890
891void InputDispatcher::releasePendingEventLocked() {
892 if (mPendingEvent) {
893 resetANRTimeoutsLocked();
894 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700895 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
897}
898
899void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
900 InjectionState* injectionState = entry->injectionState;
901 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
902#if DEBUG_DISPATCH_CYCLE
903 ALOGD("Injected inbound event was dropped.");
904#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800905 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 }
907 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700908 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 }
910 addRecentEventLocked(entry);
911 entry->release();
912}
913
914void InputDispatcher::resetKeyRepeatLocked() {
915 if (mKeyRepeatState.lastKeyEntry) {
916 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700917 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800918 }
919}
920
Garfield Tane84e6f92019-08-29 17:28:41 -0700921KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
923
924 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700925 uint32_t policyFlags = entry->policyFlags &
926 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 if (entry->refCount == 1) {
928 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800929 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 entry->eventTime = currentTime;
931 entry->policyFlags = policyFlags;
932 entry->repeatCount += 1;
933 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700934 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800935 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800936 entry->displayId, policyFlags, entry->action, entry->flags,
937 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700938 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939
940 mKeyRepeatState.lastKeyEntry = newEntry;
941 entry->release();
942
943 entry = newEntry;
944 }
945 entry->syntheticRepeat = true;
946
947 // Increment reference count since we keep a reference to the event in
948 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
949 entry->refCount += 1;
950
951 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
952 return entry;
953}
954
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700955bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
956 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700958 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959#endif
960
961 // Reset key repeating in case a keyboard device was added or removed or something.
962 resetKeyRepeatLocked();
963
964 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700965 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
966 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700968 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 return true;
970}
971
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700972bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700974 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700975 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976#endif
977
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700978 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 options.deviceId = entry->deviceId;
980 synthesizeCancelationEventsForAllConnectionsLocked(options);
981 return true;
982}
983
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100984void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
985 FocusEntry* focusEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800986 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100987 enqueueInboundEventLocked(focusEntry);
988}
989
990void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
991 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
992 if (channel == nullptr) {
993 return; // Window has gone away
994 }
995 InputTarget target;
996 target.inputChannel = channel;
997 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
998 entry->dispatchInProgress = true;
999
1000 dispatchEventLocked(currentTime, entry, {target});
1001}
1002
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001004 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001006 if (!entry->dispatchInProgress) {
1007 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1008 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1009 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1010 if (mKeyRepeatState.lastKeyEntry &&
1011 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 // We have seen two identical key downs in a row which indicates that the device
1013 // driver is automatically generating key repeats itself. We take note of the
1014 // repeat here, but we disable our own next key repeat timer since it is clear that
1015 // we will not need to synthesize key repeats ourselves.
1016 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1017 resetKeyRepeatLocked();
1018 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1019 } else {
1020 // Not a repeat. Save key down state in case we do see a repeat later.
1021 resetKeyRepeatLocked();
1022 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1023 }
1024 mKeyRepeatState.lastKeyEntry = entry;
1025 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001026 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 resetKeyRepeatLocked();
1028 }
1029
1030 if (entry->repeatCount == 1) {
1031 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1032 } else {
1033 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1034 }
1035
1036 entry->dispatchInProgress = true;
1037
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001038 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
1040
1041 // Handle case where the policy asked us to try again later last time.
1042 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1043 if (currentTime < entry->interceptKeyWakeupTime) {
1044 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1045 *nextWakeupTime = entry->interceptKeyWakeupTime;
1046 }
1047 return false; // wait until next wakeup
1048 }
1049 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1050 entry->interceptKeyWakeupTime = 0;
1051 }
1052
1053 // Give the policy a chance to intercept the key.
1054 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1055 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001056 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001057 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001058 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001059 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001060 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001061 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 }
1063 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001064 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 entry->refCount += 1;
1066 return false; // wait for the command to run
1067 } else {
1068 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1069 }
1070 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001071 if (*dropReason == DropReason::NOT_DROPPED) {
1072 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
1074 }
1075
1076 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001077 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001081 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 return true;
1083 }
1084
1085 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001086 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001087 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001088 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1090 return false;
1091 }
1092
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001093 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1095 return true;
1096 }
1097
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001098 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001099 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100
1101 // Dispatch the key.
1102 dispatchEventLocked(currentTime, entry, inputTargets);
1103 return true;
1104}
1105
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001106void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001108 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001109 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1110 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001111 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1112 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1113 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114#endif
1115}
1116
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001117bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1118 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001119 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001121 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 entry->dispatchInProgress = true;
1123
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001124 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 }
1126
1127 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001128 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001130 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001131 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 return true;
1133 }
1134
1135 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1136
1137 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001138 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139
1140 bool conflictingPointerActions = false;
1141 int32_t injectionResult;
1142 if (isPointerEvent) {
1143 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001144 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001145 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001146 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 } else {
1148 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001149 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001150 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 }
1152 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1153 return false;
1154 }
1155
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001156 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001158 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001159 CancelationOptions::Mode mode(isPointerEvent
1160 ? CancelationOptions::CANCEL_POINTER_EVENTS
1161 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001162 CancelationOptions options(mode, "input event injection failed");
1163 synthesizeCancelationEventsForMonitorsLocked(options);
1164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165 return true;
1166 }
1167
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001168 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001169 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001171 if (isPointerEvent) {
1172 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
1173 if (stateIndex >= 0) {
1174 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001175 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001176 // The event has gone through these portal windows, so we add monitoring targets of
1177 // the corresponding displays as well.
1178 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001179 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001180 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001181 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001182 }
1183 }
1184 }
1185 }
1186
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 // Dispatch the motion.
1188 if (conflictingPointerActions) {
1189 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001190 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 synthesizeCancelationEventsForAllConnectionsLocked(options);
1192 }
1193 dispatchEventLocked(currentTime, entry, inputTargets);
1194 return true;
1195}
1196
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001197void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001199 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001200 ", policyFlags=0x%x, "
1201 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1202 "metaState=0x%x, buttonState=0x%x,"
1203 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001204 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1205 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1206 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001208 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 "x=%f, y=%f, pressure=%f, size=%f, "
1211 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1212 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001213 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1214 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1215 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1216 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1217 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1218 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1219 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1220 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1221 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1222 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 }
1224#endif
1225}
1226
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001227void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1228 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001229 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230#if DEBUG_DISPATCH_CYCLE
1231 ALOGD("dispatchEventToCurrentInputTargets");
1232#endif
1233
1234 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1235
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001236 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001238 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001239 sp<Connection> connection =
1240 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001241 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001242 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001244 if (DEBUG_FOCUS) {
1245 ALOGD("Dropping event delivery to target with channel '%s' because it "
1246 "is no longer registered with the input dispatcher.",
1247 inputTarget.inputChannel->getName().c_str());
1248 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 }
1250 }
1251}
1252
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001253int32_t InputDispatcher::handleTargetsNotReadyLocked(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001254 nsecs_t currentTime, const EventEntry& entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001256 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001257 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001259 if (DEBUG_FOCUS) {
1260 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1263 mInputTargetWaitStartTime = currentTime;
1264 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1265 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001266 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 }
1268 } else {
1269 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001270 ALOGI("Waiting for application to become ready for input: %s. Reason: %s",
1271 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001273 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001275 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001276 timeout =
1277 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 } else {
1279 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1280 }
1281
1282 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1283 mInputTargetWaitStartTime = currentTime;
1284 mInputTargetWaitTimeoutTime = currentTime + timeout;
1285 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001286 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287
Yi Kong9b14ac62018-07-17 13:48:38 -07001288 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001289 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 }
Robert Carr740167f2018-10-11 19:03:41 -07001291 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1292 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 }
1294 }
1295 }
1296
1297 if (mInputTargetWaitTimeoutExpired) {
1298 return INPUT_EVENT_INJECTION_TIMED_OUT;
1299 }
1300
1301 if (currentTime >= mInputTargetWaitTimeoutTime) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001302 onANRLocked(currentTime, applicationHandle, windowHandle, entry.eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304
1305 // Force poll loop to wake up immediately on next iteration once we get the
1306 // ANR response back from the policy.
1307 *nextWakeupTime = LONG_LONG_MIN;
1308 return INPUT_EVENT_INJECTION_PENDING;
1309 } else {
1310 // Force poll loop to wake up when timeout is due.
1311 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1312 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1313 }
1314 return INPUT_EVENT_INJECTION_PENDING;
1315 }
1316}
1317
Robert Carr803535b2018-08-02 16:38:15 -07001318void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1319 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1320 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1321 state.removeWindowByToken(token);
1322 }
1323}
1324
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001325void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001326 nsecs_t newTimeout, const sp<IBinder>& inputConnectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 if (newTimeout > 0) {
1328 // Extend the timeout.
1329 mInputTargetWaitTimeoutTime = now() + newTimeout;
1330 } else {
1331 // Give up.
1332 mInputTargetWaitTimeoutExpired = true;
1333
1334 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001335 sp<Connection> connection = getConnectionLocked(inputConnectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001336 if (connection != nullptr) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07001337 removeWindowByTokenLocked(inputConnectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001339 if (connection->status == Connection::STATUS_NORMAL) {
1340 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1341 "application not responding");
1342 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 }
1344 }
1345 }
1346}
1347
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001348nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1350 return currentTime - mInputTargetWaitStartTime;
1351 }
1352 return 0;
1353}
1354
1355void InputDispatcher::resetANRTimeoutsLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001356 if (DEBUG_FOCUS) {
1357 ALOGD("Resetting ANR timeouts.");
1358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359
1360 // Reset input target wait timeout.
1361 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001362 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363}
1364
Tiger Huang721e26f2018-07-24 22:26:19 +08001365/**
1366 * Get the display id that the given event should go to. If this event specifies a valid display id,
1367 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1368 * Focused display is the display that the user most recently interacted with.
1369 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001370int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001371 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001372 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001373 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001374 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1375 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001376 break;
1377 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001378 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001379 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1380 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001381 break;
1382 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001383 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001384 case EventEntry::Type::CONFIGURATION_CHANGED:
1385 case EventEntry::Type::DEVICE_RESET: {
1386 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001387 return ADISPLAY_ID_NONE;
1388 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001389 }
1390 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1391}
1392
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001394 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001395 std::vector<InputTarget>& inputTargets,
1396 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001398 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399
Tiger Huang721e26f2018-07-24 22:26:19 +08001400 int32_t displayId = getTargetDisplayId(entry);
1401 sp<InputWindowHandle> focusedWindowHandle =
1402 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1403 sp<InputApplicationHandle> focusedApplicationHandle =
1404 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1405
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406 // If there is no currently focused window and no focused application
1407 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001408 if (focusedWindowHandle == nullptr) {
1409 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001410 injectionResult =
1411 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1412 nullptr, nextWakeupTime,
1413 "Waiting because no window has focus but there is "
1414 "a focused application that may eventually add a "
1415 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416 goto Unresponsive;
1417 }
1418
Arthur Hung3b413f22018-10-26 18:05:34 +08001419 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001420 "%" PRId32 ".",
1421 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1423 goto Failed;
1424 }
1425
1426 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001427 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1429 goto Failed;
1430 }
1431
Jeff Brownffb49772014-10-10 19:01:34 -07001432 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001433 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001434 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001435 injectionResult =
1436 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1437 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438 goto Unresponsive;
1439 }
1440
1441 // Success! Output targets.
1442 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001443 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001444 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1445 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446
1447 // Done.
1448Failed:
1449Unresponsive:
1450 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001451 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001452 if (DEBUG_FOCUS) {
1453 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1454 "timeSpentWaitingForApplication=%0.1fms",
1455 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1456 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457 return injectionResult;
1458}
1459
1460int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001461 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001462 std::vector<InputTarget>& inputTargets,
1463 nsecs_t* nextWakeupTime,
1464 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001465 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 enum InjectionPermission {
1467 INJECTION_PERMISSION_UNKNOWN,
1468 INJECTION_PERMISSION_GRANTED,
1469 INJECTION_PERMISSION_DENIED
1470 };
1471
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 // For security reasons, we defer updating the touch state until we are sure that
1473 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001474 int32_t displayId = entry.displayId;
1475 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1477
1478 // Update the touch state as needed based on the properties of the touch event.
1479 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1480 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1481 sp<InputWindowHandle> newHoverWindowHandle;
1482
Jeff Brownf086ddb2014-02-11 14:28:48 -08001483 // Copy current touch state into mTempTouchState.
1484 // This state is always reset at the end of this function, so if we don't find state
1485 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001486 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001487 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1488 if (oldStateIndex >= 0) {
1489 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1490 mTempTouchState.copyFrom(*oldState);
1491 }
1492
1493 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001494 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001495 (mTempTouchState.deviceId != entry.deviceId || mTempTouchState.source != entry.source ||
1496 mTempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001497 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1498 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1499 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1500 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1501 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001502 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 bool wrongDevice = false;
1504 if (newGesture) {
1505 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001506 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001507 ALOGI("Dropping event because a pointer for a different device is already down "
1508 "in display %" PRId32,
1509 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001510 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1512 switchedDevice = false;
1513 wrongDevice = true;
1514 goto Failed;
1515 }
1516 mTempTouchState.reset();
1517 mTempTouchState.down = down;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001518 mTempTouchState.deviceId = entry.deviceId;
1519 mTempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520 mTempTouchState.displayId = displayId;
1521 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001522 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001523 ALOGI("Dropping move event because a pointer for a different device is already active "
1524 "in display %" PRId32,
1525 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001526 // TODO: test multiple simultaneous input streams.
1527 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1528 switchedDevice = false;
1529 wrongDevice = true;
1530 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 }
1532
1533 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1534 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1535
Garfield Tan00f511d2019-06-12 16:55:40 -07001536 int32_t x;
1537 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001539 // Always dispatch mouse events to cursor position.
1540 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001541 x = int32_t(entry.xCursorPosition);
1542 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001543 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001544 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1545 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001546 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001547 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001548 sp<InputWindowHandle> newTouchedWindowHandle =
1549 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1550 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001551
1552 std::vector<TouchedMonitor> newGestureMonitors = isDown
1553 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1554 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555
Michael Wrightd02c5b62014-02-10 15:10:22 -08001556 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001557 if (newTouchedWindowHandle != nullptr &&
1558 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001559 // New window supports splitting, but we should never split mouse events.
1560 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 } else if (isSplit) {
1562 // New window does not support splitting but we have already split events.
1563 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001564 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 }
1566
1567 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001568 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569 // Try to assign the pointer to the first foreground window we find, if there is one.
1570 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001571 }
1572
1573 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1574 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001575 "(%d, %d) in display %" PRId32 ".",
1576 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001577 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1578 goto Failed;
1579 }
1580
1581 if (newTouchedWindowHandle != nullptr) {
1582 // Set target flags.
1583 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1584 if (isSplit) {
1585 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001587 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1588 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1589 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1590 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1591 }
1592
1593 // Update hover state.
1594 if (isHoverAction) {
1595 newHoverWindowHandle = newTouchedWindowHandle;
1596 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1597 newHoverWindowHandle = mLastHoverWindowHandle;
1598 }
1599
1600 // Update the temporary touch state.
1601 BitSet32 pointerIds;
1602 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001603 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001604 pointerIds.markBit(pointerId);
1605 }
1606 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 }
1608
Michael Wright3dd60e22019-03-27 22:06:44 +00001609 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 } else {
1611 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1612
1613 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001614 if (!mTempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001615 if (DEBUG_FOCUS) {
1616 ALOGD("Dropping event because the pointer is not down or we previously "
1617 "dropped the pointer down event in display %" PRId32,
1618 displayId);
1619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1621 goto Failed;
1622 }
1623
1624 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001625 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001626 mTempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001627 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1628 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629
1630 sp<InputWindowHandle> oldTouchedWindowHandle =
1631 mTempTouchState.getFirstForegroundWindowHandle();
1632 sp<InputWindowHandle> newTouchedWindowHandle =
1633 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001634 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1635 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001636 if (DEBUG_FOCUS) {
1637 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1638 oldTouchedWindowHandle->getName().c_str(),
1639 newTouchedWindowHandle->getName().c_str(), displayId);
1640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 // Make a slippery exit from the old window.
1642 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001643 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1644 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645
1646 // Make a slippery entrance into the new window.
1647 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1648 isSplit = true;
1649 }
1650
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001651 int32_t targetFlags =
1652 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 if (isSplit) {
1654 targetFlags |= InputTarget::FLAG_SPLIT;
1655 }
1656 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1657 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1658 }
1659
1660 BitSet32 pointerIds;
1661 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001662 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 }
1664 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1665 }
1666 }
1667 }
1668
1669 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1670 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001671 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672#if DEBUG_HOVER
1673 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001674 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675#endif
1676 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001677 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1678 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 }
1680
1681 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001682 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683#if DEBUG_HOVER
1684 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001685 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686#endif
1687 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001688 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1689 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 }
1691 }
1692
1693 // Check permission to inject into all touched foreground windows and ensure there
1694 // is at least one touched foreground window.
1695 {
1696 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001697 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1699 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001700 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1702 injectionPermission = INJECTION_PERMISSION_DENIED;
1703 goto Failed;
1704 }
1705 }
1706 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001707 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1708 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001709 ALOGI("Dropping event because there is no touched foreground window in display "
1710 "%" PRId32 " or gesture monitor to receive it.",
1711 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1713 goto Failed;
1714 }
1715
1716 // Permission granted to injection into all touched foreground windows.
1717 injectionPermission = INJECTION_PERMISSION_GRANTED;
1718 }
1719
1720 // Check whether windows listening for outside touches are owned by the same UID. If it is
1721 // set the policy flag that we will not reveal coordinate information to this window.
1722 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1723 sp<InputWindowHandle> foregroundWindowHandle =
1724 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001725 if (foregroundWindowHandle) {
1726 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1727 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1728 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1729 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1730 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1731 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001732 InputTarget::FLAG_ZERO_COORDS,
1733 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001734 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735 }
1736 }
1737 }
1738 }
1739
1740 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001741 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001743 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001744 std::string reason =
1745 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1746 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001747 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001748 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1749 touchedWindow.windowHandle,
1750 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 goto Unresponsive;
1752 }
1753 }
1754 }
1755
1756 // If this is the first pointer going down and the touched window has a wallpaper
1757 // then also add the touched wallpaper windows so they are locked in for the duration
1758 // of the touch gesture.
1759 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1760 // engine only supports touch events. We would need to add a mechanism similar
1761 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1762 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1763 sp<InputWindowHandle> foregroundWindowHandle =
1764 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001765 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001766 const std::vector<sp<InputWindowHandle>> windowHandles =
1767 getWindowHandlesLocked(displayId);
1768 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001770 if (info->displayId == displayId &&
1771 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1772 mTempTouchState
1773 .addOrUpdateWindow(windowHandle,
1774 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1775 InputTarget::
1776 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1777 InputTarget::FLAG_DISPATCH_AS_IS,
1778 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779 }
1780 }
1781 }
1782 }
1783
1784 // Success! Output targets.
1785 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1786
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001787 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001789 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790 }
1791
Michael Wright3dd60e22019-03-27 22:06:44 +00001792 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1793 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001794 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001795 }
1796
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 // Drop the outside or hover touch windows since we will not care about them
1798 // in the next iteration.
1799 mTempTouchState.filterNonAsIsTouchWindows();
1800
1801Failed:
1802 // Check injection permission once and for all.
1803 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001804 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805 injectionPermission = INJECTION_PERMISSION_GRANTED;
1806 } else {
1807 injectionPermission = INJECTION_PERMISSION_DENIED;
1808 }
1809 }
1810
1811 // Update final pieces of touch state if the injector had permission.
1812 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1813 if (!wrongDevice) {
1814 if (switchedDevice) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001815 if (DEBUG_FOCUS) {
1816 ALOGD("Conflicting pointer actions: Switched to a different device.");
1817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 *outConflictingPointerActions = true;
1819 }
1820
1821 if (isHoverAction) {
1822 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001823 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001824 if (DEBUG_FOCUS) {
1825 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1826 "down.");
1827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 *outConflictingPointerActions = true;
1829 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001830 mTempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001831 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1832 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001833 mTempTouchState.deviceId = entry.deviceId;
1834 mTempTouchState.source = entry.source;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001835 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001837 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1838 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001840 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1842 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001843 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001844 if (DEBUG_FOCUS) {
1845 ALOGD("Conflicting pointer actions: Down received while already down.");
1846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 *outConflictingPointerActions = true;
1848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1850 // One pointer went up.
1851 if (isSplit) {
1852 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001853 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001855 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001856 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1858 touchedWindow.pointerIds.clearBit(pointerId);
1859 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001860 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 continue;
1862 }
1863 }
1864 i += 1;
1865 }
1866 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001867 }
1868
1869 // Save changes unless the action was scroll in which case the temporary touch
1870 // state was only valid for this one action.
1871 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1872 if (mTempTouchState.displayId >= 0) {
1873 if (oldStateIndex >= 0) {
1874 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1875 } else {
1876 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1877 }
1878 } else if (oldStateIndex >= 0) {
1879 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 }
1882
1883 // Update hover state.
1884 mLastHoverWindowHandle = newHoverWindowHandle;
1885 }
1886 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001887 if (DEBUG_FOCUS) {
1888 ALOGD("Not updating touch focus because injection was denied.");
1889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 }
1891
1892Unresponsive:
1893 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1894 mTempTouchState.reset();
1895
1896 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001897 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001898 if (DEBUG_FOCUS) {
1899 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1900 "timeSpentWaitingForApplication=%0.1fms",
1901 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 return injectionResult;
1904}
1905
1906void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001907 int32_t targetFlags, BitSet32 pointerIds,
1908 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001909 std::vector<InputTarget>::iterator it =
1910 std::find_if(inputTargets.begin(), inputTargets.end(),
1911 [&windowHandle](const InputTarget& inputTarget) {
1912 return inputTarget.inputChannel->getConnectionToken() ==
1913 windowHandle->getToken();
1914 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00001915
Chavi Weingarten114b77f2020-01-15 22:35:10 +00001916 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001917
1918 if (it == inputTargets.end()) {
1919 InputTarget inputTarget;
1920 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1921 if (inputChannel == nullptr) {
1922 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1923 return;
1924 }
1925 inputTarget.inputChannel = inputChannel;
1926 inputTarget.flags = targetFlags;
1927 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
1928 inputTargets.push_back(inputTarget);
1929 it = inputTargets.end() - 1;
1930 }
1931
1932 ALOG_ASSERT(it->flags == targetFlags);
1933 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
1934
1935 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
1936 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937}
1938
Michael Wright3dd60e22019-03-27 22:06:44 +00001939void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001940 int32_t displayId, float xOffset,
1941 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001942 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1943 mGlobalMonitorsByDisplay.find(displayId);
1944
1945 if (it != mGlobalMonitorsByDisplay.end()) {
1946 const std::vector<Monitor>& monitors = it->second;
1947 for (const Monitor& monitor : monitors) {
1948 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 }
1951}
1952
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001953void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1954 float yOffset,
1955 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001956 InputTarget target;
1957 target.inputChannel = monitor.inputChannel;
1958 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001959 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00001960 inputTargets.push_back(target);
1961}
1962
Michael Wrightd02c5b62014-02-10 15:10:22 -08001963bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001964 const InjectionState* injectionState) {
1965 if (injectionState &&
1966 (windowHandle == nullptr ||
1967 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1968 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001969 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001971 "owned by uid %d",
1972 injectionState->injectorPid, injectionState->injectorUid,
1973 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974 } else {
1975 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001976 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977 }
1978 return false;
1979 }
1980 return true;
1981}
1982
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001983bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1984 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001986 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1987 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
minchelif28cc4e2020-03-19 11:18:11 +08001988 if (haveSameToken(otherHandle, windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 break;
1990 }
1991
1992 const InputWindowInfo* otherInfo = otherHandle->getInfo();
minchelif28cc4e2020-03-19 11:18:11 +08001993 if (otherInfo->visible && !otherInfo->isTrustedOverlay() &&
1994 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995 return true;
1996 }
1997 }
1998 return false;
1999}
2000
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002001bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2002 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002003 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002004 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002005 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
minchelif28cc4e2020-03-19 11:18:11 +08002006 if (haveSameToken(otherHandle, windowHandle)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002007 break;
2008 }
2009
2010 const InputWindowInfo* otherInfo = otherHandle->getInfo();
minchelif28cc4e2020-03-19 11:18:11 +08002011 if (otherInfo->visible && !otherInfo->isTrustedOverlay() &&
2012 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002013 return true;
2014 }
2015 }
2016 return false;
2017}
2018
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002019std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
2020 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002021 const EventEntry& eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07002022 // If the window is paused then keep waiting.
2023 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002024 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002025 }
2026
2027 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07002028 sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002029 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002030 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002031 "registered with the input dispatcher. The window may be in the "
2032 "process of being removed.",
2033 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07002034 }
2035
2036 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07002037 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002038 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002039 "The window may be in the process of being removed.",
2040 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07002041 }
2042
2043 // If the connection is backed up then keep waiting.
2044 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002045 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002046 "Outbound queue length: %zu. Wait queue length: %zu.",
2047 targetType, connection->outboundQueue.size(),
2048 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07002049 }
2050
2051 // Ensure that the dispatch queues aren't too far backed up for this event.
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002052 if (eventEntry.type == EventEntry::Type::KEY) {
Jeff Brownffb49772014-10-10 19:01:34 -07002053 // If the event is a key event, then we must wait for all previous events to
2054 // complete before delivering it because previous events may have the
2055 // side-effect of transferring focus to a different window and we want to
2056 // ensure that the following keys are sent to the new window.
2057 //
2058 // Suppose the user touches a button in a window then immediately presses "A".
2059 // If the button causes a pop-up window to appear then we want to ensure that
2060 // the "A" key is delivered to the new pop-up window. This is because users
2061 // often anticipate pending UI changes when typing on a keyboard.
2062 // To obtain this behavior, we must serialize key events with respect to all
2063 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002064 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002065 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002066 "finished processing all of the input events that were previously "
2067 "delivered to it. Outbound queue length: %zu. Wait queue length: "
2068 "%zu.",
2069 targetType, connection->outboundQueue.size(),
2070 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 }
Jeff Brownffb49772014-10-10 19:01:34 -07002072 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 // Touch events can always be sent to a window immediately because the user intended
2074 // to touch whatever was visible at the time. Even if focus changes or a new
2075 // window appears moments later, the touch event was meant to be delivered to
2076 // whatever window happened to be on screen at the time.
2077 //
2078 // Generic motion events, such as trackball or joystick events are a little trickier.
2079 // Like key events, generic motion events are delivered to the focused window.
2080 // Unlike key events, generic motion events don't tend to transfer focus to other
2081 // windows and it is not important for them to be serialized. So we prefer to deliver
2082 // generic motion events as soon as possible to improve efficiency and reduce lag
2083 // through batching.
2084 //
2085 // The one case where we pause input event delivery is when the wait queue is piling
2086 // up with lots of events because the application is not responding.
2087 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002088 if (!connection->waitQueue.empty() &&
2089 currentTime >=
2090 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002091 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002092 "finished processing certain input events that were delivered to "
2093 "it over "
2094 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
2095 "%0.1fms.",
2096 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
2097 connection->waitQueue.size(),
2098 (currentTime - connection->waitQueue.front()->deliveryTime) *
2099 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100 }
2101 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002102 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103}
2104
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002105std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 const sp<InputApplicationHandle>& applicationHandle,
2107 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002108 if (applicationHandle != nullptr) {
2109 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002110 std::string label(applicationHandle->getName());
2111 label += " - ";
2112 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 return label;
2114 } else {
2115 return applicationHandle->getName();
2116 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002117 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118 return windowHandle->getName();
2119 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002120 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 }
2122}
2123
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002124void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002125 if (eventEntry.type == EventEntry::Type::FOCUS) {
2126 // Focus events are passed to apps, but do not represent user activity.
2127 return;
2128 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002129 int32_t displayId = getTargetDisplayId(eventEntry);
2130 sp<InputWindowHandle> focusedWindowHandle =
2131 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2132 if (focusedWindowHandle != nullptr) {
2133 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2135#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002136 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137#endif
2138 return;
2139 }
2140 }
2141
2142 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002143 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002144 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002145 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2146 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002147 return;
2148 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002150 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002151 eventType = USER_ACTIVITY_EVENT_TOUCH;
2152 }
2153 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002155 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002156 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2157 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002158 return;
2159 }
2160 eventType = USER_ACTIVITY_EVENT_BUTTON;
2161 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002163 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002164 case EventEntry::Type::CONFIGURATION_CHANGED:
2165 case EventEntry::Type::DEVICE_RESET: {
2166 LOG_ALWAYS_FATAL("%s events are not user activity",
2167 EventEntry::typeToString(eventEntry.type));
2168 break;
2169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 }
2171
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002172 std::unique_ptr<CommandEntry> commandEntry =
2173 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002174 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002176 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177}
2178
2179void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002180 const sp<Connection>& connection,
2181 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002182 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002183 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002184 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002185 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002186 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002187 ATRACE_NAME(message.c_str());
2188 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189#if DEBUG_DISPATCH_CYCLE
2190 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002191 "globalScaleFactor=%f, pointerIds=0x%x %s",
2192 connection->getInputChannelName().c_str(), inputTarget.flags,
2193 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2194 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195#endif
2196
2197 // Skip this event if the connection status is not normal.
2198 // We don't want to enqueue additional outbound events if the connection is broken.
2199 if (connection->status != Connection::STATUS_NORMAL) {
2200#if DEBUG_DISPATCH_CYCLE
2201 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002202 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203#endif
2204 return;
2205 }
2206
2207 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002208 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2209 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2210 "Entry type %s should not have FLAG_SPLIT",
2211 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002213 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002214 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002215 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002216 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217 if (!splitMotionEntry) {
2218 return; // split event was dropped
2219 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002220 if (DEBUG_FOCUS) {
2221 ALOGD("channel '%s' ~ Split motion event.",
2222 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002223 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002224 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002225 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 splitMotionEntry->release();
2227 return;
2228 }
2229 }
2230
2231 // Not splitting. Enqueue dispatch entries for the event as is.
2232 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2233}
2234
2235void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002236 const sp<Connection>& connection,
2237 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002238 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002239 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002240 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002241 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002242 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002243 ATRACE_NAME(message.c_str());
2244 }
2245
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002246 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247
2248 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002249 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002250 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002251 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002252 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002253 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002255 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002256 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002257 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002258 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002259 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002260 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261
2262 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002263 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 startDispatchCycleLocked(currentTime, connection);
2265 }
2266}
2267
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002268void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2269 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002270 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002271 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002272 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002273 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2274 connection->getInputChannelName().c_str(),
2275 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002276 ATRACE_NAME(message.c_str());
2277 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002278 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 if (!(inputTargetFlags & dispatchMode)) {
2280 return;
2281 }
2282 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2283
2284 // This is a new event.
2285 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002286 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002287 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002289 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2290 // different EventEntry than what was passed in.
2291 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002293 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002294 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002295 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002296 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002297 dispatchEntry->resolvedAction = keyEntry.action;
2298 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002300 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2301 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002303 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2304 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002306 return; // skip the inconsistent event
2307 }
2308 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002311 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002312 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002313 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2314 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2315 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2316 static_cast<int32_t>(IdGenerator::Source::OTHER);
2317 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002318 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2319 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2320 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2321 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2322 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2323 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2324 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2325 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2326 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2327 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2328 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002329 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002330 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002331 }
2332 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002333 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2334 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002336 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2337 "event",
2338 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002340 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002343 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002344 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2345 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2346 }
2347 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2348 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002351 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2352 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002354 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2355 "event",
2356 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002358 return; // skip the inconsistent event
2359 }
2360
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002361 dispatchEntry->resolvedEventId =
2362 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2363 ? mIdGenerator.nextId()
2364 : motionEntry.id;
2365 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2366 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2367 ") to MotionEvent(id=0x%" PRIx32 ").",
2368 motionEntry.id, dispatchEntry->resolvedEventId);
2369 ATRACE_NAME(message.c_str());
2370 }
2371
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002372 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002373 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002374
2375 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002377 case EventEntry::Type::FOCUS: {
2378 break;
2379 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002380 case EventEntry::Type::CONFIGURATION_CHANGED:
2381 case EventEntry::Type::DEVICE_RESET: {
2382 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002383 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002384 break;
2385 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 }
2387
2388 // Remember that we are waiting for this dispatch to complete.
2389 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002390 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391 }
2392
2393 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002394 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002395 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002396}
2397
chaviwfd6d3512019-03-25 13:23:49 -07002398void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002399 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002400 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002401 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2402 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002403 return;
2404 }
2405
2406 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2407 if (inputWindowHandle == nullptr) {
2408 return;
2409 }
2410
chaviw8c9cf542019-03-25 13:02:48 -07002411 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002412 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002413
2414 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2415
2416 if (!hasFocusChanged) {
2417 return;
2418 }
2419
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002420 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2421 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002422 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002423 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424}
2425
2426void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002427 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002428 if (ATRACE_ENABLED()) {
2429 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002430 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002431 ATRACE_NAME(message.c_str());
2432 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002434 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435#endif
2436
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002437 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2438 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439 dispatchEntry->deliveryTime = currentTime;
2440
2441 // Publish the event.
2442 status_t status;
2443 EventEntry* eventEntry = dispatchEntry->eventEntry;
2444 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002445 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002446 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Gang Wange9087892020-01-07 12:17:14 -05002447 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(*keyEntry);
2448 verifiedEvent.flags = dispatchEntry->resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2449 verifiedEvent.action = dispatchEntry->resolvedAction;
2450 std::array<uint8_t, 32> hmac = mHmacKeyManager.sign(verifiedEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002452 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002453 status =
2454 connection->inputPublisher
2455 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2456 keyEntry->deviceId, keyEntry->source,
2457 keyEntry->displayId, std::move(hmac),
2458 dispatchEntry->resolvedAction,
2459 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2460 keyEntry->scanCode, keyEntry->metaState,
2461 keyEntry->repeatCount, keyEntry->downTime,
2462 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002463 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 }
2465
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002466 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002467 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002469 PointerCoords scaledCoords[MAX_POINTERS];
2470 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2471
chaviw82357092020-01-28 13:13:06 -08002472 // Set the X and Y offset and X and Y scale depending on the input source.
2473 float xOffset = 0.0f, yOffset = 0.0f;
2474 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002475 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2476 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2477 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002478 xScale = dispatchEntry->windowXScale;
2479 yScale = dispatchEntry->windowYScale;
2480 xOffset = dispatchEntry->xOffset * xScale;
2481 yOffset = dispatchEntry->yOffset * yScale;
2482 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002483 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2484 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002485 // Don't apply window scale here since we don't want scale to affect raw
2486 // coordinates. The scale will be sent back to the client and applied
2487 // later when requesting relative coordinates.
2488 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2489 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002490 }
2491 usingCoords = scaledCoords;
2492 }
2493 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002494 // We don't want the dispatch target to know.
2495 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2496 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2497 scaledCoords[i].clear();
2498 }
2499 usingCoords = scaledCoords;
2500 }
2501 }
Gang Wange9087892020-01-07 12:17:14 -05002502 VerifiedMotionEvent verifiedEvent =
2503 verifiedMotionEventFromMotionEntry(*motionEntry);
2504 verifiedEvent.actionMasked =
2505 dispatchEntry->resolvedAction & AMOTION_EVENT_ACTION_MASK;
2506 verifiedEvent.flags = dispatchEntry->resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2507 std::array<uint8_t, 32> hmac = mHmacKeyManager.sign(verifiedEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002508
2509 // Publish the motion event.
2510 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002511 .publishMotionEvent(dispatchEntry->seq,
2512 dispatchEntry->resolvedEventId,
2513 motionEntry->deviceId, motionEntry->source,
2514 motionEntry->displayId, std::move(hmac),
2515 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002516 motionEntry->actionButton,
2517 dispatchEntry->resolvedFlags,
2518 motionEntry->edgeFlags, motionEntry->metaState,
2519 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002520 motionEntry->classification, xScale, yScale,
2521 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002522 motionEntry->yPrecision,
2523 motionEntry->xCursorPosition,
2524 motionEntry->yCursorPosition,
2525 motionEntry->downTime, motionEntry->eventTime,
2526 motionEntry->pointerCount,
2527 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002528 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002529 break;
2530 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002531 case EventEntry::Type::FOCUS: {
2532 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2533 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002534 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002535 focusEntry->hasFocus,
2536 mInTouchMode);
2537 break;
2538 }
2539
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002540 case EventEntry::Type::CONFIGURATION_CHANGED:
2541 case EventEntry::Type::DEVICE_RESET: {
2542 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2543 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002544 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 }
2547
2548 // Check the result.
2549 if (status) {
2550 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002551 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002553 "This is unexpected because the wait queue is empty, so the pipe "
2554 "should be empty and we shouldn't have any problems writing an "
2555 "event to it, status=%d",
2556 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2558 } else {
2559 // Pipe is full and we are waiting for the app to finish process some events
2560 // before sending more events to it.
2561#if DEBUG_DISPATCH_CYCLE
2562 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002563 "waiting for the application to catch up",
2564 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565#endif
2566 connection->inputPublisherBlocked = true;
2567 }
2568 } else {
2569 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002570 "status=%d",
2571 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2573 }
2574 return;
2575 }
2576
2577 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002578 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2579 connection->outboundQueue.end(),
2580 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002581 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002582 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002583 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 }
2585}
2586
2587void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002588 const sp<Connection>& connection, uint32_t seq,
2589 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002590#if DEBUG_DISPATCH_CYCLE
2591 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002592 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593#endif
2594
2595 connection->inputPublisherBlocked = false;
2596
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002597 if (connection->status == Connection::STATUS_BROKEN ||
2598 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 return;
2600 }
2601
2602 // Notify other system components and prepare to start the next dispatch cycle.
2603 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2604}
2605
2606void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002607 const sp<Connection>& connection,
2608 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609#if DEBUG_DISPATCH_CYCLE
2610 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002611 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612#endif
2613
2614 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002615 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002616 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002617 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002618 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619
2620 // The connection appears to be unrecoverably broken.
2621 // Ignore already broken or zombie connections.
2622 if (connection->status == Connection::STATUS_NORMAL) {
2623 connection->status = Connection::STATUS_BROKEN;
2624
2625 if (notify) {
2626 // Notify other system components.
2627 onDispatchCycleBrokenLocked(currentTime, connection);
2628 }
2629 }
2630}
2631
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002632void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2633 while (!queue.empty()) {
2634 DispatchEntry* dispatchEntry = queue.front();
2635 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002636 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 }
2638}
2639
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002640void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002642 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 }
2644 delete dispatchEntry;
2645}
2646
2647int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2648 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2649
2650 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002651 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002653 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002655 "fd=%d, events=0x%x",
2656 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 return 0; // remove the callback
2658 }
2659
2660 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002661 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2663 if (!(events & ALOOPER_EVENT_INPUT)) {
2664 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002665 "events=0x%x",
2666 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667 return 1;
2668 }
2669
2670 nsecs_t currentTime = now();
2671 bool gotOne = false;
2672 status_t status;
2673 for (;;) {
2674 uint32_t seq;
2675 bool handled;
2676 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2677 if (status) {
2678 break;
2679 }
2680 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2681 gotOne = true;
2682 }
2683 if (gotOne) {
2684 d->runCommandsLockedInterruptible();
2685 if (status == WOULD_BLOCK) {
2686 return 1;
2687 }
2688 }
2689
2690 notify = status != DEAD_OBJECT || !connection->monitor;
2691 if (notify) {
2692 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002693 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 }
2695 } else {
2696 // Monitor channels are never explicitly unregistered.
2697 // We do it automatically when the remote endpoint is closed so don't warn
2698 // about them.
2699 notify = !connection->monitor;
2700 if (notify) {
2701 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002702 "events=0x%x",
2703 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704 }
2705 }
2706
2707 // Unregister the channel.
2708 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2709 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002710 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711}
2712
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002713void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002715 for (const auto& pair : mConnectionsByFd) {
2716 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717 }
2718}
2719
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002720void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002721 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002722 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2723 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2724}
2725
2726void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2727 const CancelationOptions& options,
2728 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2729 for (const auto& it : monitorsByDisplay) {
2730 const std::vector<Monitor>& monitors = it.second;
2731 for (const Monitor& monitor : monitors) {
2732 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002733 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002734 }
2735}
2736
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2738 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002739 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002740 if (connection == nullptr) {
2741 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002743
2744 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745}
2746
2747void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2748 const sp<Connection>& connection, const CancelationOptions& options) {
2749 if (connection->status == Connection::STATUS_BROKEN) {
2750 return;
2751 }
2752
2753 nsecs_t currentTime = now();
2754
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002755 std::vector<EventEntry*> cancelationEvents =
2756 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002758 if (cancelationEvents.empty()) {
2759 return;
2760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002762 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2763 "with reality: %s, mode=%d.",
2764 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2765 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002767
2768 InputTarget target;
2769 sp<InputWindowHandle> windowHandle =
2770 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2771 if (windowHandle != nullptr) {
2772 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2773 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2774 windowInfo->windowXScale, windowInfo->windowYScale);
2775 target.globalScaleFactor = windowInfo->globalScaleFactor;
2776 }
2777 target.inputChannel = connection->inputChannel;
2778 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2779
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002780 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2781 EventEntry* cancelationEventEntry = cancelationEvents[i];
2782 switch (cancelationEventEntry->type) {
2783 case EventEntry::Type::KEY: {
2784 logOutboundKeyDetails("cancel - ",
2785 static_cast<const KeyEntry&>(*cancelationEventEntry));
2786 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002788 case EventEntry::Type::MOTION: {
2789 logOutboundMotionDetails("cancel - ",
2790 static_cast<const MotionEntry&>(*cancelationEventEntry));
2791 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002793 case EventEntry::Type::FOCUS: {
2794 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2795 break;
2796 }
2797 case EventEntry::Type::CONFIGURATION_CHANGED:
2798 case EventEntry::Type::DEVICE_RESET: {
2799 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2800 EventEntry::typeToString(cancelationEventEntry->type));
2801 break;
2802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803 }
2804
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002805 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2806 target, InputTarget::FLAG_DISPATCH_AS_IS);
2807
2808 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002810
2811 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812}
2813
Svet Ganov5d3bc372020-01-26 23:11:07 -08002814void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2815 const sp<Connection>& connection) {
2816 if (connection->status == Connection::STATUS_BROKEN) {
2817 return;
2818 }
2819
2820 nsecs_t currentTime = now();
2821
2822 std::vector<EventEntry*> downEvents =
2823 connection->inputState.synthesizePointerDownEvents(currentTime);
2824
2825 if (downEvents.empty()) {
2826 return;
2827 }
2828
2829#if DEBUG_OUTBOUND_EVENT_DETAILS
2830 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2831 connection->getInputChannelName().c_str(), downEvents.size());
2832#endif
2833
2834 InputTarget target;
2835 sp<InputWindowHandle> windowHandle =
2836 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2837 if (windowHandle != nullptr) {
2838 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2839 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2840 windowInfo->windowXScale, windowInfo->windowYScale);
2841 target.globalScaleFactor = windowInfo->globalScaleFactor;
2842 }
2843 target.inputChannel = connection->inputChannel;
2844 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2845
2846 for (EventEntry* downEventEntry : downEvents) {
2847 switch (downEventEntry->type) {
2848 case EventEntry::Type::MOTION: {
2849 logOutboundMotionDetails("down - ",
2850 static_cast<const MotionEntry&>(*downEventEntry));
2851 break;
2852 }
2853
2854 case EventEntry::Type::KEY:
2855 case EventEntry::Type::FOCUS:
2856 case EventEntry::Type::CONFIGURATION_CHANGED:
2857 case EventEntry::Type::DEVICE_RESET: {
2858 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2859 EventEntry::typeToString(downEventEntry->type));
2860 break;
2861 }
2862 }
2863
2864 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2865 target, InputTarget::FLAG_DISPATCH_AS_IS);
2866
2867 downEventEntry->release();
2868 }
2869
2870 startDispatchCycleLocked(currentTime, connection);
2871}
2872
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002873MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002874 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 ALOG_ASSERT(pointerIds.value != 0);
2876
2877 uint32_t splitPointerIndexMap[MAX_POINTERS];
2878 PointerProperties splitPointerProperties[MAX_POINTERS];
2879 PointerCoords splitPointerCoords[MAX_POINTERS];
2880
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002881 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882 uint32_t splitPointerCount = 0;
2883
2884 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002885 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002887 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888 uint32_t pointerId = uint32_t(pointerProperties.id);
2889 if (pointerIds.hasBit(pointerId)) {
2890 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2891 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2892 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002893 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894 splitPointerCount += 1;
2895 }
2896 }
2897
2898 if (splitPointerCount != pointerIds.count()) {
2899 // This is bad. We are missing some of the pointers that we expected to deliver.
2900 // Most likely this indicates that we received an ACTION_MOVE events that has
2901 // different pointer ids than we expected based on the previous ACTION_DOWN
2902 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2903 // in this way.
2904 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002905 "we expected there to be %d pointers. This probably means we received "
2906 "a broken sequence of pointer ids from the input device.",
2907 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002908 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002909 }
2910
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002911 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2914 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2916 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002917 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918 uint32_t pointerId = uint32_t(pointerProperties.id);
2919 if (pointerIds.hasBit(pointerId)) {
2920 if (pointerIds.count() == 1) {
2921 // The first/last pointer went down/up.
2922 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002923 ? AMOTION_EVENT_ACTION_DOWN
2924 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 } else {
2926 // A secondary pointer went down/up.
2927 uint32_t splitPointerIndex = 0;
2928 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2929 splitPointerIndex += 1;
2930 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002931 action = maskedAction |
2932 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 }
2934 } else {
2935 // An unrelated pointer changed.
2936 action = AMOTION_EVENT_ACTION_MOVE;
2937 }
2938 }
2939
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002940 int32_t newId = mIdGenerator.nextId();
2941 if (ATRACE_ENABLED()) {
2942 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
2943 ") to MotionEvent(id=0x%" PRIx32 ").",
2944 originalMotionEntry.id, newId);
2945 ATRACE_NAME(message.c_str());
2946 }
Garfield Tan00f511d2019-06-12 16:55:40 -07002947 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002948 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
2949 originalMotionEntry.source, originalMotionEntry.displayId,
2950 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002951 originalMotionEntry.actionButton, originalMotionEntry.flags,
2952 originalMotionEntry.metaState, originalMotionEntry.buttonState,
2953 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
2954 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
2955 originalMotionEntry.xCursorPosition,
2956 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07002957 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002959 if (originalMotionEntry.injectionState) {
2960 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961 splitMotionEntry->injectionState->refCount += 1;
2962 }
2963
2964 return splitMotionEntry;
2965}
2966
2967void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2968#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002969 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970#endif
2971
2972 bool needWake;
2973 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002974 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002975
Prabir Pradhan42611e02018-11-27 14:04:02 -08002976 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002977 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002978 needWake = enqueueInboundEventLocked(newEntry);
2979 } // release lock
2980
2981 if (needWake) {
2982 mLooper->wake();
2983 }
2984}
2985
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002986/**
2987 * If one of the meta shortcuts is detected, process them here:
2988 * Meta + Backspace -> generate BACK
2989 * Meta + Enter -> generate HOME
2990 * This will potentially overwrite keyCode and metaState.
2991 */
2992void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002993 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002994 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2995 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2996 if (keyCode == AKEYCODE_DEL) {
2997 newKeyCode = AKEYCODE_BACK;
2998 } else if (keyCode == AKEYCODE_ENTER) {
2999 newKeyCode = AKEYCODE_HOME;
3000 }
3001 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003002 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003003 struct KeyReplacement replacement = {keyCode, deviceId};
3004 mReplacedKeys.add(replacement, newKeyCode);
3005 keyCode = newKeyCode;
3006 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3007 }
3008 } else if (action == AKEY_EVENT_ACTION_UP) {
3009 // In order to maintain a consistent stream of up and down events, check to see if the key
3010 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3011 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003012 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003013 struct KeyReplacement replacement = {keyCode, deviceId};
3014 ssize_t index = mReplacedKeys.indexOfKey(replacement);
3015 if (index >= 0) {
3016 keyCode = mReplacedKeys.valueAt(index);
3017 mReplacedKeys.removeItemsAt(index);
3018 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3019 }
3020 }
3021}
3022
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3024#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003025 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3026 "policyFlags=0x%x, action=0x%x, "
3027 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3028 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3029 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3030 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031#endif
3032 if (!validateKeyEvent(args->action)) {
3033 return;
3034 }
3035
3036 uint32_t policyFlags = args->policyFlags;
3037 int32_t flags = args->flags;
3038 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003039 // InputDispatcher tracks and generates key repeats on behalf of
3040 // whatever notifies it, so repeatCount should always be set to 0
3041 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3043 policyFlags |= POLICY_FLAG_VIRTUAL;
3044 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046 if (policyFlags & POLICY_FLAG_FUNCTION) {
3047 metaState |= AMETA_FUNCTION_ON;
3048 }
3049
3050 policyFlags |= POLICY_FLAG_TRUSTED;
3051
Michael Wright78f24442014-08-06 15:55:28 -07003052 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003053 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003054
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003056 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003057 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3058 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059
Michael Wright2b3c3302018-03-02 17:19:13 +00003060 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003061 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003062 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3063 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003064 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003065 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067 bool needWake;
3068 { // acquire lock
3069 mLock.lock();
3070
3071 if (shouldSendKeyToInputFilterLocked(args)) {
3072 mLock.unlock();
3073
3074 policyFlags |= POLICY_FLAG_FILTERED;
3075 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3076 return; // event was consumed by the filter
3077 }
3078
3079 mLock.lock();
3080 }
3081
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003082 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003083 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003084 args->displayId, policyFlags, args->action, flags, keyCode,
3085 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086
3087 needWake = enqueueInboundEventLocked(newEntry);
3088 mLock.unlock();
3089 } // release lock
3090
3091 if (needWake) {
3092 mLooper->wake();
3093 }
3094}
3095
3096bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3097 return mInputFilterEnabled;
3098}
3099
3100void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3101#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003102 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3103 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003104 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3105 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003106 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003107 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3108 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3109 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3110 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111 for (uint32_t i = 0; i < args->pointerCount; i++) {
3112 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003113 "x=%f, y=%f, pressure=%f, size=%f, "
3114 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3115 "orientation=%f",
3116 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3117 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3118 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3119 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3120 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3121 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3122 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3123 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3124 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3125 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126 }
3127#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003128 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3129 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 return;
3131 }
3132
3133 uint32_t policyFlags = args->policyFlags;
3134 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003135
3136 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003137 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003138 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3139 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003140 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142
3143 bool needWake;
3144 { // acquire lock
3145 mLock.lock();
3146
3147 if (shouldSendMotionToInputFilterLocked(args)) {
3148 mLock.unlock();
3149
3150 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003151 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3152 args->action, args->actionButton, args->flags, args->edgeFlags,
3153 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3154 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3155 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3156 args->downTime, args->eventTime, args->pointerCount,
3157 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158
3159 policyFlags |= POLICY_FLAG_FILTERED;
3160 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3161 return; // event was consumed by the filter
3162 }
3163
3164 mLock.lock();
3165 }
3166
3167 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003168 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003169 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003170 args->displayId, policyFlags, args->action, args->actionButton,
3171 args->flags, args->metaState, args->buttonState,
3172 args->classification, args->edgeFlags, args->xPrecision,
3173 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3174 args->downTime, args->pointerCount, args->pointerProperties,
3175 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176
3177 needWake = enqueueInboundEventLocked(newEntry);
3178 mLock.unlock();
3179 } // release lock
3180
3181 if (needWake) {
3182 mLooper->wake();
3183 }
3184}
3185
3186bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003187 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188}
3189
3190void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3191#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003192 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 "switchMask=0x%08x",
3194 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195#endif
3196
3197 uint32_t policyFlags = args->policyFlags;
3198 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003199 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200}
3201
3202void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3203#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003204 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3205 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206#endif
3207
3208 bool needWake;
3209 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003210 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211
Prabir Pradhan42611e02018-11-27 14:04:02 -08003212 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003213 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 needWake = enqueueInboundEventLocked(newEntry);
3215 } // release lock
3216
3217 if (needWake) {
3218 mLooper->wake();
3219 }
3220}
3221
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3223 int32_t injectorUid, int32_t syncMode,
3224 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225#if DEBUG_INBOUND_EVENT_DETAILS
3226 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003227 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
3228 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229#endif
3230
3231 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
3232
3233 policyFlags |= POLICY_FLAG_INJECTED;
3234 if (hasInjectionPermission(injectorPid, injectorUid)) {
3235 policyFlags |= POLICY_FLAG_TRUSTED;
3236 }
3237
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003238 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003240 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003241 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3242 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 if (!validateKeyEvent(action)) {
3244 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003245 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003247 int32_t flags = incomingKey.getFlags();
3248 int32_t keyCode = incomingKey.getKeyCode();
3249 int32_t metaState = incomingKey.getMetaState();
3250 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003251 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003252 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003253 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003254 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3255 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3256 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003258 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3259 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003260 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003261
3262 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3263 android::base::Timer t;
3264 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3265 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3266 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3267 std::to_string(t.duration().count()).c_str());
3268 }
3269 }
3270
3271 mLock.lock();
3272 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003273 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3274 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
3275 incomingKey.getDisplayId(), policyFlags, action, flags,
3276 incomingKey.getKeyCode(), incomingKey.getScanCode(),
3277 incomingKey.getMetaState(), incomingKey.getRepeatCount(),
3278 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003279 injectedEntries.push(injectedEntry);
3280 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 }
3282
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003283 case AINPUT_EVENT_TYPE_MOTION: {
3284 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3285 int32_t action = motionEvent->getAction();
3286 size_t pointerCount = motionEvent->getPointerCount();
3287 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3288 int32_t actionButton = motionEvent->getActionButton();
3289 int32_t displayId = motionEvent->getDisplayId();
3290 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3291 return INPUT_EVENT_INJECTION_FAILED;
3292 }
3293
3294 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3295 nsecs_t eventTime = motionEvent->getEventTime();
3296 android::base::Timer t;
3297 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3298 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3299 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3300 std::to_string(t.duration().count()).c_str());
3301 }
3302 }
3303
3304 mLock.lock();
3305 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3306 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3307 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003308 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3309 motionEvent->getSource(), motionEvent->getDisplayId(),
3310 policyFlags, action, actionButton, motionEvent->getFlags(),
3311 motionEvent->getMetaState(), motionEvent->getButtonState(),
3312 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3313 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003314 motionEvent->getRawXCursorPosition(),
3315 motionEvent->getRawYCursorPosition(),
3316 motionEvent->getDownTime(), uint32_t(pointerCount),
3317 pointerProperties, samplePointerCoords,
3318 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003319 injectedEntries.push(injectedEntry);
3320 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3321 sampleEventTimes += 1;
3322 samplePointerCoords += pointerCount;
3323 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003324 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003325 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003326 motionEvent->getDisplayId(), policyFlags, action,
3327 actionButton, motionEvent->getFlags(),
3328 motionEvent->getMetaState(), motionEvent->getButtonState(),
3329 motionEvent->getClassification(),
3330 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3331 motionEvent->getYPrecision(),
3332 motionEvent->getRawXCursorPosition(),
3333 motionEvent->getRawYCursorPosition(),
3334 motionEvent->getDownTime(), uint32_t(pointerCount),
3335 pointerProperties, samplePointerCoords,
3336 motionEvent->getXOffset(), motionEvent->getYOffset());
3337 injectedEntries.push(nextInjectedEntry);
3338 }
3339 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003342 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003343 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003344 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345 }
3346
3347 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3348 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3349 injectionState->injectionIsAsync = true;
3350 }
3351
3352 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003353 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354
3355 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003356 while (!injectedEntries.empty()) {
3357 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3358 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359 }
3360
3361 mLock.unlock();
3362
3363 if (needWake) {
3364 mLooper->wake();
3365 }
3366
3367 int32_t injectionResult;
3368 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003369 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370
3371 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3372 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3373 } else {
3374 for (;;) {
3375 injectionResult = injectionState->injectionResult;
3376 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3377 break;
3378 }
3379
3380 nsecs_t remainingTimeout = endTime - now();
3381 if (remainingTimeout <= 0) {
3382#if DEBUG_INJECTION
3383 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003384 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385#endif
3386 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3387 break;
3388 }
3389
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003390 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 }
3392
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003393 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3394 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 while (injectionState->pendingForegroundDispatches != 0) {
3396#if DEBUG_INJECTION
3397 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003398 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399#endif
3400 nsecs_t remainingTimeout = endTime - now();
3401 if (remainingTimeout <= 0) {
3402#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003403 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3404 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405#endif
3406 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3407 break;
3408 }
3409
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003410 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 }
3412 }
3413 }
3414
3415 injectionState->release();
3416 } // release lock
3417
3418#if DEBUG_INJECTION
3419 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003420 "injectorPid=%d, injectorUid=%d",
3421 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422#endif
3423
3424 return injectionResult;
3425}
3426
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003427std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003428 std::array<uint8_t, 32> calculatedHmac;
3429 std::unique_ptr<VerifiedInputEvent> result;
3430 switch (event.getType()) {
3431 case AINPUT_EVENT_TYPE_KEY: {
3432 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3433 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3434 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3435 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3436 break;
3437 }
3438 case AINPUT_EVENT_TYPE_MOTION: {
3439 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3440 VerifiedMotionEvent verifiedMotionEvent =
3441 verifiedMotionEventFromMotionEvent(motionEvent);
3442 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3443 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3444 break;
3445 }
3446 default: {
3447 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3448 return nullptr;
3449 }
3450 }
3451 if (calculatedHmac == INVALID_HMAC) {
3452 return nullptr;
3453 }
3454 if (calculatedHmac != event.getHmac()) {
3455 return nullptr;
3456 }
3457 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003458}
3459
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003461 return injectorUid == 0 ||
3462 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463}
3464
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003465void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466 InjectionState* injectionState = entry->injectionState;
3467 if (injectionState) {
3468#if DEBUG_INJECTION
3469 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003470 "injectorPid=%d, injectorUid=%d",
3471 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472#endif
3473
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003474 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 // Log the outcome since the injector did not wait for the injection result.
3476 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003477 case INPUT_EVENT_INJECTION_SUCCEEDED:
3478 ALOGV("Asynchronous input event injection succeeded.");
3479 break;
3480 case INPUT_EVENT_INJECTION_FAILED:
3481 ALOGW("Asynchronous input event injection failed.");
3482 break;
3483 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3484 ALOGW("Asynchronous input event injection permission denied.");
3485 break;
3486 case INPUT_EVENT_INJECTION_TIMED_OUT:
3487 ALOGW("Asynchronous input event injection timed out.");
3488 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489 }
3490 }
3491
3492 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003493 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494 }
3495}
3496
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003497void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498 InjectionState* injectionState = entry->injectionState;
3499 if (injectionState) {
3500 injectionState->pendingForegroundDispatches += 1;
3501 }
3502}
3503
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003504void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 InjectionState* injectionState = entry->injectionState;
3506 if (injectionState) {
3507 injectionState->pendingForegroundDispatches -= 1;
3508
3509 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003510 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 }
3512 }
3513}
3514
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003515std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3516 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003517 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003518}
3519
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003521 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003522 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003523 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3524 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003525 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003526 return windowHandle;
3527 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 }
3529 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003530 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531}
3532
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003533bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003534 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003535 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3536 for (const sp<InputWindowHandle>& handle : windowHandles) {
3537 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003538 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003539 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003540 ", but it should belong to display %" PRId32,
3541 windowHandle->getName().c_str(), it.first,
3542 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003543 }
3544 return true;
3545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546 }
3547 }
3548 return false;
3549}
3550
Robert Carr5c8a0262018-10-03 16:30:44 -07003551sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3552 size_t count = mInputChannelsByToken.count(token);
3553 if (count == 0) {
3554 return nullptr;
3555 }
3556 return mInputChannelsByToken.at(token);
3557}
3558
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003559void InputDispatcher::updateWindowHandlesForDisplayLocked(
3560 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3561 if (inputWindowHandles.empty()) {
3562 // Remove all handles on a display if there are no windows left.
3563 mWindowHandlesByDisplay.erase(displayId);
3564 return;
3565 }
3566
3567 // Since we compare the pointer of input window handles across window updates, we need
3568 // to make sure the handle object for the same window stays unchanged across updates.
3569 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003570 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003571 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003572 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003573 }
3574
3575 std::vector<sp<InputWindowHandle>> newHandles;
3576 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3577 if (!handle->updateInfo()) {
3578 // handle no longer valid
3579 continue;
3580 }
3581
3582 const InputWindowInfo* info = handle->getInfo();
3583 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3584 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3585 const bool noInputChannel =
3586 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3587 const bool canReceiveInput =
3588 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3589 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3590 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003591 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003592 handle->getName().c_str());
3593 }
3594 continue;
3595 }
3596
3597 if (info->displayId != displayId) {
3598 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3599 handle->getName().c_str(), displayId, info->displayId);
3600 continue;
3601 }
3602
chaviwaf87b3e2019-10-01 16:59:28 -07003603 if (oldHandlesById.find(handle->getId()) != oldHandlesById.end()) {
3604 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003605 oldHandle->updateFrom(handle);
3606 newHandles.push_back(oldHandle);
3607 } else {
3608 newHandles.push_back(handle);
3609 }
3610 }
3611
3612 // Insert or replace
3613 mWindowHandlesByDisplay[displayId] = newHandles;
3614}
3615
Arthur Hung72d8dc32020-03-28 00:48:39 +00003616void InputDispatcher::setInputWindows(
3617 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3618 { // acquire lock
3619 std::scoped_lock _l(mLock);
3620 for (auto const& i : handlesPerDisplay) {
3621 setInputWindowsLocked(i.second, i.first);
3622 }
3623 }
3624 // Wake up poll loop since it may need to make new input dispatching choices.
3625 mLooper->wake();
3626}
3627
Arthur Hungb92218b2018-08-14 12:00:21 +08003628/**
3629 * Called from InputManagerService, update window handle list by displayId that can receive input.
3630 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3631 * If set an empty list, remove all handles from the specific display.
3632 * For focused handle, check if need to change and send a cancel event to previous one.
3633 * For removed handle, check if need to send a cancel event if already in touch.
3634 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003635void InputDispatcher::setInputWindowsLocked(
3636 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003637 if (DEBUG_FOCUS) {
3638 std::string windowList;
3639 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3640 windowList += iwh->getName() + " ";
3641 }
3642 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644
Arthur Hung72d8dc32020-03-28 00:48:39 +00003645 // Copy old handles for release if they are no longer present.
3646 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647
Arthur Hung72d8dc32020-03-28 00:48:39 +00003648 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003649
Arthur Hung72d8dc32020-03-28 00:48:39 +00003650 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3651 bool foundHoveredWindow = false;
3652 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3653 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3654 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3655 windowHandle->getInfo()->visible) {
3656 newFocusedWindowHandle = windowHandle;
3657 }
3658 if (windowHandle == mLastHoverWindowHandle) {
3659 foundHoveredWindow = true;
3660 }
3661 }
3662
3663 if (!foundHoveredWindow) {
3664 mLastHoverWindowHandle = nullptr;
3665 }
3666
3667 sp<InputWindowHandle> oldFocusedWindowHandle =
3668 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3669
3670 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3671 if (oldFocusedWindowHandle != nullptr) {
3672 if (DEBUG_FOCUS) {
3673 ALOGD("Focus left window: %s in display %" PRId32,
3674 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003675 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003676 sp<InputChannel> focusedInputChannel =
3677 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3678 if (focusedInputChannel != nullptr) {
3679 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3680 "focus left window");
3681 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3682 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003683 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003684 mFocusedWindowHandlesByDisplay.erase(displayId);
3685 }
3686 if (newFocusedWindowHandle != nullptr) {
3687 if (DEBUG_FOCUS) {
3688 ALOGD("Focus entered window: %s in display %" PRId32,
3689 newFocusedWindowHandle->getName().c_str(), displayId);
3690 }
3691 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3692 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 }
3694
Arthur Hung72d8dc32020-03-28 00:48:39 +00003695 if (mFocusedDisplayId == displayId) {
3696 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699
Arthur Hung72d8dc32020-03-28 00:48:39 +00003700 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3701 if (stateIndex >= 0) {
3702 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
3703 for (size_t i = 0; i < state.windows.size();) {
3704 TouchedWindow& touchedWindow = state.windows[i];
3705 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003706 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003707 ALOGD("Touched window was removed: %s in display %" PRId32,
3708 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003709 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003710 sp<InputChannel> touchedInputChannel =
3711 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3712 if (touchedInputChannel != nullptr) {
3713 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3714 "touched window was removed");
3715 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003717 state.windows.erase(state.windows.begin() + i);
3718 } else {
3719 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720 }
3721 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003722 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003723
Arthur Hung72d8dc32020-03-28 00:48:39 +00003724 // Release information for windows that are no longer present.
3725 // This ensures that unused input channels are released promptly.
3726 // Otherwise, they might stick around until the window handle is destroyed
3727 // which might not happen until the next GC.
3728 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
3729 if (!hasWindowHandleLocked(oldWindowHandle)) {
3730 if (DEBUG_FOCUS) {
3731 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003732 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003733 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003734 }
chaviw291d88a2019-02-14 10:33:58 -08003735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736}
3737
3738void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003739 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003740 if (DEBUG_FOCUS) {
3741 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3742 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003745 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746
Tiger Huang721e26f2018-07-24 22:26:19 +08003747 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3748 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003749 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003750 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3751 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003754 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003756 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003758 oldFocusedApplicationHandle.clear();
3759 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761 } // release lock
3762
3763 // Wake up poll loop since it may need to make new input dispatching choices.
3764 mLooper->wake();
3765}
3766
Tiger Huang721e26f2018-07-24 22:26:19 +08003767/**
3768 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3769 * the display not specified.
3770 *
3771 * We track any unreleased events for each window. If a window loses the ability to receive the
3772 * released event, we will send a cancel event to it. So when the focused display is changed, we
3773 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3774 * display. The display-specified events won't be affected.
3775 */
3776void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003777 if (DEBUG_FOCUS) {
3778 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3779 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003780 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003781 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003782
3783 if (mFocusedDisplayId != displayId) {
3784 sp<InputWindowHandle> oldFocusedWindowHandle =
3785 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3786 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003787 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003788 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003789 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003790 CancelationOptions
3791 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3792 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003793 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003794 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3795 }
3796 }
3797 mFocusedDisplayId = displayId;
3798
3799 // Sanity check
3800 sp<InputWindowHandle> newFocusedWindowHandle =
3801 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003802 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003803
Tiger Huang721e26f2018-07-24 22:26:19 +08003804 if (newFocusedWindowHandle == nullptr) {
3805 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3806 if (!mFocusedWindowHandlesByDisplay.empty()) {
3807 ALOGE("But another display has a focused window:");
3808 for (auto& it : mFocusedWindowHandlesByDisplay) {
3809 const int32_t displayId = it.first;
3810 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003811 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3812 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003813 }
3814 }
3815 }
3816 }
3817
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003818 if (DEBUG_FOCUS) {
3819 logDispatchStateLocked();
3820 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003821 } // release lock
3822
3823 // Wake up poll loop since it may need to make new input dispatching choices.
3824 mLooper->wake();
3825}
3826
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003828 if (DEBUG_FOCUS) {
3829 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831
3832 bool changed;
3833 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003834 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835
3836 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3837 if (mDispatchFrozen && !frozen) {
3838 resetANRTimeoutsLocked();
3839 }
3840
3841 if (mDispatchEnabled && !enabled) {
3842 resetAndDropEverythingLocked("dispatcher is being disabled");
3843 }
3844
3845 mDispatchEnabled = enabled;
3846 mDispatchFrozen = frozen;
3847 changed = true;
3848 } else {
3849 changed = false;
3850 }
3851
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003852 if (DEBUG_FOCUS) {
3853 logDispatchStateLocked();
3854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 } // release lock
3856
3857 if (changed) {
3858 // Wake up poll loop since it may need to make new input dispatching choices.
3859 mLooper->wake();
3860 }
3861}
3862
3863void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003864 if (DEBUG_FOCUS) {
3865 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867
3868 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003869 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870
3871 if (mInputFilterEnabled == enabled) {
3872 return;
3873 }
3874
3875 mInputFilterEnabled = enabled;
3876 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3877 } // release lock
3878
3879 // Wake up poll loop since there might be work to do to drop everything.
3880 mLooper->wake();
3881}
3882
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003883void InputDispatcher::setInTouchMode(bool inTouchMode) {
3884 std::scoped_lock lock(mLock);
3885 mInTouchMode = inTouchMode;
3886}
3887
chaviwfbe5d9c2018-12-26 12:23:37 -08003888bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3889 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003890 if (DEBUG_FOCUS) {
3891 ALOGD("Trivial transfer to same window.");
3892 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003893 return true;
3894 }
3895
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003897 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898
chaviwfbe5d9c2018-12-26 12:23:37 -08003899 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3900 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003901 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003902 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 return false;
3904 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003905 if (DEBUG_FOCUS) {
3906 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3907 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003910 if (DEBUG_FOCUS) {
3911 ALOGD("Cannot transfer focus because windows are on different displays.");
3912 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913 return false;
3914 }
3915
3916 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003917 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3918 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3919 for (size_t i = 0; i < state.windows.size(); i++) {
3920 const TouchedWindow& touchedWindow = state.windows[i];
3921 if (touchedWindow.windowHandle == fromWindowHandle) {
3922 int32_t oldTargetFlags = touchedWindow.targetFlags;
3923 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003925 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003927 int32_t newTargetFlags = oldTargetFlags &
3928 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3929 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003930 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931
Jeff Brownf086ddb2014-02-11 14:28:48 -08003932 found = true;
3933 goto Found;
3934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 }
3936 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003937 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003939 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003940 if (DEBUG_FOCUS) {
3941 ALOGD("Focus transfer failed because from window did not have focus.");
3942 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 return false;
3944 }
3945
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07003946 sp<Connection> fromConnection = getConnectionLocked(fromToken);
3947 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003948 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003949 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003950 CancelationOptions
3951 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3952 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003954 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955 }
3956
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003957 if (DEBUG_FOCUS) {
3958 logDispatchStateLocked();
3959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960 } // release lock
3961
3962 // Wake up poll loop since it may need to make new input dispatching choices.
3963 mLooper->wake();
3964 return true;
3965}
3966
3967void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003968 if (DEBUG_FOCUS) {
3969 ALOGD("Resetting and dropping all events (%s).", reason);
3970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971
3972 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3973 synthesizeCancelationEventsForAllConnectionsLocked(options);
3974
3975 resetKeyRepeatLocked();
3976 releasePendingEventLocked();
3977 drainInboundQueueLocked();
3978 resetANRTimeoutsLocked();
3979
Jeff Brownf086ddb2014-02-11 14:28:48 -08003980 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003982 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983}
3984
3985void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003986 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987 dumpDispatchStateLocked(dump);
3988
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003989 std::istringstream stream(dump);
3990 std::string line;
3991
3992 while (std::getline(stream, line, '\n')) {
3993 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 }
3995}
3996
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003997void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003998 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3999 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4000 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004001 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002
Tiger Huang721e26f2018-07-24 22:26:19 +08004003 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4004 dump += StringPrintf(INDENT "FocusedApplications:\n");
4005 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4006 const int32_t displayId = it.first;
4007 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004008 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4009 ", name='%s', dispatchingTimeout=%0.3fms\n",
4010 displayId, applicationHandle->getName().c_str(),
4011 applicationHandle->getDispatchingTimeout(
4012 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
4013 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08004014 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004016 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004018
4019 if (!mFocusedWindowHandlesByDisplay.empty()) {
4020 dump += StringPrintf(INDENT "FocusedWindows:\n");
4021 for (auto& it : mFocusedWindowHandlesByDisplay) {
4022 const int32_t displayId = it.first;
4023 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004024 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4025 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004026 }
4027 } else {
4028 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030
Jeff Brownf086ddb2014-02-11 14:28:48 -08004031 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004032 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08004033 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
4034 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004035 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004036 state.displayId, toString(state.down), toString(state.split),
4037 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004038 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004039 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004040 for (size_t i = 0; i < state.windows.size(); i++) {
4041 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004042 dump += StringPrintf(INDENT4
4043 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4044 i, touchedWindow.windowHandle->getName().c_str(),
4045 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004046 }
4047 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004048 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004049 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004050 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004051 dump += INDENT3 "Portal windows:\n";
4052 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004053 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004054 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4055 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004056 }
4057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 }
4059 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004060 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061 }
4062
Arthur Hungb92218b2018-08-14 12:00:21 +08004063 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004064 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004065 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004066 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004067 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004068 dump += INDENT2 "Windows:\n";
4069 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004070 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004071 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072
Arthur Hungb92218b2018-08-14 12:00:21 +08004073 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004074 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004075 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4076 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004077 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004078 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004079 i, windowInfo->name.c_str(), windowInfo->displayId,
4080 windowInfo->portalToDisplayId,
4081 toString(windowInfo->paused),
4082 toString(windowInfo->hasFocus),
4083 toString(windowInfo->hasWallpaper),
4084 toString(windowInfo->visible),
4085 toString(windowInfo->canReceiveKeys),
4086 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004087 windowInfo->layoutParamsType, windowInfo->frameLeft,
4088 windowInfo->frameTop, windowInfo->frameRight,
4089 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4090 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004091 dumpRegion(dump, windowInfo->touchableRegion);
4092 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
4093 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004094 windowInfo->ownerPid, windowInfo->ownerUid,
4095 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08004096 }
4097 } else {
4098 dump += INDENT2 "Windows: <none>\n";
4099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 }
4101 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004102 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 }
4104
Michael Wright3dd60e22019-03-27 22:06:44 +00004105 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004106 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004107 const std::vector<Monitor>& monitors = it.second;
4108 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4109 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004110 }
4111 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004112 const std::vector<Monitor>& monitors = it.second;
4113 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4114 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004115 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004117 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 }
4119
4120 nsecs_t currentTime = now();
4121
4122 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004123 if (!mRecentQueue.empty()) {
4124 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4125 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004126 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004128 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 }
4130 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004131 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 }
4133
4134 // Dump event currently being dispatched.
4135 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004136 dump += INDENT "PendingEvent:\n";
4137 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004139 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004140 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004142 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143 }
4144
4145 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004146 if (!mInboundQueue.empty()) {
4147 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4148 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004149 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004151 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152 }
4153 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004154 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 }
4156
Michael Wright78f24442014-08-06 15:55:28 -07004157 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004158 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07004159 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
4160 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
4161 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004162 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
4163 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004164 }
4165 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004166 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004167 }
4168
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004169 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004170 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004171 for (const auto& pair : mConnectionsByFd) {
4172 const sp<Connection>& connection = pair.second;
4173 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
4174 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
4175 pair.first, connection->getInputChannelName().c_str(),
4176 connection->getWindowName().c_str(), connection->getStatusLabel(),
4177 toString(connection->monitor),
4178 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004180 if (!connection->outboundQueue.empty()) {
4181 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4182 connection->outboundQueue.size());
4183 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 dump.append(INDENT4);
4185 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004186 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004187 entry->targetFlags, entry->resolvedAction,
4188 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 }
4190 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004191 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 }
4193
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004194 if (!connection->waitQueue.empty()) {
4195 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4196 connection->waitQueue.size());
4197 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004198 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004200 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 "age=%0.1fms, wait=%0.1fms\n",
4202 entry->targetFlags, entry->resolvedAction,
4203 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
4204 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205 }
4206 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004207 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 }
4209 }
4210 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004211 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 }
4213
4214 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004215 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004216 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004218 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 }
4220
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004221 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004222 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004223 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225}
4226
Michael Wright3dd60e22019-03-27 22:06:44 +00004227void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4228 const size_t numMonitors = monitors.size();
4229 for (size_t i = 0; i < numMonitors; i++) {
4230 const Monitor& monitor = monitors[i];
4231 const sp<InputChannel>& channel = monitor.inputChannel;
4232 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4233 dump += "\n";
4234 }
4235}
4236
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004237status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004239 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240#endif
4241
4242 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004243 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004244 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004245 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004247 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 return BAD_VALUE;
4249 }
4250
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004251 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252
4253 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004254 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004255 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4258 } // release lock
4259
4260 // Wake the looper because some connections have changed.
4261 mLooper->wake();
4262 return OK;
4263}
4264
Michael Wright3dd60e22019-03-27 22:06:44 +00004265status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004266 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004267 { // acquire lock
4268 std::scoped_lock _l(mLock);
4269
4270 if (displayId < 0) {
4271 ALOGW("Attempted to register input monitor without a specified display.");
4272 return BAD_VALUE;
4273 }
4274
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004275 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004276 ALOGW("Attempted to register input monitor without an identifying token.");
4277 return BAD_VALUE;
4278 }
4279
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004280 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004281
4282 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004283 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004284 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004285
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004286 auto& monitorsByDisplay =
4287 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004288 monitorsByDisplay[displayId].emplace_back(inputChannel);
4289
4290 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004291 }
4292 // Wake the looper because some connections have changed.
4293 mLooper->wake();
4294 return OK;
4295}
4296
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4298#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004299 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300#endif
4301
4302 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004303 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304
4305 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4306 if (status) {
4307 return status;
4308 }
4309 } // release lock
4310
4311 // Wake the poll loop because removing the connection may have changed the current
4312 // synchronization state.
4313 mLooper->wake();
4314 return OK;
4315}
4316
4317status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004318 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004319 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004320 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004322 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 return BAD_VALUE;
4324 }
4325
John Recke0710582019-09-26 13:46:12 -07004326 [[maybe_unused]] const bool removed = removeByValue(mConnectionsByFd, connection);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004327 ALOG_ASSERT(removed);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004328 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004329
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 if (connection->monitor) {
4331 removeMonitorChannelLocked(inputChannel);
4332 }
4333
4334 mLooper->removeFd(inputChannel->getFd());
4335
4336 nsecs_t currentTime = now();
4337 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4338
4339 connection->status = Connection::STATUS_ZOMBIE;
4340 return OK;
4341}
4342
4343void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004344 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4345 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4346}
4347
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004348void InputDispatcher::removeMonitorChannelLocked(
4349 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004350 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004351 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004352 std::vector<Monitor>& monitors = it->second;
4353 const size_t numMonitors = monitors.size();
4354 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004355 if (monitors[i].inputChannel == inputChannel) {
4356 monitors.erase(monitors.begin() + i);
4357 break;
4358 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004359 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004360 if (monitors.empty()) {
4361 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004362 } else {
4363 ++it;
4364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 }
4366}
4367
Michael Wright3dd60e22019-03-27 22:06:44 +00004368status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4369 { // acquire lock
4370 std::scoped_lock _l(mLock);
4371 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4372
4373 if (!foundDisplayId) {
4374 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4375 return BAD_VALUE;
4376 }
4377 int32_t displayId = foundDisplayId.value();
4378
4379 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4380 if (stateIndex < 0) {
4381 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4382 return BAD_VALUE;
4383 }
4384
4385 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4386 std::optional<int32_t> foundDeviceId;
4387 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004388 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004389 foundDeviceId = state.deviceId;
4390 }
4391 }
4392 if (!foundDeviceId || !state.down) {
4393 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004394 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004395 return BAD_VALUE;
4396 }
4397 int32_t deviceId = foundDeviceId.value();
4398
4399 // Send cancel events to all the input channels we're stealing from.
4400 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004401 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004402 options.deviceId = deviceId;
4403 options.displayId = displayId;
4404 for (const TouchedWindow& window : state.windows) {
4405 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004406 if (channel != nullptr) {
4407 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4408 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004409 }
4410 // Then clear the current touch state so we stop dispatching to them as well.
4411 state.filterNonMonitors();
4412 }
4413 return OK;
4414}
4415
Michael Wright3dd60e22019-03-27 22:06:44 +00004416std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4417 const sp<IBinder>& token) {
4418 for (const auto& it : mGestureMonitorsByDisplay) {
4419 const std::vector<Monitor>& monitors = it.second;
4420 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004421 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004422 return it.first;
4423 }
4424 }
4425 }
4426 return std::nullopt;
4427}
4428
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004429sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) {
4430 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004431 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004432 }
4433
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004434 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004435 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004436 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004437 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438 }
4439 }
Robert Carr4e670e52018-08-15 13:26:12 -07004440
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004441 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004442}
4443
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004444void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4445 const sp<Connection>& connection, uint32_t seq,
4446 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004447 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4448 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 commandEntry->connection = connection;
4450 commandEntry->eventTime = currentTime;
4451 commandEntry->seq = seq;
4452 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004453 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454}
4455
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004456void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4457 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004459 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004461 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4462 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004464 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004465}
4466
chaviw0c06c6e2019-01-09 13:27:07 -08004467void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004468 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004469 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4470 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004471 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4472 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004473 commandEntry->oldToken = oldToken;
4474 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004475 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004476}
4477
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004478void InputDispatcher::onANRLocked(nsecs_t currentTime,
4479 const sp<InputApplicationHandle>& applicationHandle,
4480 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4481 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4483 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4484 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004485 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4486 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4487 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488
4489 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004490 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491 struct tm tm;
4492 localtime_r(&t, &tm);
4493 char timestr[64];
4494 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4495 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004496 mLastANRState += INDENT "ANR:\n";
4497 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004498 mLastANRState +=
4499 StringPrintf(INDENT2 "Window: %s\n",
4500 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004501 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4502 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4503 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504 dumpDispatchStateLocked(mLastANRState);
4505
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004506 std::unique_ptr<CommandEntry> commandEntry =
4507 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004509 commandEntry->inputChannel =
4510 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004512 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513}
4514
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004515void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004516 mLock.unlock();
4517
4518 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4519
4520 mLock.lock();
4521}
4522
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004523void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524 sp<Connection> connection = commandEntry->connection;
4525
4526 if (connection->status != Connection::STATUS_ZOMBIE) {
4527 mLock.unlock();
4528
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004529 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530
4531 mLock.lock();
4532 }
4533}
4534
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004535void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004536 sp<IBinder> oldToken = commandEntry->oldToken;
4537 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004538 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004539 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004540 mLock.lock();
4541}
4542
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004543void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004544 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004545 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 mLock.unlock();
4547
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004548 nsecs_t newTimeout =
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004549 mPolicy->notifyANR(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550
4551 mLock.lock();
4552
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004553 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554}
4555
4556void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4557 CommandEntry* commandEntry) {
4558 KeyEntry* entry = commandEntry->keyEntry;
4559
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004560 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561
4562 mLock.unlock();
4563
Michael Wright2b3c3302018-03-02 17:19:13 +00004564 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004565 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004566 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004567 : nullptr;
4568 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004569 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4570 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004571 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004572 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004573
4574 mLock.lock();
4575
4576 if (delay < 0) {
4577 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4578 } else if (!delay) {
4579 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4580 } else {
4581 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4582 entry->interceptKeyWakeupTime = now() + delay;
4583 }
4584 entry->release();
4585}
4586
chaviwfd6d3512019-03-25 13:23:49 -07004587void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4588 mLock.unlock();
4589 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4590 mLock.lock();
4591}
4592
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004593void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004595 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004597 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004598
4599 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004600 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004601 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004602 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004604 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004605
4606 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4607 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4608 std::string msg =
4609 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4610 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4611 dispatchEntry->eventEntry->appendDescription(msg);
4612 ALOGI("%s", msg.c_str());
4613 }
4614
4615 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004616 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004617 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4618 restartEvent =
4619 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004620 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004621 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4622 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4623 handled);
4624 } else {
4625 restartEvent = false;
4626 }
4627
4628 // Dequeue the event and start the next cycle.
4629 // Note that because the lock might have been released, it is possible that the
4630 // contents of the wait queue to have been drained, so we need to double-check
4631 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004632 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4633 if (dispatchEntryIt != connection->waitQueue.end()) {
4634 dispatchEntry = *dispatchEntryIt;
4635 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004636 traceWaitQueueLength(connection);
4637 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004638 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004639 traceOutboundQueueLength(connection);
4640 } else {
4641 releaseDispatchEntry(dispatchEntry);
4642 }
4643 }
4644
4645 // Start the next dispatch cycle for this connection.
4646 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647}
4648
4649bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004650 DispatchEntry* dispatchEntry,
4651 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004652 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004653 if (!handled) {
4654 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004655 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004656 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004657 return false;
4658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004660 // Get the fallback key state.
4661 // Clear it out after dispatching the UP.
4662 int32_t originalKeyCode = keyEntry->keyCode;
4663 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4664 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4665 connection->inputState.removeFallbackKey(originalKeyCode);
4666 }
4667
4668 if (handled || !dispatchEntry->hasForegroundTarget()) {
4669 // If the application handles the original key for which we previously
4670 // generated a fallback or if the window is not a foreground window,
4671 // then cancel the associated fallback key, if any.
4672 if (fallbackKeyCode != -1) {
4673 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004675 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004676 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4677 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4678 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004680 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004681 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682
4683 mLock.unlock();
4684
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004685 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004686 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687
4688 mLock.lock();
4689
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004690 // Cancel the fallback key.
4691 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004693 "application handled the original non-fallback key "
4694 "or is no longer a foreground target, "
4695 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 options.keyCode = fallbackKeyCode;
4697 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004699 connection->inputState.removeFallbackKey(originalKeyCode);
4700 }
4701 } else {
4702 // If the application did not handle a non-fallback key, first check
4703 // that we are in a good state to perform unhandled key event processing
4704 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004705 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004706 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004708 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004709 "since this is not an initial down. "
4710 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4711 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004713 return false;
4714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004716 // Dispatch the unhandled key to the policy.
4717#if DEBUG_OUTBOUND_EVENT_DETAILS
4718 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004719 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4720 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004721#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004722 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004723
4724 mLock.unlock();
4725
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004726 bool fallback =
4727 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4728 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004729
4730 mLock.lock();
4731
4732 if (connection->status != Connection::STATUS_NORMAL) {
4733 connection->inputState.removeFallbackKey(originalKeyCode);
4734 return false;
4735 }
4736
4737 // Latch the fallback keycode for this key on an initial down.
4738 // The fallback keycode cannot change at any other point in the lifecycle.
4739 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004741 fallbackKeyCode = event.getKeyCode();
4742 } else {
4743 fallbackKeyCode = AKEYCODE_UNKNOWN;
4744 }
4745 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4746 }
4747
4748 ALOG_ASSERT(fallbackKeyCode != -1);
4749
4750 // Cancel the fallback key if the policy decides not to send it anymore.
4751 // We will continue to dispatch the key to the policy but we will no
4752 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004753 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4754 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004755#if DEBUG_OUTBOUND_EVENT_DETAILS
4756 if (fallback) {
4757 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004758 "as a fallback for %d, but on the DOWN it had requested "
4759 "to send %d instead. Fallback canceled.",
4760 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004761 } else {
4762 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004763 "but on the DOWN it had requested to send %d. "
4764 "Fallback canceled.",
4765 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004766 }
4767#endif
4768
4769 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4770 "canceling fallback, policy no longer desires it");
4771 options.keyCode = fallbackKeyCode;
4772 synthesizeCancelationEventsForConnectionLocked(connection, options);
4773
4774 fallback = false;
4775 fallbackKeyCode = AKEYCODE_UNKNOWN;
4776 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004777 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004778 }
4779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780
4781#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004782 {
4783 std::string msg;
4784 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4785 connection->inputState.getFallbackKeys();
4786 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004787 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004789 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004790 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004791 }
4792#endif
4793
4794 if (fallback) {
4795 // Restart the dispatch cycle using the fallback key.
4796 keyEntry->eventTime = event.getEventTime();
4797 keyEntry->deviceId = event.getDeviceId();
4798 keyEntry->source = event.getSource();
4799 keyEntry->displayId = event.getDisplayId();
4800 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4801 keyEntry->keyCode = fallbackKeyCode;
4802 keyEntry->scanCode = event.getScanCode();
4803 keyEntry->metaState = event.getMetaState();
4804 keyEntry->repeatCount = event.getRepeatCount();
4805 keyEntry->downTime = event.getDownTime();
4806 keyEntry->syntheticRepeat = false;
4807
4808#if DEBUG_OUTBOUND_EVENT_DETAILS
4809 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004810 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4811 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004812#endif
4813 return true; // restart the event
4814 } else {
4815#if DEBUG_OUTBOUND_EVENT_DETAILS
4816 ALOGD("Unhandled key event: No fallback key.");
4817#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004818
4819 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004820 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821 }
4822 }
4823 return false;
4824}
4825
4826bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004827 DispatchEntry* dispatchEntry,
4828 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004829 return false;
4830}
4831
4832void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4833 mLock.unlock();
4834
4835 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4836
4837 mLock.lock();
4838}
4839
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004840KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4841 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004842 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004843 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
4844 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004845 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846}
4847
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004848void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004849 int32_t injectionResult,
4850 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 // TODO Write some statistics about how long we spend waiting.
4852}
4853
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05004854/**
4855 * Report the touch event latency to the statsd server.
4856 * Input events are reported for statistics if:
4857 * - This is a touchscreen event
4858 * - InputFilter is not enabled
4859 * - Event is not injected or synthesized
4860 *
4861 * Statistics should be reported before calling addValue, to prevent a fresh new sample
4862 * from getting aggregated with the "old" data.
4863 */
4864void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
4865 REQUIRES(mLock) {
4866 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
4867 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
4868 if (!reportForStatistics) {
4869 return;
4870 }
4871
4872 if (mTouchStatistics.shouldReport()) {
4873 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
4874 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
4875 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
4876 mTouchStatistics.reset();
4877 }
4878 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
4879 mTouchStatistics.addValue(latencyMicros);
4880}
4881
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882void InputDispatcher::traceInboundQueueLengthLocked() {
4883 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004884 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 }
4886}
4887
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004888void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 if (ATRACE_ENABLED()) {
4890 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004891 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004892 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893 }
4894}
4895
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004896void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 if (ATRACE_ENABLED()) {
4898 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004899 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004900 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901 }
4902}
4903
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004904void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004905 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004907 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908 dumpDispatchStateLocked(dump);
4909
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004910 if (!mLastANRState.empty()) {
4911 dump += "\nInput Dispatcher State at time of last ANR:\n";
4912 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913 }
4914}
4915
4916void InputDispatcher::monitor() {
4917 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004918 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004920 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921}
4922
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004923/**
4924 * Wake up the dispatcher and wait until it processes all events and commands.
4925 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
4926 * this method can be safely called from any thread, as long as you've ensured that
4927 * the work you are interested in completing has already been queued.
4928 */
4929bool InputDispatcher::waitForIdle() {
4930 /**
4931 * Timeout should represent the longest possible time that a device might spend processing
4932 * events and commands.
4933 */
4934 constexpr std::chrono::duration TIMEOUT = 100ms;
4935 std::unique_lock lock(mLock);
4936 mLooper->wake();
4937 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
4938 return result == std::cv_status::no_timeout;
4939}
4940
Garfield Tane84e6f92019-08-29 17:28:41 -07004941} // namespace android::inputdispatcher