blob: 443e2ca13120cc4db223090cacb1f363f9d86729 [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
Michael Wright2b3c3302018-03-02 17:19:13 +000048#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080049#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070050#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080051#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010052#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070053#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000054#include <log/log_event_list.h>
Gang Wang342c9272020-01-13 13:15:04 -050055#include <openssl/hmac.h>
56#include <openssl/rand.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070057#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010058#include <statslog.h>
59#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070060#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080061
Michael Wright44753b12020-07-08 13:48:11 +010062#include <cerrno>
63#include <cinttypes>
64#include <climits>
65#include <cstddef>
66#include <ctime>
67#include <queue>
68#include <sstream>
69
70#include "Connection.h"
71
Michael Wrightd02c5b62014-02-10 15:10:22 -080072#define INDENT " "
73#define INDENT2 " "
74#define INDENT3 " "
75#define INDENT4 " "
76
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080077using android::base::StringPrintf;
78
Garfield Tane84e6f92019-08-29 17:28:41 -070079namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080080
81// Default input dispatching timeout if there is no focused application or paused window
82// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070083constexpr std::chrono::nanoseconds DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5s;
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow for all pending events to be processed when an app switch
86// key is on the way. This is used to preempt input dispatch and drop input events
87// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000088constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for an event to be dispatched (measured since its eventTime)
91// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Michael Wrightd02c5b62014-02-10 15:10:22 -080094// 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 +000095constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
96
97// Log a warning when an interception call takes longer than this to process.
98constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700100// Additional key latency in case a connection is still processing some motion events.
101// This will help with the case when a user touched a button that opens a new window,
102// and gives us the chance to dispatch the key to this new window.
103constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
107
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000108// Event log tags. See EventLogTags.logtags for reference
109constexpr int LOGTAG_INPUT_INTERACTION = 62000;
110constexpr int LOGTAG_INPUT_FOCUS = 62001;
111
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112static inline nsecs_t now() {
113 return systemTime(SYSTEM_TIME_MONOTONIC);
114}
115
116static inline const char* toString(bool value) {
117 return value ? "true" : "false";
118}
119
120static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700121 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
122 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123}
124
125static bool isValidKeyAction(int32_t action) {
126 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700127 case AKEY_EVENT_ACTION_DOWN:
128 case AKEY_EVENT_ACTION_UP:
129 return true;
130 default:
131 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 }
133}
134
135static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700136 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137 ALOGE("Key event has invalid action code 0x%x", action);
138 return false;
139 }
140 return true;
141}
142
Michael Wright7b159c92015-05-14 14:48:03 +0100143static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700145 case AMOTION_EVENT_ACTION_DOWN:
146 case AMOTION_EVENT_ACTION_UP:
147 case AMOTION_EVENT_ACTION_CANCEL:
148 case AMOTION_EVENT_ACTION_MOVE:
149 case AMOTION_EVENT_ACTION_OUTSIDE:
150 case AMOTION_EVENT_ACTION_HOVER_ENTER:
151 case AMOTION_EVENT_ACTION_HOVER_MOVE:
152 case AMOTION_EVENT_ACTION_HOVER_EXIT:
153 case AMOTION_EVENT_ACTION_SCROLL:
154 return true;
155 case AMOTION_EVENT_ACTION_POINTER_DOWN:
156 case AMOTION_EVENT_ACTION_POINTER_UP: {
157 int32_t index = getMotionEventActionPointerIndex(action);
158 return index >= 0 && index < pointerCount;
159 }
160 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
161 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
162 return actionButton != 0;
163 default:
164 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 }
166}
167
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500168static int64_t millis(std::chrono::nanoseconds t) {
169 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
170}
171
Michael Wright7b159c92015-05-14 14:48:03 +0100172static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 const PointerProperties* pointerProperties) {
174 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 ALOGE("Motion event has invalid action code 0x%x", action);
176 return false;
177 }
178 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000179 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700180 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 return false;
182 }
183 BitSet32 pointerIdBits;
184 for (size_t i = 0; i < pointerCount; i++) {
185 int32_t id = pointerProperties[i].id;
186 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700187 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
188 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 return false;
190 }
191 if (pointerIdBits.hasBit(id)) {
192 ALOGE("Motion event has duplicate pointer id %d", id);
193 return false;
194 }
195 pointerIdBits.markBit(id);
196 }
197 return true;
198}
199
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800200static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800202 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 return;
204 }
205
206 bool first = true;
207 Region::const_iterator cur = region.begin();
208 Region::const_iterator const tail = region.end();
209 while (cur != tail) {
210 if (first) {
211 first = false;
212 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800213 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800215 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 cur++;
217 }
218}
219
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700220/**
221 * Find the entry in std::unordered_map by key, and return it.
222 * If the entry is not found, return a default constructed entry.
223 *
224 * Useful when the entries are vectors, since an empty vector will be returned
225 * if the entry is not found.
226 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
227 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700228template <typename K, typename V>
229static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700230 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700231 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800232}
233
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700234/**
235 * Find the entry in std::unordered_map by value, and remove it.
236 * If more than one entry has the same value, then all matching
237 * key-value pairs will be removed.
238 *
239 * Return true if at least one value has been removed.
240 */
241template <typename K, typename V>
242static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
243 bool removed = false;
244 for (auto it = map.begin(); it != map.end();) {
245 if (it->second == value) {
246 it = map.erase(it);
247 removed = true;
248 } else {
249 it++;
250 }
251 }
252 return removed;
253}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254
chaviwaf87b3e2019-10-01 16:59:28 -0700255static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
256 if (first == second) {
257 return true;
258 }
259
260 if (first == nullptr || second == nullptr) {
261 return false;
262 }
263
264 return first->getToken() == second->getToken();
265}
266
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800267static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
268 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
269}
270
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000271static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
272 EventEntry* eventEntry,
273 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700274 if (inputTarget.useDefaultPointerTransform()) {
275 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000276 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700277 inputTargetFlags, transform,
278 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000279 }
280
281 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
282 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
283
284 PointerCoords pointerCoords[motionEntry.pointerCount];
285
286 // Use the first pointer information to normalize all other pointers. This could be any pointer
287 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700288 // uses the transform for the normalized pointer.
289 const ui::Transform& firstPointerTransform =
290 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
291 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000292
293 // Iterate through all pointers in the event to normalize against the first.
294 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
295 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
296 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700297 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000298
299 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700300 // First, apply the current pointer's transform to update the coordinates into
301 // window space.
302 pointerCoords[pointerIndex].transform(currTransform);
303 // Next, apply the inverse transform of the normalized coordinates so the
304 // current coordinates are transformed into the normalized coordinate space.
305 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000306 }
307
308 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800309 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000310 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
311 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
312 motionEntry.metaState, motionEntry.buttonState,
313 motionEntry.classification, motionEntry.edgeFlags,
314 motionEntry.xPrecision, motionEntry.yPrecision,
315 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
316 motionEntry.downTime, motionEntry.pointerCount,
317 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
318 0 /* yOffset */);
319
320 if (motionEntry.injectionState) {
321 combinedMotionEntry->injectionState = motionEntry.injectionState;
322 combinedMotionEntry->injectionState->refCount += 1;
323 }
324
325 std::unique_ptr<DispatchEntry> dispatchEntry =
326 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700327 inputTargetFlags, firstPointerTransform,
328 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000329 combinedMotionEntry->release();
330 return dispatchEntry;
331}
332
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700333static void addGestureMonitors(const std::vector<Monitor>& monitors,
334 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
335 float yOffset = 0) {
336 if (monitors.empty()) {
337 return;
338 }
339 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
340 for (const Monitor& monitor : monitors) {
341 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
342 }
343}
344
Gang Wang342c9272020-01-13 13:15:04 -0500345static std::array<uint8_t, 128> getRandomKey() {
346 std::array<uint8_t, 128> key;
347 if (RAND_bytes(key.data(), key.size()) != 1) {
348 LOG_ALWAYS_FATAL("Can't generate HMAC key");
349 }
350 return key;
351}
352
353// --- HmacKeyManager ---
354
355HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
356
357std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
358 size_t size;
359 switch (event.type) {
360 case VerifiedInputEvent::Type::KEY: {
361 size = sizeof(VerifiedKeyEvent);
362 break;
363 }
364 case VerifiedInputEvent::Type::MOTION: {
365 size = sizeof(VerifiedMotionEvent);
366 break;
367 }
368 }
Gang Wang342c9272020-01-13 13:15:04 -0500369 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700370 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500371}
372
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700373std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500374 // SHA256 always generates 32-bytes result
375 std::array<uint8_t, 32> hash;
376 unsigned int hashLen = 0;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700377 uint8_t* result =
378 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500379 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),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700409 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800410 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800411 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800412
Yi Kong9b14ac62018-07-17 13:48:38 -0700413 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414
415 policy->getDispatcherConfiguration(&mConfig);
416}
417
418InputDispatcher::~InputDispatcher() {
419 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800420 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800421
422 resetKeyRepeatLocked();
423 releasePendingEventLocked();
424 drainInboundQueueLocked();
425 }
426
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700427 while (!mConnectionsByFd.empty()) {
428 sp<Connection> connection = mConnectionsByFd.begin()->second;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500429 unregisterInputChannel(*connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800430 }
431}
432
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700433status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700434 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700435 return ALREADY_EXISTS;
436 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700437 mThread = std::make_unique<InputThread>(
438 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
439 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700440}
441
442status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700443 if (mThread && mThread->isCallingThread()) {
444 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700445 return INVALID_OPERATION;
446 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700447 mThread.reset();
448 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700449}
450
Michael Wrightd02c5b62014-02-10 15:10:22 -0800451void InputDispatcher::dispatchOnce() {
452 nsecs_t nextWakeupTime = LONG_LONG_MAX;
453 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800454 std::scoped_lock _l(mLock);
455 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800456
457 // Run a dispatch loop if there are no pending commands.
458 // The dispatch loop might enqueue commands to run afterwards.
459 if (!haveCommandsLocked()) {
460 dispatchOnceInnerLocked(&nextWakeupTime);
461 }
462
463 // Run all pending commands if there are any.
464 // If any commands were run then force the next poll to wake up immediately.
465 if (runCommandsLockedInterruptible()) {
466 nextWakeupTime = LONG_LONG_MIN;
467 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800468
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700469 // If we are still waiting for ack on some events,
470 // we might have to wake up earlier to check if an app is anr'ing.
471 const nsecs_t nextAnrCheck = processAnrsLocked();
472 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
473
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800474 // We are about to enter an infinitely long sleep, because we have no commands or
475 // pending or queued events
476 if (nextWakeupTime == LONG_LONG_MAX) {
477 mDispatcherEnteredIdle.notify_all();
478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800479 } // release lock
480
481 // Wait for callback or timeout or wake. (make sure we round up, not down)
482 nsecs_t currentTime = now();
483 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
484 mLooper->pollOnce(timeoutMillis);
485}
486
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700487/**
488 * Check if any of the connections' wait queues have events that are too old.
489 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
490 * Return the time at which we should wake up next.
491 */
492nsecs_t InputDispatcher::processAnrsLocked() {
493 const nsecs_t currentTime = now();
494 nsecs_t nextAnrCheck = LONG_LONG_MAX;
495 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
496 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
497 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
498 onAnrLocked(mAwaitedFocusedApplication);
Chris Yea209fde2020-07-22 13:54:51 -0700499 mAwaitedFocusedApplication.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700500 return LONG_LONG_MIN;
501 } else {
502 // Keep waiting
503 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
504 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
505 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
506 }
507 }
508
509 // Check if any connection ANRs are due
510 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
511 if (currentTime < nextAnrCheck) { // most likely scenario
512 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
513 }
514
515 // If we reached here, we have an unresponsive connection.
516 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
517 if (connection == nullptr) {
518 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
519 return nextAnrCheck;
520 }
521 connection->responsive = false;
522 // Stop waking up for this unresponsive connection
523 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
524 onAnrLocked(connection);
525 return LONG_LONG_MIN;
526}
527
528nsecs_t InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
529 sp<InputWindowHandle> window = getWindowHandleLocked(token);
530 if (window != nullptr) {
531 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT).count();
532 }
533 return DEFAULT_INPUT_DISPATCHING_TIMEOUT.count();
534}
535
Michael Wrightd02c5b62014-02-10 15:10:22 -0800536void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
537 nsecs_t currentTime = now();
538
Jeff Browndc5992e2014-04-11 01:27:26 -0700539 // Reset the key repeat timer whenever normal dispatch is suspended while the
540 // device is in a non-interactive state. This is to ensure that we abort a key
541 // repeat if the device is just coming out of sleep.
542 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 resetKeyRepeatLocked();
544 }
545
546 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
547 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100548 if (DEBUG_FOCUS) {
549 ALOGD("Dispatch frozen. Waiting some more.");
550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551 return;
552 }
553
554 // Optimize latency of app switches.
555 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
556 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
557 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
558 if (mAppSwitchDueTime < *nextWakeupTime) {
559 *nextWakeupTime = mAppSwitchDueTime;
560 }
561
562 // Ready to start a new event.
563 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700564 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700565 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800566 if (isAppSwitchDue) {
567 // The inbound queue is empty so the app switch key we were waiting
568 // for will never arrive. Stop waiting for it.
569 resetPendingAppSwitchLocked(false);
570 isAppSwitchDue = false;
571 }
572
573 // Synthesize a key repeat if appropriate.
574 if (mKeyRepeatState.lastKeyEntry) {
575 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
576 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
577 } else {
578 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
579 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
580 }
581 }
582 }
583
584 // Nothing to do if there is no pending event.
585 if (!mPendingEvent) {
586 return;
587 }
588 } else {
589 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700590 mPendingEvent = mInboundQueue.front();
591 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800592 traceInboundQueueLengthLocked();
593 }
594
595 // Poke user activity for this event.
596 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700597 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599 }
600
601 // Now we have an event to dispatch.
602 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700603 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800604 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700605 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700607 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700609 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610 }
611
612 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700613 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800614 }
615
616 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700617 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700618 ConfigurationChangedEntry* typedEntry =
619 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
620 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700621 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700622 break;
623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700625 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700626 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
627 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700628 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700629 break;
630 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100632 case EventEntry::Type::FOCUS: {
633 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
634 dispatchFocusLocked(currentTime, typedEntry);
635 done = true;
636 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
637 break;
638 }
639
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700640 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700641 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
642 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700643 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700644 resetPendingAppSwitchLocked(true);
645 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700646 } else if (dropReason == DropReason::NOT_DROPPED) {
647 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700648 }
649 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700650 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700651 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700652 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700653 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
654 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700655 }
656 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
657 break;
658 }
659
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700660 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700661 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700662 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
663 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700665 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700666 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700667 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700668 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
669 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700670 }
671 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
672 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 }
675
676 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700677 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700678 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679 }
Michael Wright3a981722015-06-10 15:26:13 +0100680 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681
682 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700683 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684 }
685}
686
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700687/**
688 * Return true if the events preceding this incoming motion event should be dropped
689 * Return false otherwise (the default behaviour)
690 */
691bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700692 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700693 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700694
695 // Optimize case where the current application is unresponsive and the user
696 // decides to touch a window in a different application.
697 // If the application takes too long to catch up then we drop all events preceding
698 // the touch into the other window.
699 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700700 int32_t displayId = motionEntry.displayId;
701 int32_t x = static_cast<int32_t>(
702 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
703 int32_t y = static_cast<int32_t>(
704 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
705 sp<InputWindowHandle> touchedWindowHandle =
706 findTouchedWindowAtLocked(displayId, x, y, nullptr);
707 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700708 touchedWindowHandle->getApplicationToken() !=
709 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700710 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700711 ALOGI("Pruning input queue because user touched a different application while waiting "
712 "for %s",
713 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700714 return true;
715 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700716
717 // Alternatively, maybe there's a gesture monitor that could handle this event
718 std::vector<TouchedMonitor> gestureMonitors =
719 findTouchedGestureMonitorsLocked(displayId, {});
720 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
721 sp<Connection> connection =
722 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000723 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700724 // This monitor could take more input. Drop all events preceding this
725 // event, so that gesture monitor could get a chance to receive the stream
726 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
727 "responsive gesture monitor that may handle the event",
728 mAwaitedFocusedApplication->getName().c_str());
729 return true;
730 }
731 }
732 }
733
734 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
735 // yet been processed by some connections, the dispatcher will wait for these motion
736 // events to be processed before dispatching the key event. This is because these motion events
737 // may cause a new window to be launched, which the user might expect to receive focus.
738 // To prevent waiting forever for such events, just send the key to the currently focused window
739 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
740 ALOGD("Received a new pointer down event, stop waiting for events to process and "
741 "just send the pending key event to the focused window.");
742 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700743 }
744 return false;
745}
746
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700748 bool needWake = mInboundQueue.empty();
749 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 traceInboundQueueLengthLocked();
751
752 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700753 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700754 // Optimize app switch latency.
755 // If the application takes too long to catch up then we drop all events preceding
756 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700757 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700758 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700759 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700760 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700761 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700762 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800763#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700764 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800765#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700766 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700767 mAppSwitchSawKeyDown = false;
768 needWake = true;
769 }
770 }
771 }
772 break;
773 }
774
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700775 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700776 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
777 mNextUnblockedEvent = entry;
778 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700780 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100782 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700783 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
784 break;
785 }
786 case EventEntry::Type::CONFIGURATION_CHANGED:
787 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700788 // nothing to do
789 break;
790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791 }
792
793 return needWake;
794}
795
796void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
797 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700798 mRecentQueue.push_back(entry);
799 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
800 mRecentQueue.front()->release();
801 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802 }
803}
804
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700806 int32_t y, TouchState* touchState,
807 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700808 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700809 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
810 LOG_ALWAYS_FATAL(
811 "Must provide a valid touch state if adding portal windows or outside targets");
812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800814 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
815 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816 const InputWindowInfo* windowInfo = windowHandle->getInfo();
817 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100818 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819
820 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100821 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
822 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
823 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800825 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700826 if (portalToDisplayId != ADISPLAY_ID_NONE &&
827 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800828 if (addPortalWindows) {
829 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700830 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800831 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700832 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700833 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800834 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835 // Found window.
836 return windowHandle;
837 }
838 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800839
Michael Wright44753b12020-07-08 13:48:11 +0100840 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700841 touchState->addOrUpdateWindow(windowHandle,
842 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
843 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846 }
847 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700848 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849}
850
Garfield Tane84e6f92019-08-29 17:28:41 -0700851std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700852 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000853 std::vector<TouchedMonitor> touchedMonitors;
854
855 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
856 addGestureMonitors(monitors, touchedMonitors);
857 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
858 const InputWindowInfo* windowInfo = portalWindow->getInfo();
859 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700860 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
861 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000862 }
863 return touchedMonitors;
864}
865
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700866void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 const char* reason;
868 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700869 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700871 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700873 reason = "inbound event was dropped because the policy consumed it";
874 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700875 case DropReason::DISABLED:
876 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700877 ALOGI("Dropped event because input dispatch is disabled.");
878 }
879 reason = "inbound event was dropped because input dispatch is disabled";
880 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700881 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700882 ALOGI("Dropped event because of pending overdue app switch.");
883 reason = "inbound event was dropped because of pending overdue app switch";
884 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700885 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700886 ALOGI("Dropped event because the current application is not responding and the user "
887 "has started interacting with a different application.");
888 reason = "inbound event was dropped because the current application is not responding "
889 "and the user has started interacting with a different application";
890 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700891 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700892 ALOGI("Dropped event because it is stale.");
893 reason = "inbound event was dropped because it is stale";
894 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700895 case DropReason::NOT_DROPPED: {
896 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700897 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 }
900
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700901 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700902 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
904 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700907 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700908 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
909 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700910 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
911 synthesizeCancelationEventsForAllConnectionsLocked(options);
912 } else {
913 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
914 synthesizeCancelationEventsForAllConnectionsLocked(options);
915 }
916 break;
917 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100918 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700919 case EventEntry::Type::CONFIGURATION_CHANGED:
920 case EventEntry::Type::DEVICE_RESET: {
921 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
922 break;
923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 }
925}
926
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800927static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700928 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
929 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930}
931
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700932bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
933 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
934 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
935 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936}
937
938bool InputDispatcher::isAppSwitchPendingLocked() {
939 return mAppSwitchDueTime != LONG_LONG_MAX;
940}
941
942void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
943 mAppSwitchDueTime = LONG_LONG_MAX;
944
945#if DEBUG_APP_SWITCH
946 if (handled) {
947 ALOGD("App switch has arrived.");
948 } else {
949 ALOGD("App switch was abandoned.");
950 }
951#endif
952}
953
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700955 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956}
957
958bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700959 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 return false;
961 }
962
963 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700964 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700965 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700967 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968
969 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700970 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 return true;
972}
973
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700974void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
975 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976}
977
978void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700979 while (!mInboundQueue.empty()) {
980 EventEntry* entry = mInboundQueue.front();
981 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 releaseInboundEventLocked(entry);
983 }
984 traceInboundQueueLengthLocked();
985}
986
987void InputDispatcher::releasePendingEventLocked() {
988 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700990 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 }
992}
993
994void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
995 InjectionState* injectionState = entry->injectionState;
996 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
997#if DEBUG_DISPATCH_CYCLE
998 ALOGD("Injected inbound event was dropped.");
999#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001000 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
1002 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001003 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 }
1005 addRecentEventLocked(entry);
1006 entry->release();
1007}
1008
1009void InputDispatcher::resetKeyRepeatLocked() {
1010 if (mKeyRepeatState.lastKeyEntry) {
1011 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001012 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001013 }
1014}
1015
Garfield Tane84e6f92019-08-29 17:28:41 -07001016KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1018
1019 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001020 uint32_t policyFlags = entry->policyFlags &
1021 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 if (entry->refCount == 1) {
1023 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001024 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 entry->eventTime = currentTime;
1026 entry->policyFlags = policyFlags;
1027 entry->repeatCount += 1;
1028 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001029 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001030 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001031 entry->displayId, policyFlags, entry->action, entry->flags,
1032 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001033 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034
1035 mKeyRepeatState.lastKeyEntry = newEntry;
1036 entry->release();
1037
1038 entry = newEntry;
1039 }
1040 entry->syntheticRepeat = true;
1041
1042 // Increment reference count since we keep a reference to the event in
1043 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1044 entry->refCount += 1;
1045
1046 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1047 return entry;
1048}
1049
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001050bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1051 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001053 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054#endif
1055
1056 // Reset key repeating in case a keyboard device was added or removed or something.
1057 resetKeyRepeatLocked();
1058
1059 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001060 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1061 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001063 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 return true;
1065}
1066
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001067bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001069 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071#endif
1072
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 options.deviceId = entry->deviceId;
1075 synthesizeCancelationEventsForAllConnectionsLocked(options);
1076 return true;
1077}
1078
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001079void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus,
1080 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001081 if (mPendingEvent != nullptr) {
1082 // Move the pending event to the front of the queue. This will give the chance
1083 // for the pending event to get dispatched to the newly focused window
1084 mInboundQueue.push_front(mPendingEvent);
1085 mPendingEvent = nullptr;
1086 }
1087
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001088 FocusEntry* focusEntry =
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001089 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001090
1091 // This event should go to the front of the queue, but behind all other focus events
1092 // Find the last focus event, and insert right after it
1093 std::deque<EventEntry*>::reverse_iterator it =
1094 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1095 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1096
1097 // Maintain the order of focus events. Insert the entry after all other focus events.
1098 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001099}
1100
1101void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001102 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001103 if (channel == nullptr) {
1104 return; // Window has gone away
1105 }
1106 InputTarget target;
1107 target.inputChannel = channel;
1108 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1109 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001110 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1111 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001112 std::string reason = std::string("reason=").append(entry->reason);
1113 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001114 dispatchEventLocked(currentTime, entry, {target});
1115}
1116
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001118 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001120 if (!entry->dispatchInProgress) {
1121 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1122 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1123 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1124 if (mKeyRepeatState.lastKeyEntry &&
1125 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 // We have seen two identical key downs in a row which indicates that the device
1127 // driver is automatically generating key repeats itself. We take note of the
1128 // repeat here, but we disable our own next key repeat timer since it is clear that
1129 // we will not need to synthesize key repeats ourselves.
1130 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1131 resetKeyRepeatLocked();
1132 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1133 } else {
1134 // Not a repeat. Save key down state in case we do see a repeat later.
1135 resetKeyRepeatLocked();
1136 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1137 }
1138 mKeyRepeatState.lastKeyEntry = entry;
1139 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001140 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 resetKeyRepeatLocked();
1142 }
1143
1144 if (entry->repeatCount == 1) {
1145 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1146 } else {
1147 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1148 }
1149
1150 entry->dispatchInProgress = true;
1151
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001152 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 }
1154
1155 // Handle case where the policy asked us to try again later last time.
1156 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1157 if (currentTime < entry->interceptKeyWakeupTime) {
1158 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1159 *nextWakeupTime = entry->interceptKeyWakeupTime;
1160 }
1161 return false; // wait until next wakeup
1162 }
1163 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1164 entry->interceptKeyWakeupTime = 0;
1165 }
1166
1167 // Give the policy a chance to intercept the key.
1168 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1169 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001170 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001171 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001172 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001173 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001174 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001175 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 }
1177 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001178 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 entry->refCount += 1;
1180 return false; // wait for the command to run
1181 } else {
1182 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1183 }
1184 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001185 if (*dropReason == DropReason::NOT_DROPPED) {
1186 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 }
1188 }
1189
1190 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001191 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001192 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001193 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001194 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001195 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 return true;
1197 }
1198
1199 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001200 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001201 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001202 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1204 return false;
1205 }
1206
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001207 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1209 return true;
1210 }
1211
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001212 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001213 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214
1215 // Dispatch the key.
1216 dispatchEventLocked(currentTime, entry, inputTargets);
1217 return true;
1218}
1219
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001220void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001222 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001223 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1224 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001225 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1226 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1227 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228#endif
1229}
1230
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001231bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1232 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001233 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001235 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 entry->dispatchInProgress = true;
1237
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001238 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 }
1240
1241 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001242 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001243 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001244 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001245 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 return true;
1247 }
1248
1249 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1250
1251 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001252 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253
1254 bool conflictingPointerActions = false;
1255 int32_t injectionResult;
1256 if (isPointerEvent) {
1257 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001258 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001259 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001260 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 } else {
1262 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001263 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001264 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 }
1266 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1267 return false;
1268 }
1269
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001270 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001271 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1272 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1273 return true;
1274 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001276 CancelationOptions::Mode mode(isPointerEvent
1277 ? CancelationOptions::CANCEL_POINTER_EVENTS
1278 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1279 CancelationOptions options(mode, "input event injection failed");
1280 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 return true;
1282 }
1283
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001284 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001285 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001287 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001288 std::unordered_map<int32_t, TouchState>::iterator it =
1289 mTouchStatesByDisplay.find(entry->displayId);
1290 if (it != mTouchStatesByDisplay.end()) {
1291 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001292 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001293 // The event has gone through these portal windows, so we add monitoring targets of
1294 // the corresponding displays as well.
1295 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001296 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001297 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001298 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001299 }
1300 }
1301 }
1302 }
1303
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 // Dispatch the motion.
1305 if (conflictingPointerActions) {
1306 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 synthesizeCancelationEventsForAllConnectionsLocked(options);
1309 }
1310 dispatchEventLocked(currentTime, entry, inputTargets);
1311 return true;
1312}
1313
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001314void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001316 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001317 ", policyFlags=0x%x, "
1318 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1319 "metaState=0x%x, buttonState=0x%x,"
1320 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001321 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1322 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1323 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001325 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001327 "x=%f, y=%f, pressure=%f, size=%f, "
1328 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1329 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001330 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1331 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1332 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1333 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1334 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1335 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1336 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1337 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1338 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1339 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 }
1341#endif
1342}
1343
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001344void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1345 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001346 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347#if DEBUG_DISPATCH_CYCLE
1348 ALOGD("dispatchEventToCurrentInputTargets");
1349#endif
1350
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001351 updateInteractionTokensLocked(*eventEntry, inputTargets);
1352
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1354
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001355 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001357 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001358 sp<Connection> connection =
1359 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001360 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001361 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001363 if (DEBUG_FOCUS) {
1364 ALOGD("Dropping event delivery to target with channel '%s' because it "
1365 "is no longer registered with the input dispatcher.",
1366 inputTarget.inputChannel->getName().c_str());
1367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001368 }
1369 }
1370}
1371
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001372void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1373 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1374 // If the policy decides to close the app, we will get a channel removal event via
1375 // unregisterInputChannel, and will clean up the connection that way. We are already not
1376 // sending new pointers to the connection when it blocked, but focused events will continue to
1377 // pile up.
1378 ALOGW("Canceling events for %s because it is unresponsive",
1379 connection->inputChannel->getName().c_str());
1380 if (connection->status == Connection::STATUS_NORMAL) {
1381 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1382 "application not responding");
1383 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001384 }
1385}
1386
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001387void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001388 if (DEBUG_FOCUS) {
1389 ALOGD("Resetting ANR timeouts.");
1390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391
1392 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001393 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001394 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395}
1396
Tiger Huang721e26f2018-07-24 22:26:19 +08001397/**
1398 * Get the display id that the given event should go to. If this event specifies a valid display id,
1399 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1400 * Focused display is the display that the user most recently interacted with.
1401 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001402int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001403 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001404 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001405 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001406 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1407 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001408 break;
1409 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001410 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001411 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1412 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001413 break;
1414 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001415 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001416 case EventEntry::Type::CONFIGURATION_CHANGED:
1417 case EventEntry::Type::DEVICE_RESET: {
1418 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001419 return ADISPLAY_ID_NONE;
1420 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001421 }
1422 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1423}
1424
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001425bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1426 const char* focusedWindowName) {
1427 if (mAnrTracker.empty()) {
1428 // already processed all events that we waited for
1429 mKeyIsWaitingForEventsTimeout = std::nullopt;
1430 return false;
1431 }
1432
1433 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1434 // Start the timer
1435 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1436 "focus to change",
1437 focusedWindowName);
1438 mKeyIsWaitingForEventsTimeout = currentTime + KEY_WAITING_FOR_EVENTS_TIMEOUT.count();
1439 return true;
1440 }
1441
1442 // We still have pending events, and already started the timer
1443 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1444 return true; // Still waiting
1445 }
1446
1447 // Waited too long, and some connection still hasn't processed all motions
1448 // Just send the key to the focused window
1449 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1450 focusedWindowName);
1451 mKeyIsWaitingForEventsTimeout = std::nullopt;
1452 return false;
1453}
1454
Michael Wrightd02c5b62014-02-10 15:10:22 -08001455int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001456 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001457 std::vector<InputTarget>& inputTargets,
1458 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001459 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460
Tiger Huang721e26f2018-07-24 22:26:19 +08001461 int32_t displayId = getTargetDisplayId(entry);
1462 sp<InputWindowHandle> focusedWindowHandle =
1463 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001464 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001465 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1466
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 // If there is no currently focused window and no focused application
1468 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001469 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1470 ALOGI("Dropping %s event because there is no focused window or focused application in "
1471 "display %" PRId32 ".",
1472 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001473 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 }
1475
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001476 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1477 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1478 // start interacting with another application via touch (app switch). This code can be removed
1479 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1480 // an app is expected to have a focused window.
1481 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1482 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1483 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001484 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1485 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1486 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001487 mAwaitedFocusedApplication = focusedApplicationHandle;
1488 ALOGW("Waiting because no window has focus but %s may eventually add a "
1489 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001490 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001491 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1492 return INPUT_EVENT_INJECTION_PENDING;
1493 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1494 // Already raised ANR. Drop the event
1495 ALOGE("Dropping %s event because there is no focused window",
1496 EventEntry::typeToString(entry.type));
1497 return INPUT_EVENT_INJECTION_FAILED;
1498 } else {
1499 // Still waiting for the focused window
1500 return INPUT_EVENT_INJECTION_PENDING;
1501 }
1502 }
1503
1504 // we have a valid, non-null focused window
1505 resetNoFocusedWindowTimeoutLocked();
1506
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001508 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001509 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 }
1511
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001512 if (focusedWindowHandle->getInfo()->paused) {
1513 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1514 return INPUT_EVENT_INJECTION_PENDING;
1515 }
1516
1517 // If the event is a key event, then we must wait for all previous events to
1518 // complete before delivering it because previous events may have the
1519 // side-effect of transferring focus to a different window and we want to
1520 // ensure that the following keys are sent to the new window.
1521 //
1522 // Suppose the user touches a button in a window then immediately presses "A".
1523 // If the button causes a pop-up window to appear then we want to ensure that
1524 // the "A" key is delivered to the new pop-up window. This is because users
1525 // often anticipate pending UI changes when typing on a keyboard.
1526 // To obtain this behavior, we must serialize key events with respect to all
1527 // prior input events.
1528 if (entry.type == EventEntry::Type::KEY) {
1529 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1530 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1531 return INPUT_EVENT_INJECTION_PENDING;
1532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 }
1534
1535 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001536 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001537 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1538 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539
1540 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001541 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542}
1543
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001544/**
1545 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1546 * that are currently unresponsive.
1547 */
1548std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1549 const std::vector<TouchedMonitor>& monitors) const {
1550 std::vector<TouchedMonitor> responsiveMonitors;
1551 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1552 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1553 sp<Connection> connection = getConnectionLocked(
1554 monitor.monitor.inputChannel->getConnectionToken());
1555 if (connection == nullptr) {
1556 ALOGE("Could not find connection for monitor %s",
1557 monitor.monitor.inputChannel->getName().c_str());
1558 return false;
1559 }
1560 if (!connection->responsive) {
1561 ALOGW("Unresponsive monitor %s will not get the new gesture",
1562 connection->inputChannel->getName().c_str());
1563 return false;
1564 }
1565 return true;
1566 });
1567 return responsiveMonitors;
1568}
1569
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001571 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001572 std::vector<InputTarget>& inputTargets,
1573 nsecs_t* nextWakeupTime,
1574 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001575 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 enum InjectionPermission {
1577 INJECTION_PERMISSION_UNKNOWN,
1578 INJECTION_PERMISSION_GRANTED,
1579 INJECTION_PERMISSION_DENIED
1580 };
1581
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582 // For security reasons, we defer updating the touch state until we are sure that
1583 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001584 int32_t displayId = entry.displayId;
1585 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1587
1588 // Update the touch state as needed based on the properties of the touch event.
1589 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1590 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001591 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1592 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001594 // Copy current touch state into tempTouchState.
1595 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1596 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001597 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001598 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001599 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1600 mTouchStatesByDisplay.find(displayId);
1601 if (oldStateIt != mTouchStatesByDisplay.end()) {
1602 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001603 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001604 }
1605
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001606 bool isSplit = tempTouchState.split;
1607 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1608 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1609 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001610 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1611 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1612 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1613 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1614 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001615 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 bool wrongDevice = false;
1617 if (newGesture) {
1618 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001619 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001620 ALOGI("Dropping event because a pointer for a different device is already down "
1621 "in display %" PRId32,
1622 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001623 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1625 switchedDevice = false;
1626 wrongDevice = true;
1627 goto Failed;
1628 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001629 tempTouchState.reset();
1630 tempTouchState.down = down;
1631 tempTouchState.deviceId = entry.deviceId;
1632 tempTouchState.source = entry.source;
1633 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001635 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001636 ALOGI("Dropping move event because a pointer for a different device is already active "
1637 "in display %" PRId32,
1638 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001639 // TODO: test multiple simultaneous input streams.
1640 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1641 switchedDevice = false;
1642 wrongDevice = true;
1643 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 }
1645
1646 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1647 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1648
Garfield Tan00f511d2019-06-12 16:55:40 -07001649 int32_t x;
1650 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001652 // Always dispatch mouse events to cursor position.
1653 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001654 x = int32_t(entry.xCursorPosition);
1655 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001656 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001657 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1658 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001659 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001660 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001661 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001662 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1663 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001664
1665 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001666 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001667 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001670 if (newTouchedWindowHandle != nullptr &&
1671 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001672 // New window supports splitting, but we should never split mouse events.
1673 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 } else if (isSplit) {
1675 // New window does not support splitting but we have already split events.
1676 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001677 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 }
1679
1680 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001681 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001683 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001684 }
1685
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001686 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1687 ALOGI("Not sending touch event to %s because it is paused",
1688 newTouchedWindowHandle->getName().c_str());
1689 newTouchedWindowHandle = nullptr;
1690 }
1691
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001692 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001693 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001694 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1695 if (!isResponsive) {
1696 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001697 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1698 newTouchedWindowHandle = nullptr;
1699 }
1700 }
1701
1702 // Also don't send the new touch event to unresponsive gesture monitors
1703 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1704
Michael Wright3dd60e22019-03-27 22:06:44 +00001705 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1706 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001707 "(%d, %d) in display %" PRId32 ".",
1708 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001709 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1710 goto Failed;
1711 }
1712
1713 if (newTouchedWindowHandle != nullptr) {
1714 // Set target flags.
1715 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1716 if (isSplit) {
1717 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001719 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1720 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1721 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1722 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1723 }
1724
1725 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001726 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1727 newHoverWindowHandle = nullptr;
1728 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001729 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001730 }
1731
1732 // Update the temporary touch state.
1733 BitSet32 pointerIds;
1734 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001735 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001736 pointerIds.markBit(pointerId);
1737 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001738 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 }
1740
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001741 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 } else {
1743 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1744
1745 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001746 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001747 if (DEBUG_FOCUS) {
1748 ALOGD("Dropping event because the pointer is not down or we previously "
1749 "dropped the pointer down event in display %" PRId32,
1750 displayId);
1751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1753 goto Failed;
1754 }
1755
1756 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001757 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001758 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001759 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1760 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761
1762 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001763 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001764 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001765 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1766 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001767 if (DEBUG_FOCUS) {
1768 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1769 oldTouchedWindowHandle->getName().c_str(),
1770 newTouchedWindowHandle->getName().c_str(), displayId);
1771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001773 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1774 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1775 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776
1777 // Make a slippery entrance into the new window.
1778 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1779 isSplit = true;
1780 }
1781
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001782 int32_t targetFlags =
1783 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 if (isSplit) {
1785 targetFlags |= InputTarget::FLAG_SPLIT;
1786 }
1787 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1788 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1789 }
1790
1791 BitSet32 pointerIds;
1792 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001793 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001795 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 }
1797 }
1798 }
1799
1800 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001801 // Let the previous window know that the hover sequence is over, unless we already did it
1802 // when dispatching it as is to newTouchedWindowHandle.
1803 if (mLastHoverWindowHandle != nullptr &&
1804 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1805 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806#if DEBUG_HOVER
1807 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001808 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001810 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1811 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 }
1813
Garfield Tandf26e862020-07-01 20:18:19 -07001814 // Let the new window know that the hover sequence is starting, unless we already did it
1815 // when dispatching it as is to newTouchedWindowHandle.
1816 if (newHoverWindowHandle != nullptr &&
1817 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1818 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819#if DEBUG_HOVER
1820 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001821 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001823 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1824 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1825 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 }
1827 }
1828
1829 // Check permission to inject into all touched foreground windows and ensure there
1830 // is at least one touched foreground window.
1831 {
1832 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001833 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1835 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001836 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1838 injectionPermission = INJECTION_PERMISSION_DENIED;
1839 goto Failed;
1840 }
1841 }
1842 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001843 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001844 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001845 ALOGI("Dropping event because there is no touched foreground window in display "
1846 "%" PRId32 " or gesture monitor to receive it.",
1847 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1849 goto Failed;
1850 }
1851
1852 // Permission granted to injection into all touched foreground windows.
1853 injectionPermission = INJECTION_PERMISSION_GRANTED;
1854 }
1855
1856 // Check whether windows listening for outside touches are owned by the same UID. If it is
1857 // set the policy flag that we will not reveal coordinate information to this window.
1858 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1859 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001860 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001861 if (foregroundWindowHandle) {
1862 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001863 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001864 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1865 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1866 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001867 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1868 InputTarget::FLAG_ZERO_COORDS,
1869 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 }
1872 }
1873 }
1874 }
1875
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 // If this is the first pointer going down and the touched window has a wallpaper
1877 // then also add the touched wallpaper windows so they are locked in for the duration
1878 // of the touch gesture.
1879 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1880 // engine only supports touch events. We would need to add a mechanism similar
1881 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1882 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1883 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001884 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001885 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001886 const std::vector<sp<InputWindowHandle>> windowHandles =
1887 getWindowHandlesLocked(displayId);
1888 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001890 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001891 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001892 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001893 .addOrUpdateWindow(windowHandle,
1894 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1895 InputTarget::
1896 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1897 InputTarget::FLAG_DISPATCH_AS_IS,
1898 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 }
1900 }
1901 }
1902 }
1903
1904 // Success! Output targets.
1905 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1906
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001907 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001909 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 }
1911
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001912 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001913 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001914 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001915 }
1916
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 // Drop the outside or hover touch windows since we will not care about them
1918 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001919 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920
1921Failed:
1922 // Check injection permission once and for all.
1923 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001924 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 injectionPermission = INJECTION_PERMISSION_GRANTED;
1926 } else {
1927 injectionPermission = INJECTION_PERMISSION_DENIED;
1928 }
1929 }
1930
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001931 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1932 return injectionResult;
1933 }
1934
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001936 if (!wrongDevice) {
1937 if (switchedDevice) {
1938 if (DEBUG_FOCUS) {
1939 ALOGD("Conflicting pointer actions: Switched to a different device.");
1940 }
1941 *outConflictingPointerActions = true;
1942 }
1943
1944 if (isHoverAction) {
1945 // Started hovering, therefore no longer down.
1946 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001947 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001948 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1949 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951 *outConflictingPointerActions = true;
1952 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001953 tempTouchState.reset();
1954 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1955 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1956 tempTouchState.deviceId = entry.deviceId;
1957 tempTouchState.source = entry.source;
1958 tempTouchState.displayId = displayId;
1959 }
1960 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1961 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1962 // All pointers up or canceled.
1963 tempTouchState.reset();
1964 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1965 // First pointer went down.
1966 if (oldState && oldState->down) {
1967 if (DEBUG_FOCUS) {
1968 ALOGD("Conflicting pointer actions: Down received while already down.");
1969 }
1970 *outConflictingPointerActions = true;
1971 }
1972 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1973 // One pointer went up.
1974 if (isSplit) {
1975 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1976 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001978 for (size_t i = 0; i < tempTouchState.windows.size();) {
1979 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1980 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1981 touchedWindow.pointerIds.clearBit(pointerId);
1982 if (touchedWindow.pointerIds.isEmpty()) {
1983 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1984 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001987 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001989 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001990 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001991
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001992 // Save changes unless the action was scroll in which case the temporary touch
1993 // state was only valid for this one action.
1994 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1995 if (tempTouchState.displayId >= 0) {
1996 mTouchStatesByDisplay[displayId] = tempTouchState;
1997 } else {
1998 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002002 // Update hover state.
2003 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 }
2005
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 return injectionResult;
2007}
2008
2009void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002010 int32_t targetFlags, BitSet32 pointerIds,
2011 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002012 std::vector<InputTarget>::iterator it =
2013 std::find_if(inputTargets.begin(), inputTargets.end(),
2014 [&windowHandle](const InputTarget& inputTarget) {
2015 return inputTarget.inputChannel->getConnectionToken() ==
2016 windowHandle->getToken();
2017 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002018
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002019 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002020
2021 if (it == inputTargets.end()) {
2022 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002023 std::shared_ptr<InputChannel> inputChannel =
2024 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002025 if (inputChannel == nullptr) {
2026 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2027 return;
2028 }
2029 inputTarget.inputChannel = inputChannel;
2030 inputTarget.flags = targetFlags;
2031 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2032 inputTargets.push_back(inputTarget);
2033 it = inputTargets.end() - 1;
2034 }
2035
2036 ALOG_ASSERT(it->flags == targetFlags);
2037 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2038
chaviw1ff3d1e2020-07-01 15:53:47 -07002039 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040}
2041
Michael Wright3dd60e22019-03-27 22:06:44 +00002042void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002043 int32_t displayId, float xOffset,
2044 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002045 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2046 mGlobalMonitorsByDisplay.find(displayId);
2047
2048 if (it != mGlobalMonitorsByDisplay.end()) {
2049 const std::vector<Monitor>& monitors = it->second;
2050 for (const Monitor& monitor : monitors) {
2051 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 }
2054}
2055
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002056void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2057 float yOffset,
2058 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002059 InputTarget target;
2060 target.inputChannel = monitor.inputChannel;
2061 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002062 ui::Transform t;
2063 t.set(xOffset, yOffset);
2064 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002065 inputTargets.push_back(target);
2066}
2067
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002069 const InjectionState* injectionState) {
2070 if (injectionState &&
2071 (windowHandle == nullptr ||
2072 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2073 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002074 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002076 "owned by uid %d",
2077 injectionState->injectorPid, injectionState->injectorUid,
2078 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 } else {
2080 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002081 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 }
2083 return false;
2084 }
2085 return true;
2086}
2087
Robert Carrc9bf1d32020-04-13 17:21:08 -07002088/**
2089 * Indicate whether one window handle should be considered as obscuring
2090 * another window handle. We only check a few preconditions. Actually
2091 * checking the bounds is left to the caller.
2092 */
2093static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2094 const sp<InputWindowHandle>& otherHandle) {
2095 // Compare by token so cloned layers aren't counted
2096 if (haveSameToken(windowHandle, otherHandle)) {
2097 return false;
2098 }
2099 auto info = windowHandle->getInfo();
2100 auto otherInfo = otherHandle->getInfo();
2101 if (!otherInfo->visible) {
2102 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002103 } else if (info->ownerPid == otherInfo->ownerPid) {
2104 // If ownerPid is the same we don't generate occlusion events as there
2105 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002106 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002107 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002108 return false;
2109 } else if (otherInfo->displayId != info->displayId) {
2110 return false;
2111 }
2112 return true;
2113}
2114
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002115bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2116 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002118 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2119 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002120 if (windowHandle == otherHandle) {
2121 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002124 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002125 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 return true;
2127 }
2128 }
2129 return false;
2130}
2131
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002132bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2133 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002134 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002135 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002136 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002137 if (windowHandle == otherHandle) {
2138 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002139 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002140 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002141 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002142 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002143 return true;
2144 }
2145 }
2146 return false;
2147}
2148
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002149std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002150 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002152 if (applicationHandle != nullptr) {
2153 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002154 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 } else {
2156 return applicationHandle->getName();
2157 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002158 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002159 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002161 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 }
2163}
2164
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002165void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002166 if (eventEntry.type == EventEntry::Type::FOCUS) {
2167 // Focus events are passed to apps, but do not represent user activity.
2168 return;
2169 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002170 int32_t displayId = getTargetDisplayId(eventEntry);
2171 sp<InputWindowHandle> focusedWindowHandle =
2172 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2173 if (focusedWindowHandle != nullptr) {
2174 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002175 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002177 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178#endif
2179 return;
2180 }
2181 }
2182
2183 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002184 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002185 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002186 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2187 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002188 return;
2189 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002191 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002192 eventType = USER_ACTIVITY_EVENT_TOUCH;
2193 }
2194 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002196 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002197 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2198 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002199 return;
2200 }
2201 eventType = USER_ACTIVITY_EVENT_BUTTON;
2202 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002204 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002205 case EventEntry::Type::CONFIGURATION_CHANGED:
2206 case EventEntry::Type::DEVICE_RESET: {
2207 LOG_ALWAYS_FATAL("%s events are not user activity",
2208 EventEntry::typeToString(eventEntry.type));
2209 break;
2210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 }
2212
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002213 std::unique_ptr<CommandEntry> commandEntry =
2214 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002215 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002217 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218}
2219
2220void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002221 const sp<Connection>& connection,
2222 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002223 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002224 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002225 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002226 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002227 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002228 ATRACE_NAME(message.c_str());
2229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230#if DEBUG_DISPATCH_CYCLE
2231 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002232 "globalScaleFactor=%f, pointerIds=0x%x %s",
2233 connection->getInputChannelName().c_str(), inputTarget.flags,
2234 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2235 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236#endif
2237
2238 // Skip this event if the connection status is not normal.
2239 // We don't want to enqueue additional outbound events if the connection is broken.
2240 if (connection->status != Connection::STATUS_NORMAL) {
2241#if DEBUG_DISPATCH_CYCLE
2242 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002243 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244#endif
2245 return;
2246 }
2247
2248 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002249 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2250 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2251 "Entry type %s should not have FLAG_SPLIT",
2252 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002254 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002255 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002256 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002257 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258 if (!splitMotionEntry) {
2259 return; // split event was dropped
2260 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002261 if (DEBUG_FOCUS) {
2262 ALOGD("channel '%s' ~ Split motion event.",
2263 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002264 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002265 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002266 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267 splitMotionEntry->release();
2268 return;
2269 }
2270 }
2271
2272 // Not splitting. Enqueue dispatch entries for the event as is.
2273 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2274}
2275
2276void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002277 const sp<Connection>& connection,
2278 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002279 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002280 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002281 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002282 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002283 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002284 ATRACE_NAME(message.c_str());
2285 }
2286
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002287 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288
2289 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002290 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002291 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002292 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002293 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002294 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002296 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002298 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002299 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002300 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002301 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302
2303 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002304 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 startDispatchCycleLocked(currentTime, connection);
2306 }
2307}
2308
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002309void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2310 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002311 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002312 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002313 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002314 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2315 connection->getInputChannelName().c_str(),
2316 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002317 ATRACE_NAME(message.c_str());
2318 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002319 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 if (!(inputTargetFlags & dispatchMode)) {
2321 return;
2322 }
2323 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2324
2325 // This is a new event.
2326 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002327 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002328 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002330 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2331 // different EventEntry than what was passed in.
2332 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002334 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002335 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002336 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002337 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002338 dispatchEntry->resolvedAction = keyEntry.action;
2339 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002341 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2342 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002344 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2345 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002347 return; // skip the inconsistent event
2348 }
2349 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002352 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002353 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002354 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2355 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2356 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2357 static_cast<int32_t>(IdGenerator::Source::OTHER);
2358 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002359 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2360 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2361 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2362 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2363 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2364 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2365 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2366 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2367 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2368 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2369 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002370 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002371 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002372 }
2373 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002374 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2375 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002377 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2378 "event",
2379 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002381 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002384 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002385 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2386 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2387 }
2388 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2389 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002392 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2393 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002395 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2396 "event",
2397 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002399 return; // skip the inconsistent event
2400 }
2401
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002402 dispatchEntry->resolvedEventId =
2403 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2404 ? mIdGenerator.nextId()
2405 : motionEntry.id;
2406 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2407 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2408 ") to MotionEvent(id=0x%" PRIx32 ").",
2409 motionEntry.id, dispatchEntry->resolvedEventId);
2410 ATRACE_NAME(message.c_str());
2411 }
2412
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002413 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002414 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002415
2416 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002418 case EventEntry::Type::FOCUS: {
2419 break;
2420 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002421 case EventEntry::Type::CONFIGURATION_CHANGED:
2422 case EventEntry::Type::DEVICE_RESET: {
2423 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002424 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002425 break;
2426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 }
2428
2429 // Remember that we are waiting for this dispatch to complete.
2430 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002431 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432 }
2433
2434 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002435 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002436 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002437}
2438
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002439/**
2440 * This function is purely for debugging. It helps us understand where the user interaction
2441 * was taking place. For example, if user is touching launcher, we will see a log that user
2442 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2443 * We will see both launcher and wallpaper in that list.
2444 * Once the interaction with a particular set of connections starts, no new logs will be printed
2445 * until the set of interacted connections changes.
2446 *
2447 * The following items are skipped, to reduce the logspam:
2448 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2449 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2450 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2451 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2452 * Both of those ACTION_UP events would not be logged
2453 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2454 * will not be logged. This is omitted to reduce the amount of data printed.
2455 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2456 * gesture monitor is the only connection receiving the remainder of the gesture.
2457 */
2458void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2459 const std::vector<InputTarget>& targets) {
2460 // Skip ACTION_UP events, and all events other than keys and motions
2461 if (entry.type == EventEntry::Type::KEY) {
2462 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2463 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2464 return;
2465 }
2466 } else if (entry.type == EventEntry::Type::MOTION) {
2467 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2468 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2469 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2470 return;
2471 }
2472 } else {
2473 return; // Not a key or a motion
2474 }
2475
2476 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2477 std::vector<sp<Connection>> newConnections;
2478 for (const InputTarget& target : targets) {
2479 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2480 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2481 continue; // Skip windows that receive ACTION_OUTSIDE
2482 }
2483
2484 sp<IBinder> token = target.inputChannel->getConnectionToken();
2485 sp<Connection> connection = getConnectionLocked(token);
2486 if (connection == nullptr || connection->monitor) {
2487 continue; // We only need to keep track of the non-monitor connections.
2488 }
2489 newConnectionTokens.insert(std::move(token));
2490 newConnections.emplace_back(connection);
2491 }
2492 if (newConnectionTokens == mInteractionConnectionTokens) {
2493 return; // no change
2494 }
2495 mInteractionConnectionTokens = newConnectionTokens;
2496
2497 std::string windowList;
2498 for (const sp<Connection>& connection : newConnections) {
2499 windowList += connection->getWindowName() + ", ";
2500 }
2501 std::string message = "Interaction with windows: " + windowList;
2502 if (windowList.empty()) {
2503 message += "<none>";
2504 }
2505 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2506}
2507
chaviwfd6d3512019-03-25 13:23:49 -07002508void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002509 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002510 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002511 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2512 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002513 return;
2514 }
2515
2516 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2517 if (inputWindowHandle == nullptr) {
2518 return;
2519 }
2520
chaviw8c9cf542019-03-25 13:02:48 -07002521 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002522 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002523
2524 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2525
2526 if (!hasFocusChanged) {
2527 return;
2528 }
2529
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002530 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2531 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002532 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002533 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534}
2535
2536void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002537 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002538 if (ATRACE_ENABLED()) {
2539 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002540 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002541 ATRACE_NAME(message.c_str());
2542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002544 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545#endif
2546
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002547 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2548 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002550 const nsecs_t timeout =
2551 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
2552 dispatchEntry->timeoutTime = currentTime + timeout;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553
2554 // Publish the event.
2555 status_t status;
2556 EventEntry* eventEntry = dispatchEntry->eventEntry;
2557 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002558 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002559 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2560 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002562 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002563 status =
2564 connection->inputPublisher
2565 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2566 keyEntry->deviceId, keyEntry->source,
2567 keyEntry->displayId, std::move(hmac),
2568 dispatchEntry->resolvedAction,
2569 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2570 keyEntry->scanCode, keyEntry->metaState,
2571 keyEntry->repeatCount, keyEntry->downTime,
2572 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002573 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574 }
2575
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002576 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002579 PointerCoords scaledCoords[MAX_POINTERS];
2580 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2581
chaviw82357092020-01-28 13:13:06 -08002582 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002583 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2584 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2585 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002586 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002587 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2588 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002589 // Don't apply window scale here since we don't want scale to affect raw
2590 // coordinates. The scale will be sent back to the client and applied
2591 // later when requesting relative coordinates.
2592 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2593 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002594 }
2595 usingCoords = scaledCoords;
2596 }
2597 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002598 // We don't want the dispatch target to know.
2599 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2600 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2601 scaledCoords[i].clear();
2602 }
2603 usingCoords = scaledCoords;
2604 }
2605 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002606
2607 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002608
2609 // Publish the motion event.
2610 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002611 .publishMotionEvent(dispatchEntry->seq,
2612 dispatchEntry->resolvedEventId,
2613 motionEntry->deviceId, motionEntry->source,
2614 motionEntry->displayId, std::move(hmac),
2615 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002616 motionEntry->actionButton,
2617 dispatchEntry->resolvedFlags,
2618 motionEntry->edgeFlags, motionEntry->metaState,
2619 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002620 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002621 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002622 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002623 motionEntry->yPrecision,
2624 motionEntry->xCursorPosition,
2625 motionEntry->yCursorPosition,
2626 motionEntry->downTime, motionEntry->eventTime,
2627 motionEntry->pointerCount,
2628 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002629 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002630 break;
2631 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002632 case EventEntry::Type::FOCUS: {
2633 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2634 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002635 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002636 focusEntry->hasFocus,
2637 mInTouchMode);
2638 break;
2639 }
2640
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002641 case EventEntry::Type::CONFIGURATION_CHANGED:
2642 case EventEntry::Type::DEVICE_RESET: {
2643 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2644 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002645 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 }
2648
2649 // Check the result.
2650 if (status) {
2651 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002652 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002654 "This is unexpected because the wait queue is empty, so the pipe "
2655 "should be empty and we shouldn't have any problems writing an "
2656 "event to it, status=%d",
2657 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2659 } else {
2660 // Pipe is full and we are waiting for the app to finish process some events
2661 // before sending more events to it.
2662#if DEBUG_DISPATCH_CYCLE
2663 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002664 "waiting for the application to catch up",
2665 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002666#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667 }
2668 } else {
2669 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002670 "status=%d",
2671 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2673 }
2674 return;
2675 }
2676
2677 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002678 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2679 connection->outboundQueue.end(),
2680 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002681 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002682 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002683 if (connection->responsive) {
2684 mAnrTracker.insert(dispatchEntry->timeoutTime,
2685 connection->inputChannel->getConnectionToken());
2686 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002687 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688 }
2689}
2690
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002691const std::array<uint8_t, 32> InputDispatcher::getSignature(
2692 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2693 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2694 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2695 // Only sign events up and down events as the purely move events
2696 // are tied to their up/down counterparts so signing would be redundant.
2697 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2698 verifiedEvent.actionMasked = actionMasked;
2699 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2700 return mHmacKeyManager.sign(verifiedEvent);
2701 }
2702 return INVALID_HMAC;
2703}
2704
2705const std::array<uint8_t, 32> InputDispatcher::getSignature(
2706 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2707 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2708 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2709 verifiedEvent.action = dispatchEntry.resolvedAction;
2710 return mHmacKeyManager.sign(verifiedEvent);
2711}
2712
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002714 const sp<Connection>& connection, uint32_t seq,
2715 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716#if DEBUG_DISPATCH_CYCLE
2717 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002718 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719#endif
2720
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002721 if (connection->status == Connection::STATUS_BROKEN ||
2722 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723 return;
2724 }
2725
2726 // Notify other system components and prepare to start the next dispatch cycle.
2727 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2728}
2729
2730void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002731 const sp<Connection>& connection,
2732 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733#if DEBUG_DISPATCH_CYCLE
2734 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002735 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736#endif
2737
2738 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002739 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002740 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002741 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002742 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743
2744 // The connection appears to be unrecoverably broken.
2745 // Ignore already broken or zombie connections.
2746 if (connection->status == Connection::STATUS_NORMAL) {
2747 connection->status = Connection::STATUS_BROKEN;
2748
2749 if (notify) {
2750 // Notify other system components.
2751 onDispatchCycleBrokenLocked(currentTime, connection);
2752 }
2753 }
2754}
2755
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002756void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2757 while (!queue.empty()) {
2758 DispatchEntry* dispatchEntry = queue.front();
2759 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002760 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761 }
2762}
2763
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002764void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002766 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002767 }
2768 delete dispatchEntry;
2769}
2770
2771int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2772 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2773
2774 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002775 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002777 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002779 "fd=%d, events=0x%x",
2780 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781 return 0; // remove the callback
2782 }
2783
2784 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002785 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2787 if (!(events & ALOOPER_EVENT_INPUT)) {
2788 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002789 "events=0x%x",
2790 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791 return 1;
2792 }
2793
2794 nsecs_t currentTime = now();
2795 bool gotOne = false;
2796 status_t status;
2797 for (;;) {
2798 uint32_t seq;
2799 bool handled;
2800 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2801 if (status) {
2802 break;
2803 }
2804 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2805 gotOne = true;
2806 }
2807 if (gotOne) {
2808 d->runCommandsLockedInterruptible();
2809 if (status == WOULD_BLOCK) {
2810 return 1;
2811 }
2812 }
2813
2814 notify = status != DEAD_OBJECT || !connection->monitor;
2815 if (notify) {
2816 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002817 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 }
2819 } else {
2820 // Monitor channels are never explicitly unregistered.
2821 // We do it automatically when the remote endpoint is closed so don't warn
2822 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002823 const bool stillHaveWindowHandle =
2824 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2825 nullptr;
2826 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827 if (notify) {
2828 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002829 "events=0x%x",
2830 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 }
2832 }
2833
2834 // Unregister the channel.
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002835 d->unregisterInputChannelLocked(*connection->inputChannel, notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002837 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838}
2839
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002840void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002841 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002842 for (const auto& pair : mConnectionsByFd) {
2843 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844 }
2845}
2846
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002847void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002848 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002849 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2850 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2851}
2852
2853void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2854 const CancelationOptions& options,
2855 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2856 for (const auto& it : monitorsByDisplay) {
2857 const std::vector<Monitor>& monitors = it.second;
2858 for (const Monitor& monitor : monitors) {
2859 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002860 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002861 }
2862}
2863
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002865 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002866 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002867 if (connection == nullptr) {
2868 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002869 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002870
2871 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872}
2873
2874void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2875 const sp<Connection>& connection, const CancelationOptions& options) {
2876 if (connection->status == Connection::STATUS_BROKEN) {
2877 return;
2878 }
2879
2880 nsecs_t currentTime = now();
2881
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002882 std::vector<EventEntry*> cancelationEvents =
2883 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002885 if (cancelationEvents.empty()) {
2886 return;
2887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002889 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2890 "with reality: %s, mode=%d.",
2891 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2892 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002894
2895 InputTarget target;
2896 sp<InputWindowHandle> windowHandle =
2897 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2898 if (windowHandle != nullptr) {
2899 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002900 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002901 target.globalScaleFactor = windowInfo->globalScaleFactor;
2902 }
2903 target.inputChannel = connection->inputChannel;
2904 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2905
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002906 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2907 EventEntry* cancelationEventEntry = cancelationEvents[i];
2908 switch (cancelationEventEntry->type) {
2909 case EventEntry::Type::KEY: {
2910 logOutboundKeyDetails("cancel - ",
2911 static_cast<const KeyEntry&>(*cancelationEventEntry));
2912 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002914 case EventEntry::Type::MOTION: {
2915 logOutboundMotionDetails("cancel - ",
2916 static_cast<const MotionEntry&>(*cancelationEventEntry));
2917 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002919 case EventEntry::Type::FOCUS: {
2920 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2921 break;
2922 }
2923 case EventEntry::Type::CONFIGURATION_CHANGED:
2924 case EventEntry::Type::DEVICE_RESET: {
2925 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2926 EventEntry::typeToString(cancelationEventEntry->type));
2927 break;
2928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 }
2930
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002931 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2932 target, InputTarget::FLAG_DISPATCH_AS_IS);
2933
2934 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002936
2937 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938}
2939
Svet Ganov5d3bc372020-01-26 23:11:07 -08002940void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2941 const sp<Connection>& connection) {
2942 if (connection->status == Connection::STATUS_BROKEN) {
2943 return;
2944 }
2945
2946 nsecs_t currentTime = now();
2947
2948 std::vector<EventEntry*> downEvents =
2949 connection->inputState.synthesizePointerDownEvents(currentTime);
2950
2951 if (downEvents.empty()) {
2952 return;
2953 }
2954
2955#if DEBUG_OUTBOUND_EVENT_DETAILS
2956 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2957 connection->getInputChannelName().c_str(), downEvents.size());
2958#endif
2959
2960 InputTarget target;
2961 sp<InputWindowHandle> windowHandle =
2962 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2963 if (windowHandle != nullptr) {
2964 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002965 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002966 target.globalScaleFactor = windowInfo->globalScaleFactor;
2967 }
2968 target.inputChannel = connection->inputChannel;
2969 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2970
2971 for (EventEntry* downEventEntry : downEvents) {
2972 switch (downEventEntry->type) {
2973 case EventEntry::Type::MOTION: {
2974 logOutboundMotionDetails("down - ",
2975 static_cast<const MotionEntry&>(*downEventEntry));
2976 break;
2977 }
2978
2979 case EventEntry::Type::KEY:
2980 case EventEntry::Type::FOCUS:
2981 case EventEntry::Type::CONFIGURATION_CHANGED:
2982 case EventEntry::Type::DEVICE_RESET: {
2983 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2984 EventEntry::typeToString(downEventEntry->type));
2985 break;
2986 }
2987 }
2988
2989 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2990 target, InputTarget::FLAG_DISPATCH_AS_IS);
2991
2992 downEventEntry->release();
2993 }
2994
2995 startDispatchCycleLocked(currentTime, connection);
2996}
2997
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002998MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002999 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000 ALOG_ASSERT(pointerIds.value != 0);
3001
3002 uint32_t splitPointerIndexMap[MAX_POINTERS];
3003 PointerProperties splitPointerProperties[MAX_POINTERS];
3004 PointerCoords splitPointerCoords[MAX_POINTERS];
3005
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003006 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007 uint32_t splitPointerCount = 0;
3008
3009 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003010 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003012 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013 uint32_t pointerId = uint32_t(pointerProperties.id);
3014 if (pointerIds.hasBit(pointerId)) {
3015 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3016 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3017 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003018 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019 splitPointerCount += 1;
3020 }
3021 }
3022
3023 if (splitPointerCount != pointerIds.count()) {
3024 // This is bad. We are missing some of the pointers that we expected to deliver.
3025 // Most likely this indicates that we received an ACTION_MOVE events that has
3026 // different pointer ids than we expected based on the previous ACTION_DOWN
3027 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3028 // in this way.
3029 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003030 "we expected there to be %d pointers. This probably means we received "
3031 "a broken sequence of pointer ids from the input device.",
3032 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003033 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034 }
3035
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003036 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003038 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3039 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003040 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3041 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003042 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043 uint32_t pointerId = uint32_t(pointerProperties.id);
3044 if (pointerIds.hasBit(pointerId)) {
3045 if (pointerIds.count() == 1) {
3046 // The first/last pointer went down/up.
3047 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003048 ? AMOTION_EVENT_ACTION_DOWN
3049 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003050 } else {
3051 // A secondary pointer went down/up.
3052 uint32_t splitPointerIndex = 0;
3053 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3054 splitPointerIndex += 1;
3055 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003056 action = maskedAction |
3057 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058 }
3059 } else {
3060 // An unrelated pointer changed.
3061 action = AMOTION_EVENT_ACTION_MOVE;
3062 }
3063 }
3064
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003065 int32_t newId = mIdGenerator.nextId();
3066 if (ATRACE_ENABLED()) {
3067 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3068 ") to MotionEvent(id=0x%" PRIx32 ").",
3069 originalMotionEntry.id, newId);
3070 ATRACE_NAME(message.c_str());
3071 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003072 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003073 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3074 originalMotionEntry.source, originalMotionEntry.displayId,
3075 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003076 originalMotionEntry.actionButton, originalMotionEntry.flags,
3077 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3078 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3079 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3080 originalMotionEntry.xCursorPosition,
3081 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003082 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003084 if (originalMotionEntry.injectionState) {
3085 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 splitMotionEntry->injectionState->refCount += 1;
3087 }
3088
3089 return splitMotionEntry;
3090}
3091
3092void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3093#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003094 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095#endif
3096
3097 bool needWake;
3098 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003099 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100
Prabir Pradhan42611e02018-11-27 14:04:02 -08003101 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003102 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 needWake = enqueueInboundEventLocked(newEntry);
3104 } // release lock
3105
3106 if (needWake) {
3107 mLooper->wake();
3108 }
3109}
3110
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003111/**
3112 * If one of the meta shortcuts is detected, process them here:
3113 * Meta + Backspace -> generate BACK
3114 * Meta + Enter -> generate HOME
3115 * This will potentially overwrite keyCode and metaState.
3116 */
3117void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003118 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003119 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3120 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3121 if (keyCode == AKEYCODE_DEL) {
3122 newKeyCode = AKEYCODE_BACK;
3123 } else if (keyCode == AKEYCODE_ENTER) {
3124 newKeyCode = AKEYCODE_HOME;
3125 }
3126 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003127 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003128 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003129 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003130 keyCode = newKeyCode;
3131 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3132 }
3133 } else if (action == AKEY_EVENT_ACTION_UP) {
3134 // In order to maintain a consistent stream of up and down events, check to see if the key
3135 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3136 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003137 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003138 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003139 auto replacementIt = mReplacedKeys.find(replacement);
3140 if (replacementIt != mReplacedKeys.end()) {
3141 keyCode = replacementIt->second;
3142 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003143 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3144 }
3145 }
3146}
3147
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3149#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003150 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3151 "policyFlags=0x%x, action=0x%x, "
3152 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3153 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3154 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3155 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156#endif
3157 if (!validateKeyEvent(args->action)) {
3158 return;
3159 }
3160
3161 uint32_t policyFlags = args->policyFlags;
3162 int32_t flags = args->flags;
3163 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003164 // InputDispatcher tracks and generates key repeats on behalf of
3165 // whatever notifies it, so repeatCount should always be set to 0
3166 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3168 policyFlags |= POLICY_FLAG_VIRTUAL;
3169 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171 if (policyFlags & POLICY_FLAG_FUNCTION) {
3172 metaState |= AMETA_FUNCTION_ON;
3173 }
3174
3175 policyFlags |= POLICY_FLAG_TRUSTED;
3176
Michael Wright78f24442014-08-06 15:55:28 -07003177 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003178 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003179
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003181 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003182 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3183 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184
Michael Wright2b3c3302018-03-02 17:19:13 +00003185 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003187 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3188 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003189 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 bool needWake;
3193 { // acquire lock
3194 mLock.lock();
3195
3196 if (shouldSendKeyToInputFilterLocked(args)) {
3197 mLock.unlock();
3198
3199 policyFlags |= POLICY_FLAG_FILTERED;
3200 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3201 return; // event was consumed by the filter
3202 }
3203
3204 mLock.lock();
3205 }
3206
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003207 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003208 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 args->displayId, policyFlags, args->action, flags, keyCode,
3210 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211
3212 needWake = enqueueInboundEventLocked(newEntry);
3213 mLock.unlock();
3214 } // release lock
3215
3216 if (needWake) {
3217 mLooper->wake();
3218 }
3219}
3220
3221bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3222 return mInputFilterEnabled;
3223}
3224
3225void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3226#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003227 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3228 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003229 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3230 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003231 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003232 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3233 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3234 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3235 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236 for (uint32_t i = 0; i < args->pointerCount; i++) {
3237 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003238 "x=%f, y=%f, pressure=%f, size=%f, "
3239 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3240 "orientation=%f",
3241 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3242 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3243 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3244 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3245 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3246 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3247 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3248 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3249 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3250 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251 }
3252#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003253 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3254 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 return;
3256 }
3257
3258 uint32_t policyFlags = args->policyFlags;
3259 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003260
3261 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003262 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003263 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3264 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003265 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267
3268 bool needWake;
3269 { // acquire lock
3270 mLock.lock();
3271
3272 if (shouldSendMotionToInputFilterLocked(args)) {
3273 mLock.unlock();
3274
3275 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003276 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003277 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3278 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003279 args->metaState, args->buttonState, args->classification, transform,
3280 args->xPrecision, args->yPrecision, args->xCursorPosition,
3281 args->yCursorPosition, args->downTime, args->eventTime,
3282 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283
3284 policyFlags |= POLICY_FLAG_FILTERED;
3285 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3286 return; // event was consumed by the filter
3287 }
3288
3289 mLock.lock();
3290 }
3291
3292 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003293 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003294 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003295 args->displayId, policyFlags, args->action, args->actionButton,
3296 args->flags, args->metaState, args->buttonState,
3297 args->classification, args->edgeFlags, args->xPrecision,
3298 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3299 args->downTime, args->pointerCount, args->pointerProperties,
3300 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301
3302 needWake = enqueueInboundEventLocked(newEntry);
3303 mLock.unlock();
3304 } // release lock
3305
3306 if (needWake) {
3307 mLooper->wake();
3308 }
3309}
3310
3311bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003312 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313}
3314
3315void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3316#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003317 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 "switchMask=0x%08x",
3319 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320#endif
3321
3322 uint32_t policyFlags = args->policyFlags;
3323 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003324 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325}
3326
3327void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3328#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3330 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331#endif
3332
3333 bool needWake;
3334 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003335 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336
Prabir Pradhan42611e02018-11-27 14:04:02 -08003337 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003338 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339 needWake = enqueueInboundEventLocked(newEntry);
3340 } // release lock
3341
3342 if (needWake) {
3343 mLooper->wake();
3344 }
3345}
3346
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3348 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003349 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350#if DEBUG_INBOUND_EVENT_DETAILS
3351 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003352 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3353 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354#endif
3355
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003356 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357
3358 policyFlags |= POLICY_FLAG_INJECTED;
3359 if (hasInjectionPermission(injectorPid, injectorUid)) {
3360 policyFlags |= POLICY_FLAG_TRUSTED;
3361 }
3362
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003363 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003365 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003366 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3367 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003368 if (!validateKeyEvent(action)) {
3369 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003372 int32_t flags = incomingKey.getFlags();
3373 int32_t keyCode = incomingKey.getKeyCode();
3374 int32_t metaState = incomingKey.getMetaState();
3375 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003376 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003377 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003378 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003379 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3380 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3381 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003383 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3384 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003385 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003386
3387 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3388 android::base::Timer t;
3389 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3390 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3391 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3392 std::to_string(t.duration().count()).c_str());
3393 }
3394 }
3395
3396 mLock.lock();
3397 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003398 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3399 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003400 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3401 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003402 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003403 injectedEntries.push(injectedEntry);
3404 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 }
3406
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003407 case AINPUT_EVENT_TYPE_MOTION: {
3408 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3409 int32_t action = motionEvent->getAction();
3410 size_t pointerCount = motionEvent->getPointerCount();
3411 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3412 int32_t actionButton = motionEvent->getActionButton();
3413 int32_t displayId = motionEvent->getDisplayId();
3414 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3415 return INPUT_EVENT_INJECTION_FAILED;
3416 }
3417
3418 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3419 nsecs_t eventTime = motionEvent->getEventTime();
3420 android::base::Timer t;
3421 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3422 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3423 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3424 std::to_string(t.duration().count()).c_str());
3425 }
3426 }
3427
3428 mLock.lock();
3429 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3430 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3431 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003432 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3433 motionEvent->getSource(), motionEvent->getDisplayId(),
3434 policyFlags, action, actionButton, motionEvent->getFlags(),
3435 motionEvent->getMetaState(), motionEvent->getButtonState(),
3436 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3437 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003438 motionEvent->getRawXCursorPosition(),
3439 motionEvent->getRawYCursorPosition(),
3440 motionEvent->getDownTime(), uint32_t(pointerCount),
3441 pointerProperties, samplePointerCoords,
3442 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003443 injectedEntries.push(injectedEntry);
3444 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3445 sampleEventTimes += 1;
3446 samplePointerCoords += pointerCount;
3447 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003448 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003449 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003450 motionEvent->getDisplayId(), policyFlags, action,
3451 actionButton, motionEvent->getFlags(),
3452 motionEvent->getMetaState(), motionEvent->getButtonState(),
3453 motionEvent->getClassification(),
3454 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3455 motionEvent->getYPrecision(),
3456 motionEvent->getRawXCursorPosition(),
3457 motionEvent->getRawYCursorPosition(),
3458 motionEvent->getDownTime(), uint32_t(pointerCount),
3459 pointerProperties, samplePointerCoords,
3460 motionEvent->getXOffset(), motionEvent->getYOffset());
3461 injectedEntries.push(nextInjectedEntry);
3462 }
3463 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003464 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003466 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003467 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003468 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469 }
3470
3471 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3472 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3473 injectionState->injectionIsAsync = true;
3474 }
3475
3476 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003477 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478
3479 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003480 while (!injectedEntries.empty()) {
3481 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3482 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 }
3484
3485 mLock.unlock();
3486
3487 if (needWake) {
3488 mLooper->wake();
3489 }
3490
3491 int32_t injectionResult;
3492 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003493 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494
3495 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3496 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3497 } else {
3498 for (;;) {
3499 injectionResult = injectionState->injectionResult;
3500 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3501 break;
3502 }
3503
3504 nsecs_t remainingTimeout = endTime - now();
3505 if (remainingTimeout <= 0) {
3506#if DEBUG_INJECTION
3507 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003508 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509#endif
3510 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3511 break;
3512 }
3513
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003514 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515 }
3516
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003517 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3518 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519 while (injectionState->pendingForegroundDispatches != 0) {
3520#if DEBUG_INJECTION
3521 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003522 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523#endif
3524 nsecs_t remainingTimeout = endTime - now();
3525 if (remainingTimeout <= 0) {
3526#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003527 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3528 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529#endif
3530 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3531 break;
3532 }
3533
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003534 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 }
3536 }
3537 }
3538
3539 injectionState->release();
3540 } // release lock
3541
3542#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003543 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003544 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545#endif
3546
3547 return injectionResult;
3548}
3549
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003550std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003551 std::array<uint8_t, 32> calculatedHmac;
3552 std::unique_ptr<VerifiedInputEvent> result;
3553 switch (event.getType()) {
3554 case AINPUT_EVENT_TYPE_KEY: {
3555 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3556 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3557 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3558 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3559 break;
3560 }
3561 case AINPUT_EVENT_TYPE_MOTION: {
3562 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3563 VerifiedMotionEvent verifiedMotionEvent =
3564 verifiedMotionEventFromMotionEvent(motionEvent);
3565 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3566 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3567 break;
3568 }
3569 default: {
3570 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3571 return nullptr;
3572 }
3573 }
3574 if (calculatedHmac == INVALID_HMAC) {
3575 return nullptr;
3576 }
3577 if (calculatedHmac != event.getHmac()) {
3578 return nullptr;
3579 }
3580 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003581}
3582
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003584 return injectorUid == 0 ||
3585 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586}
3587
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003588void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 InjectionState* injectionState = entry->injectionState;
3590 if (injectionState) {
3591#if DEBUG_INJECTION
3592 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003593 "injectorPid=%d, injectorUid=%d",
3594 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595#endif
3596
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003597 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 // Log the outcome since the injector did not wait for the injection result.
3599 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003600 case INPUT_EVENT_INJECTION_SUCCEEDED:
3601 ALOGV("Asynchronous input event injection succeeded.");
3602 break;
3603 case INPUT_EVENT_INJECTION_FAILED:
3604 ALOGW("Asynchronous input event injection failed.");
3605 break;
3606 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3607 ALOGW("Asynchronous input event injection permission denied.");
3608 break;
3609 case INPUT_EVENT_INJECTION_TIMED_OUT:
3610 ALOGW("Asynchronous input event injection timed out.");
3611 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 }
3613 }
3614
3615 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003616 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
3618}
3619
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003620void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 InjectionState* injectionState = entry->injectionState;
3622 if (injectionState) {
3623 injectionState->pendingForegroundDispatches += 1;
3624 }
3625}
3626
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003627void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628 InjectionState* injectionState = entry->injectionState;
3629 if (injectionState) {
3630 injectionState->pendingForegroundDispatches -= 1;
3631
3632 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003633 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 }
3635 }
3636}
3637
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003638std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3639 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003640 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003641}
3642
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003644 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003645 if (windowHandleToken == nullptr) {
3646 return nullptr;
3647 }
3648
Arthur Hungb92218b2018-08-14 12:00:21 +08003649 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003650 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3651 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003652 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003653 return windowHandle;
3654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655 }
3656 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003657 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658}
3659
Mady Mellor017bcd12020-06-23 19:12:00 +00003660bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3661 for (auto& it : mWindowHandlesByDisplay) {
3662 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3663 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003664 if (handle->getId() == windowHandle->getId() &&
3665 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003666 if (windowHandle->getInfo()->displayId != it.first) {
3667 ALOGE("Found window %s in display %" PRId32
3668 ", but it should belong to display %" PRId32,
3669 windowHandle->getName().c_str(), it.first,
3670 windowHandle->getInfo()->displayId);
3671 }
3672 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 }
3675 }
3676 return false;
3677}
3678
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003679bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3680 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3681 const bool noInputChannel =
3682 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3683 if (connection != nullptr && noInputChannel) {
3684 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3685 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3686 return false;
3687 }
3688
3689 if (connection == nullptr) {
3690 if (!noInputChannel) {
3691 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3692 }
3693 return false;
3694 }
3695 if (!connection->responsive) {
3696 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3697 return false;
3698 }
3699 return true;
3700}
3701
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003702std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3703 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003704 size_t count = mInputChannelsByToken.count(token);
3705 if (count == 0) {
3706 return nullptr;
3707 }
3708 return mInputChannelsByToken.at(token);
3709}
3710
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003711void InputDispatcher::updateWindowHandlesForDisplayLocked(
3712 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3713 if (inputWindowHandles.empty()) {
3714 // Remove all handles on a display if there are no windows left.
3715 mWindowHandlesByDisplay.erase(displayId);
3716 return;
3717 }
3718
3719 // Since we compare the pointer of input window handles across window updates, we need
3720 // to make sure the handle object for the same window stays unchanged across updates.
3721 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003722 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003723 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003724 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003725 }
3726
3727 std::vector<sp<InputWindowHandle>> newHandles;
3728 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3729 if (!handle->updateInfo()) {
3730 // handle no longer valid
3731 continue;
3732 }
3733
3734 const InputWindowInfo* info = handle->getInfo();
3735 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3736 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3737 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003738 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3739 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3740 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003741 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003742 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003743 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003744 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003745 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003746 }
3747
3748 if (info->displayId != displayId) {
3749 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3750 handle->getName().c_str(), displayId, info->displayId);
3751 continue;
3752 }
3753
Robert Carredd13602020-04-13 17:24:34 -07003754 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3755 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003756 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003757 oldHandle->updateFrom(handle);
3758 newHandles.push_back(oldHandle);
3759 } else {
3760 newHandles.push_back(handle);
3761 }
3762 }
3763
3764 // Insert or replace
3765 mWindowHandlesByDisplay[displayId] = newHandles;
3766}
3767
Arthur Hung72d8dc32020-03-28 00:48:39 +00003768void InputDispatcher::setInputWindows(
3769 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3770 { // acquire lock
3771 std::scoped_lock _l(mLock);
3772 for (auto const& i : handlesPerDisplay) {
3773 setInputWindowsLocked(i.second, i.first);
3774 }
3775 }
3776 // Wake up poll loop since it may need to make new input dispatching choices.
3777 mLooper->wake();
3778}
3779
Arthur Hungb92218b2018-08-14 12:00:21 +08003780/**
3781 * Called from InputManagerService, update window handle list by displayId that can receive input.
3782 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3783 * If set an empty list, remove all handles from the specific display.
3784 * For focused handle, check if need to change and send a cancel event to previous one.
3785 * For removed handle, check if need to send a cancel event if already in touch.
3786 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003787void InputDispatcher::setInputWindowsLocked(
3788 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003789 if (DEBUG_FOCUS) {
3790 std::string windowList;
3791 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3792 windowList += iwh->getName() + " ";
3793 }
3794 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003797 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3798 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3799 const bool noInputWindow =
3800 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3801 if (noInputWindow && window->getToken() != nullptr) {
3802 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3803 window->getName().c_str());
3804 window->releaseChannel();
3805 }
3806 }
3807
Arthur Hung72d8dc32020-03-28 00:48:39 +00003808 // Copy old handles for release if they are no longer present.
3809 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810
Arthur Hung72d8dc32020-03-28 00:48:39 +00003811 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003812
Arthur Hung72d8dc32020-03-28 00:48:39 +00003813 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3814 bool foundHoveredWindow = false;
3815 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3816 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3817 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3818 windowHandle->getInfo()->visible) {
3819 newFocusedWindowHandle = windowHandle;
3820 }
3821 if (windowHandle == mLastHoverWindowHandle) {
3822 foundHoveredWindow = true;
3823 }
3824 }
3825
3826 if (!foundHoveredWindow) {
3827 mLastHoverWindowHandle = nullptr;
3828 }
3829
3830 sp<InputWindowHandle> oldFocusedWindowHandle =
3831 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3832
3833 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07003834 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle, displayId,
3835 "setInputWindowsLocked");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003838 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3839 mTouchStatesByDisplay.find(displayId);
3840 if (stateIt != mTouchStatesByDisplay.end()) {
3841 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003842 for (size_t i = 0; i < state.windows.size();) {
3843 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003844 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003845 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003846 ALOGD("Touched window was removed: %s in display %" PRId32,
3847 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003848 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003849 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003850 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3851 if (touchedInputChannel != nullptr) {
3852 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3853 "touched window was removed");
3854 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003856 state.windows.erase(state.windows.begin() + i);
3857 } else {
3858 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859 }
3860 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003861 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003862
Arthur Hung72d8dc32020-03-28 00:48:39 +00003863 // Release information for windows that are no longer present.
3864 // This ensures that unused input channels are released promptly.
3865 // Otherwise, they might stick around until the window handle is destroyed
3866 // which might not happen until the next GC.
3867 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003868 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003869 if (DEBUG_FOCUS) {
3870 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003871 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003872 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003873 }
chaviw291d88a2019-02-14 10:33:58 -08003874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875}
3876
3877void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07003878 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003879 if (DEBUG_FOCUS) {
3880 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3881 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3882 }
Chris Yea209fde2020-07-22 13:54:51 -07003883 if (inputApplicationHandle != nullptr &&
3884 inputApplicationHandle->getApplicationToken() != nullptr) {
3885 // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003886 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887
Chris Yea209fde2020-07-22 13:54:51 -07003888 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08003889 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003890
Chris Yea209fde2020-07-22 13:54:51 -07003891 // If oldFocusedApplicationHandle already exists
3892 if (oldFocusedApplicationHandle != nullptr) {
3893 // If a new focused application handle is different from the old one and
3894 // old focus application info is awaited focused application info.
3895 if (*oldFocusedApplicationHandle != *inputApplicationHandle &&
3896 mAwaitedFocusedApplication != nullptr &&
3897 *oldFocusedApplicationHandle == *mAwaitedFocusedApplication) {
3898 resetNoFocusedWindowTimeoutLocked();
3899 }
3900 // Erase the old application from container first
3901 mFocusedApplicationHandlesByDisplay.erase(displayId);
3902 // Should already get freed after removed from container but just double check.
3903 oldFocusedApplicationHandle.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003904 }
3905
Chris Yea209fde2020-07-22 13:54:51 -07003906 // Set the new application handle.
3907 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 } // release lock
3909
3910 // Wake up poll loop since it may need to make new input dispatching choices.
3911 mLooper->wake();
3912}
3913
Tiger Huang721e26f2018-07-24 22:26:19 +08003914/**
3915 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3916 * the display not specified.
3917 *
3918 * We track any unreleased events for each window. If a window loses the ability to receive the
3919 * released event, we will send a cancel event to it. So when the focused display is changed, we
3920 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3921 * display. The display-specified events won't be affected.
3922 */
3923void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003924 if (DEBUG_FOCUS) {
3925 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3926 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003927 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003928 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003929
3930 if (mFocusedDisplayId != displayId) {
3931 sp<InputWindowHandle> oldFocusedWindowHandle =
3932 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3933 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003934 std::shared_ptr<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003935 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003936 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003937 CancelationOptions
3938 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3939 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003940 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003941 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3942 }
3943 }
3944 mFocusedDisplayId = displayId;
3945
3946 // Sanity check
3947 sp<InputWindowHandle> newFocusedWindowHandle =
3948 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07003949 notifyFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003950
Tiger Huang721e26f2018-07-24 22:26:19 +08003951 if (newFocusedWindowHandle == nullptr) {
3952 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3953 if (!mFocusedWindowHandlesByDisplay.empty()) {
3954 ALOGE("But another display has a focused window:");
3955 for (auto& it : mFocusedWindowHandlesByDisplay) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003956 const sp<InputWindowHandle>& windowHandle = it.second;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05003957 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", it.first,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003958 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003959 }
3960 }
3961 }
3962 }
3963
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003964 if (DEBUG_FOCUS) {
3965 logDispatchStateLocked();
3966 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003967 } // release lock
3968
3969 // Wake up poll loop since it may need to make new input dispatching choices.
3970 mLooper->wake();
3971}
3972
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003974 if (DEBUG_FOCUS) {
3975 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977
3978 bool changed;
3979 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003980 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981
3982 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3983 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003984 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985 }
3986
3987 if (mDispatchEnabled && !enabled) {
3988 resetAndDropEverythingLocked("dispatcher is being disabled");
3989 }
3990
3991 mDispatchEnabled = enabled;
3992 mDispatchFrozen = frozen;
3993 changed = true;
3994 } else {
3995 changed = false;
3996 }
3997
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003998 if (DEBUG_FOCUS) {
3999 logDispatchStateLocked();
4000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001 } // release lock
4002
4003 if (changed) {
4004 // Wake up poll loop since it may need to make new input dispatching choices.
4005 mLooper->wake();
4006 }
4007}
4008
4009void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004010 if (DEBUG_FOCUS) {
4011 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4012 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013
4014 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004015 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016
4017 if (mInputFilterEnabled == enabled) {
4018 return;
4019 }
4020
4021 mInputFilterEnabled = enabled;
4022 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4023 } // release lock
4024
4025 // Wake up poll loop since there might be work to do to drop everything.
4026 mLooper->wake();
4027}
4028
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004029void InputDispatcher::setInTouchMode(bool inTouchMode) {
4030 std::scoped_lock lock(mLock);
4031 mInTouchMode = inTouchMode;
4032}
4033
chaviwfbe5d9c2018-12-26 12:23:37 -08004034bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4035 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004036 if (DEBUG_FOCUS) {
4037 ALOGD("Trivial transfer to same window.");
4038 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004039 return true;
4040 }
4041
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004043 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044
chaviwfbe5d9c2018-12-26 12:23:37 -08004045 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4046 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004047 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004048 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049 return false;
4050 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004051 if (DEBUG_FOCUS) {
4052 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4053 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004056 if (DEBUG_FOCUS) {
4057 ALOGD("Cannot transfer focus because windows are on different displays.");
4058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059 return false;
4060 }
4061
4062 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004063 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4064 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004065 for (size_t i = 0; i < state.windows.size(); i++) {
4066 const TouchedWindow& touchedWindow = state.windows[i];
4067 if (touchedWindow.windowHandle == fromWindowHandle) {
4068 int32_t oldTargetFlags = touchedWindow.targetFlags;
4069 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004071 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004073 int32_t newTargetFlags = oldTargetFlags &
4074 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4075 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004076 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077
Jeff Brownf086ddb2014-02-11 14:28:48 -08004078 found = true;
4079 goto Found;
4080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081 }
4082 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004083 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004085 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004086 if (DEBUG_FOCUS) {
4087 ALOGD("Focus transfer failed because from window did not have focus.");
4088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 return false;
4090 }
4091
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004092 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4093 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004094 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004095 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004096 CancelationOptions
4097 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4098 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004100 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101 }
4102
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004103 if (DEBUG_FOCUS) {
4104 logDispatchStateLocked();
4105 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 } // release lock
4107
4108 // Wake up poll loop since it may need to make new input dispatching choices.
4109 mLooper->wake();
4110 return true;
4111}
4112
4113void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004114 if (DEBUG_FOCUS) {
4115 ALOGD("Resetting and dropping all events (%s).", reason);
4116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117
4118 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4119 synthesizeCancelationEventsForAllConnectionsLocked(options);
4120
4121 resetKeyRepeatLocked();
4122 releasePendingEventLocked();
4123 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004124 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004126 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004127 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004129 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130}
4131
4132void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004133 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 dumpDispatchStateLocked(dump);
4135
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004136 std::istringstream stream(dump);
4137 std::string line;
4138
4139 while (std::getline(stream, line, '\n')) {
4140 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 }
4142}
4143
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004144void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004145 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4146 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4147 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004148 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149
Tiger Huang721e26f2018-07-24 22:26:19 +08004150 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4151 dump += StringPrintf(INDENT "FocusedApplications:\n");
4152 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4153 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004154 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004155 const int64_t timeoutMillis = millis(
4156 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004157 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004158 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004159 displayId, applicationHandle->getName().c_str(), timeoutMillis);
Tiger Huang721e26f2018-07-24 22:26:19 +08004160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004162 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004164
4165 if (!mFocusedWindowHandlesByDisplay.empty()) {
4166 dump += StringPrintf(INDENT "FocusedWindows:\n");
4167 for (auto& it : mFocusedWindowHandlesByDisplay) {
4168 const int32_t displayId = it.first;
4169 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004170 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4171 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004172 }
4173 } else {
4174 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004177 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004178 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004179 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4180 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004181 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004182 state.displayId, toString(state.down), toString(state.split),
4183 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004184 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004185 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004186 for (size_t i = 0; i < state.windows.size(); i++) {
4187 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004188 dump += StringPrintf(INDENT4
4189 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4190 i, touchedWindow.windowHandle->getName().c_str(),
4191 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004192 }
4193 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004194 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004195 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004196 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004197 dump += INDENT3 "Portal windows:\n";
4198 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004199 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004200 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4201 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004202 }
4203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 }
4205 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004206 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 }
4208
Arthur Hungb92218b2018-08-14 12:00:21 +08004209 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004210 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004211 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004212 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004213 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004214 dump += INDENT2 "Windows:\n";
4215 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004216 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004217 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218
Arthur Hungb92218b2018-08-14 12:00:21 +08004219 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004220 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004221 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004222 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004223 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004224 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004225 i, windowInfo->name.c_str(), windowInfo->displayId,
4226 windowInfo->portalToDisplayId,
4227 toString(windowInfo->paused),
4228 toString(windowInfo->hasFocus),
4229 toString(windowInfo->hasWallpaper),
4230 toString(windowInfo->visible),
4231 toString(windowInfo->canReceiveKeys),
Michael Wright8759d672020-07-21 00:46:45 +01004232 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004233 static_cast<int32_t>(windowInfo->type),
4234 windowInfo->frameLeft, windowInfo->frameTop,
4235 windowInfo->frameRight, windowInfo->frameBottom,
chaviw1ff3d1e2020-07-01 15:53:47 -07004236 windowInfo->globalScaleFactor);
Arthur Hungb92218b2018-08-14 12:00:21 +08004237 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004238 dump += StringPrintf(", inputFeatures=%s",
4239 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004240 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4241 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004242 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004243 millis(windowInfo->dispatchingTimeout));
chaviw1ff3d1e2020-07-01 15:53:47 -07004244 windowInfo->transform.dump(dump, INDENT4 "transform=");
Arthur Hungb92218b2018-08-14 12:00:21 +08004245 }
4246 } else {
4247 dump += INDENT2 "Windows: <none>\n";
4248 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 }
4250 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004251 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 }
4253
Michael Wright3dd60e22019-03-27 22:06:44 +00004254 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004255 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004256 const std::vector<Monitor>& monitors = it.second;
4257 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4258 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004259 }
4260 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004261 const std::vector<Monitor>& monitors = it.second;
4262 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4263 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004266 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 }
4268
4269 nsecs_t currentTime = now();
4270
4271 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004272 if (!mRecentQueue.empty()) {
4273 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4274 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004275 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004277 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 }
4279 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004280 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 }
4282
4283 // Dump event currently being dispatched.
4284 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004285 dump += INDENT "PendingEvent:\n";
4286 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004288 dump += StringPrintf(", age=%" PRId64 "ms\n",
4289 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004291 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 }
4293
4294 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004295 if (!mInboundQueue.empty()) {
4296 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4297 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004298 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004300 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 }
4302 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004303 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 }
4305
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004306 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004307 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004308 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4309 const KeyReplacement& replacement = pair.first;
4310 int32_t newKeyCode = pair.second;
4311 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004312 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004313 }
4314 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004315 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004316 }
4317
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004318 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004319 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004320 for (const auto& pair : mConnectionsByFd) {
4321 const sp<Connection>& connection = pair.second;
4322 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004323 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004324 pair.first, connection->getInputChannelName().c_str(),
4325 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004326 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004328 if (!connection->outboundQueue.empty()) {
4329 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4330 connection->outboundQueue.size());
4331 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332 dump.append(INDENT4);
4333 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004334 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4335 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004336 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004337 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 }
4339 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004340 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 }
4342
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004343 if (!connection->waitQueue.empty()) {
4344 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4345 connection->waitQueue.size());
4346 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004347 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004349 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004350 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004351 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004352 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004353 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354 }
4355 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004356 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 }
4358 }
4359 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004360 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 }
4362
4363 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004364 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4365 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004367 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 }
4369
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004370 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004371 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4372 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4373 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374}
4375
Michael Wright3dd60e22019-03-27 22:06:44 +00004376void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4377 const size_t numMonitors = monitors.size();
4378 for (size_t i = 0; i < numMonitors; i++) {
4379 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004380 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004381 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4382 dump += "\n";
4383 }
4384}
4385
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004386status_t InputDispatcher::registerInputChannel(const std::shared_ptr<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004388 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389#endif
4390
4391 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004392 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004393 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004394 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004396 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397 return BAD_VALUE;
4398 }
4399
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004400 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401
4402 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004403 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004404 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4407 } // release lock
4408
4409 // Wake the looper because some connections have changed.
4410 mLooper->wake();
4411 return OK;
4412}
4413
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004414status_t InputDispatcher::registerInputMonitor(const std::shared_ptr<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004415 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004416 { // acquire lock
4417 std::scoped_lock _l(mLock);
4418
4419 if (displayId < 0) {
4420 ALOGW("Attempted to register input monitor without a specified display.");
4421 return BAD_VALUE;
4422 }
4423
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004424 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004425 ALOGW("Attempted to register input monitor without an identifying token.");
4426 return BAD_VALUE;
4427 }
4428
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004429 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004430
4431 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004432 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004433 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004434
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004435 auto& monitorsByDisplay =
4436 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004437 monitorsByDisplay[displayId].emplace_back(inputChannel);
4438
4439 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004440 }
4441 // Wake the looper because some connections have changed.
4442 mLooper->wake();
4443 return OK;
4444}
4445
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004446status_t InputDispatcher::unregisterInputChannel(const InputChannel& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447#if DEBUG_REGISTRATION
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004448 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449#endif
4450
4451 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004452 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453
4454 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4455 if (status) {
4456 return status;
4457 }
4458 } // release lock
4459
4460 // Wake the poll loop because removing the connection may have changed the current
4461 // synchronization state.
4462 mLooper->wake();
4463 return OK;
4464}
4465
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004466status_t InputDispatcher::unregisterInputChannelLocked(const InputChannel& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004467 bool notify) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004468 sp<Connection> connection = getConnectionLocked(inputChannel.getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004469 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004471 inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472 return BAD_VALUE;
4473 }
4474
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004475 removeConnectionLocked(connection);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004476 mInputChannelsByToken.erase(inputChannel.getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004477
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478 if (connection->monitor) {
4479 removeMonitorChannelLocked(inputChannel);
4480 }
4481
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004482 mLooper->removeFd(inputChannel.getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483
4484 nsecs_t currentTime = now();
4485 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4486
4487 connection->status = Connection::STATUS_ZOMBIE;
4488 return OK;
4489}
4490
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004491void InputDispatcher::removeMonitorChannelLocked(const InputChannel& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004492 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4493 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4494}
4495
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004496void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004497 const InputChannel& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004498 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004499 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004500 std::vector<Monitor>& monitors = it->second;
4501 const size_t numMonitors = monitors.size();
4502 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004503 if (*monitors[i].inputChannel == inputChannel) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004504 monitors.erase(monitors.begin() + i);
4505 break;
4506 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004507 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004508 if (monitors.empty()) {
4509 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004510 } else {
4511 ++it;
4512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513 }
4514}
4515
Michael Wright3dd60e22019-03-27 22:06:44 +00004516status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4517 { // acquire lock
4518 std::scoped_lock _l(mLock);
4519 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4520
4521 if (!foundDisplayId) {
4522 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4523 return BAD_VALUE;
4524 }
4525 int32_t displayId = foundDisplayId.value();
4526
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004527 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4528 mTouchStatesByDisplay.find(displayId);
4529 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004530 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4531 return BAD_VALUE;
4532 }
4533
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004534 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004535 std::optional<int32_t> foundDeviceId;
4536 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004537 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004538 foundDeviceId = state.deviceId;
4539 }
4540 }
4541 if (!foundDeviceId || !state.down) {
4542 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004543 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004544 return BAD_VALUE;
4545 }
4546 int32_t deviceId = foundDeviceId.value();
4547
4548 // Send cancel events to all the input channels we're stealing from.
4549 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004550 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004551 options.deviceId = deviceId;
4552 options.displayId = displayId;
4553 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004554 std::shared_ptr<InputChannel> channel =
4555 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004556 if (channel != nullptr) {
4557 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4558 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004559 }
4560 // Then clear the current touch state so we stop dispatching to them as well.
4561 state.filterNonMonitors();
4562 }
4563 return OK;
4564}
4565
Michael Wright3dd60e22019-03-27 22:06:44 +00004566std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4567 const sp<IBinder>& token) {
4568 for (const auto& it : mGestureMonitorsByDisplay) {
4569 const std::vector<Monitor>& monitors = it.second;
4570 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004571 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004572 return it.first;
4573 }
4574 }
4575 }
4576 return std::nullopt;
4577}
4578
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004579sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004580 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004581 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004582 }
4583
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004584 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004585 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004586 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004587 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588 }
4589 }
Robert Carr4e670e52018-08-15 13:26:12 -07004590
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004591 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592}
4593
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004594void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004595 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004596 removeByValue(mConnectionsByFd, connection);
4597}
4598
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004599void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4600 const sp<Connection>& connection, uint32_t seq,
4601 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004602 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4603 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604 commandEntry->connection = connection;
4605 commandEntry->eventTime = currentTime;
4606 commandEntry->seq = seq;
4607 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004608 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609}
4610
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004611void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4612 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004614 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004616 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4617 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004619 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620}
4621
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07004622void InputDispatcher::notifyFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
4623 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004624 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4625 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004626 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4627 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004628 commandEntry->oldToken = oldToken;
4629 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004630 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004631}
4632
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004633void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4634 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4635 // is already healthy again. Don't raise ANR in this situation
4636 if (connection->waitQueue.empty()) {
4637 ALOGI("Not raising ANR because the connection %s has recovered",
4638 connection->inputChannel->getName().c_str());
4639 return;
4640 }
4641 /**
4642 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4643 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4644 * has changed. This could cause newer entries to time out before the already dispatched
4645 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4646 * processes the events linearly. So providing information about the oldest entry seems to be
4647 * most useful.
4648 */
4649 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4650 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4651 std::string reason =
4652 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4653 connection->inputChannel->getName().c_str(),
4654 ns2ms(currentWait),
4655 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004657 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4658 reason);
4659
4660 std::unique_ptr<CommandEntry> commandEntry =
4661 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4662 commandEntry->inputApplicationHandle = nullptr;
4663 commandEntry->inputChannel = connection->inputChannel;
4664 commandEntry->reason = std::move(reason);
4665 postCommandLocked(std::move(commandEntry));
4666}
4667
Chris Yea209fde2020-07-22 13:54:51 -07004668void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004669 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4670 application->getName().c_str());
4671
4672 updateLastAnrStateLocked(application, reason);
4673
4674 std::unique_ptr<CommandEntry> commandEntry =
4675 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4676 commandEntry->inputApplicationHandle = application;
4677 commandEntry->inputChannel = nullptr;
4678 commandEntry->reason = std::move(reason);
4679 postCommandLocked(std::move(commandEntry));
4680}
4681
4682void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4683 const std::string& reason) {
4684 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4685 updateLastAnrStateLocked(windowLabel, reason);
4686}
4687
Chris Yea209fde2020-07-22 13:54:51 -07004688void InputDispatcher::updateLastAnrStateLocked(
4689 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004690 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4691 updateLastAnrStateLocked(windowLabel, reason);
4692}
4693
4694void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4695 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004697 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 struct tm tm;
4699 localtime_r(&t, &tm);
4700 char timestr[64];
4701 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004702 mLastAnrState.clear();
4703 mLastAnrState += INDENT "ANR:\n";
4704 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004705 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4706 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004707 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708}
4709
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004710void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 mLock.unlock();
4712
4713 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4714
4715 mLock.lock();
4716}
4717
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004718void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719 sp<Connection> connection = commandEntry->connection;
4720
4721 if (connection->status != Connection::STATUS_ZOMBIE) {
4722 mLock.unlock();
4723
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004724 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725
4726 mLock.lock();
4727 }
4728}
4729
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004730void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004731 sp<IBinder> oldToken = commandEntry->oldToken;
4732 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004733 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004734 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004735 mLock.lock();
4736}
4737
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004738void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004739 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004740 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741 mLock.unlock();
4742
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004743 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004744 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745
4746 mLock.lock();
4747
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004748 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004749 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4750 } else {
4751 // stop waking up for events in this connection, it is already not responding
4752 sp<Connection> connection = getConnectionLocked(token);
4753 if (connection == nullptr) {
4754 return;
4755 }
4756 cancelEventsForAnrLocked(connection);
4757 }
4758}
4759
Chris Yea209fde2020-07-22 13:54:51 -07004760void InputDispatcher::extendAnrTimeoutsLocked(
4761 const std::shared_ptr<InputApplicationHandle>& application,
4762 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004763 sp<Connection> connection = getConnectionLocked(connectionToken);
4764 if (connection == nullptr) {
4765 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4766 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004767 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004768 mAwaitedFocusedApplication = application;
4769 } else {
4770 // It's also possible that the connection already disappeared. No action necessary.
4771 }
4772 return;
4773 }
4774
4775 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004776 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004777
4778 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004779 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004780 for (DispatchEntry* entry : connection->waitQueue) {
4781 if (newTimeout >= entry->timeoutTime) {
4782 // Already removed old entries when connection was marked unresponsive
4783 entry->timeoutTime = newTimeout;
4784 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4785 }
4786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787}
4788
4789void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4790 CommandEntry* commandEntry) {
4791 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004792 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793
4794 mLock.unlock();
4795
Michael Wright2b3c3302018-03-02 17:19:13 +00004796 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004797 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004798 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004799 : nullptr;
4800 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004801 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4802 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004803 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805
4806 mLock.lock();
4807
4808 if (delay < 0) {
4809 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4810 } else if (!delay) {
4811 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4812 } else {
4813 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4814 entry->interceptKeyWakeupTime = now() + delay;
4815 }
4816 entry->release();
4817}
4818
chaviwfd6d3512019-03-25 13:23:49 -07004819void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4820 mLock.unlock();
4821 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4822 mLock.lock();
4823}
4824
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004825/**
4826 * Connection is responsive if it has no events in the waitQueue that are older than the
4827 * current time.
4828 */
4829static bool isConnectionResponsive(const Connection& connection) {
4830 const nsecs_t currentTime = now();
4831 for (const DispatchEntry* entry : connection.waitQueue) {
4832 if (entry->timeoutTime < currentTime) {
4833 return false;
4834 }
4835 }
4836 return true;
4837}
4838
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004839void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004841 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004843 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844
4845 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004846 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004847 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004848 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004850 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004851 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004852 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004853 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4854 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004855 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004856 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004857
4858 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004859 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004860 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4861 restartEvent =
4862 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004863 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004864 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4865 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4866 handled);
4867 } else {
4868 restartEvent = false;
4869 }
4870
4871 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004872 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004873 // contents of the wait queue to have been drained, so we need to double-check
4874 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004875 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4876 if (dispatchEntryIt != connection->waitQueue.end()) {
4877 dispatchEntry = *dispatchEntryIt;
4878 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004879 mAnrTracker.erase(dispatchEntry->timeoutTime,
4880 connection->inputChannel->getConnectionToken());
4881 if (!connection->responsive) {
4882 connection->responsive = isConnectionResponsive(*connection);
4883 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004884 traceWaitQueueLength(connection);
4885 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004886 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004887 traceOutboundQueueLength(connection);
4888 } else {
4889 releaseDispatchEntry(dispatchEntry);
4890 }
4891 }
4892
4893 // Start the next dispatch cycle for this connection.
4894 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895}
4896
4897bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004898 DispatchEntry* dispatchEntry,
4899 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004900 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004901 if (!handled) {
4902 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004903 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004904 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004905 return false;
4906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004908 // Get the fallback key state.
4909 // Clear it out after dispatching the UP.
4910 int32_t originalKeyCode = keyEntry->keyCode;
4911 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4912 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4913 connection->inputState.removeFallbackKey(originalKeyCode);
4914 }
4915
4916 if (handled || !dispatchEntry->hasForegroundTarget()) {
4917 // If the application handles the original key for which we previously
4918 // generated a fallback or if the window is not a foreground window,
4919 // then cancel the associated fallback key, if any.
4920 if (fallbackKeyCode != -1) {
4921 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004923 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004924 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4925 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4926 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004928 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004929 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930
4931 mLock.unlock();
4932
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004933 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004934 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935
4936 mLock.lock();
4937
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004938 // Cancel the fallback key.
4939 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004941 "application handled the original non-fallback key "
4942 "or is no longer a foreground target, "
4943 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 options.keyCode = fallbackKeyCode;
4945 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004947 connection->inputState.removeFallbackKey(originalKeyCode);
4948 }
4949 } else {
4950 // If the application did not handle a non-fallback key, first check
4951 // that we are in a good state to perform unhandled key event processing
4952 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004953 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004954 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004956 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004957 "since this is not an initial down. "
4958 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4959 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004961 return false;
4962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004964 // Dispatch the unhandled key to the policy.
4965#if DEBUG_OUTBOUND_EVENT_DETAILS
4966 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004967 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4968 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004969#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004970 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004971
4972 mLock.unlock();
4973
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004974 bool fallback =
4975 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4976 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004977
4978 mLock.lock();
4979
4980 if (connection->status != Connection::STATUS_NORMAL) {
4981 connection->inputState.removeFallbackKey(originalKeyCode);
4982 return false;
4983 }
4984
4985 // Latch the fallback keycode for this key on an initial down.
4986 // The fallback keycode cannot change at any other point in the lifecycle.
4987 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004989 fallbackKeyCode = event.getKeyCode();
4990 } else {
4991 fallbackKeyCode = AKEYCODE_UNKNOWN;
4992 }
4993 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4994 }
4995
4996 ALOG_ASSERT(fallbackKeyCode != -1);
4997
4998 // Cancel the fallback key if the policy decides not to send it anymore.
4999 // We will continue to dispatch the key to the policy but we will no
5000 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005001 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5002 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005003#if DEBUG_OUTBOUND_EVENT_DETAILS
5004 if (fallback) {
5005 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005006 "as a fallback for %d, but on the DOWN it had requested "
5007 "to send %d instead. Fallback canceled.",
5008 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005009 } else {
5010 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005011 "but on the DOWN it had requested to send %d. "
5012 "Fallback canceled.",
5013 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005014 }
5015#endif
5016
5017 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5018 "canceling fallback, policy no longer desires it");
5019 options.keyCode = fallbackKeyCode;
5020 synthesizeCancelationEventsForConnectionLocked(connection, options);
5021
5022 fallback = false;
5023 fallbackKeyCode = AKEYCODE_UNKNOWN;
5024 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005025 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005026 }
5027 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005028
5029#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005030 {
5031 std::string msg;
5032 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5033 connection->inputState.getFallbackKeys();
5034 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005035 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005037 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005038 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005039 }
5040#endif
5041
5042 if (fallback) {
5043 // Restart the dispatch cycle using the fallback key.
5044 keyEntry->eventTime = event.getEventTime();
5045 keyEntry->deviceId = event.getDeviceId();
5046 keyEntry->source = event.getSource();
5047 keyEntry->displayId = event.getDisplayId();
5048 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5049 keyEntry->keyCode = fallbackKeyCode;
5050 keyEntry->scanCode = event.getScanCode();
5051 keyEntry->metaState = event.getMetaState();
5052 keyEntry->repeatCount = event.getRepeatCount();
5053 keyEntry->downTime = event.getDownTime();
5054 keyEntry->syntheticRepeat = false;
5055
5056#if DEBUG_OUTBOUND_EVENT_DETAILS
5057 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005058 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5059 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005060#endif
5061 return true; // restart the event
5062 } else {
5063#if DEBUG_OUTBOUND_EVENT_DETAILS
5064 ALOGD("Unhandled key event: No fallback key.");
5065#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005066
5067 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005068 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069 }
5070 }
5071 return false;
5072}
5073
5074bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005075 DispatchEntry* dispatchEntry,
5076 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005077 return false;
5078}
5079
5080void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5081 mLock.unlock();
5082
5083 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5084
5085 mLock.lock();
5086}
5087
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005088KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5089 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005090 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005091 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5092 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005093 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094}
5095
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005096void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5097 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098 // TODO Write some statistics about how long we spend waiting.
5099}
5100
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005101/**
5102 * Report the touch event latency to the statsd server.
5103 * Input events are reported for statistics if:
5104 * - This is a touchscreen event
5105 * - InputFilter is not enabled
5106 * - Event is not injected or synthesized
5107 *
5108 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5109 * from getting aggregated with the "old" data.
5110 */
5111void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5112 REQUIRES(mLock) {
5113 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5114 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5115 if (!reportForStatistics) {
5116 return;
5117 }
5118
5119 if (mTouchStatistics.shouldReport()) {
5120 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5121 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5122 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5123 mTouchStatistics.reset();
5124 }
5125 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5126 mTouchStatistics.addValue(latencyMicros);
5127}
5128
Michael Wrightd02c5b62014-02-10 15:10:22 -08005129void InputDispatcher::traceInboundQueueLengthLocked() {
5130 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005131 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132 }
5133}
5134
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005135void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136 if (ATRACE_ENABLED()) {
5137 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005138 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005139 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 }
5141}
5142
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005143void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144 if (ATRACE_ENABLED()) {
5145 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005146 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005147 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148 }
5149}
5150
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005151void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005152 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005154 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155 dumpDispatchStateLocked(dump);
5156
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005157 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005158 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005159 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 }
5161}
5162
5163void InputDispatcher::monitor() {
5164 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005165 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005167 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168}
5169
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005170/**
5171 * Wake up the dispatcher and wait until it processes all events and commands.
5172 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5173 * this method can be safely called from any thread, as long as you've ensured that
5174 * the work you are interested in completing has already been queued.
5175 */
5176bool InputDispatcher::waitForIdle() {
5177 /**
5178 * Timeout should represent the longest possible time that a device might spend processing
5179 * events and commands.
5180 */
5181 constexpr std::chrono::duration TIMEOUT = 100ms;
5182 std::unique_lock lock(mLock);
5183 mLooper->wake();
5184 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5185 return result == std::cv_status::no_timeout;
5186}
5187
Vishnu Naire798b472020-07-23 13:52:21 -07005188/**
5189 * Sets focus to the window identified by the token. This must be called
5190 * after updating any input window handles.
5191 *
5192 * Params:
5193 * request.token - input channel token used to identify the window that should gain focus.
5194 * request.focusedToken - the token that the caller expects currently to be focused. If the
5195 * specified token does not match the currently focused window, this request will be dropped.
5196 * If the specified focused token matches the currently focused window, the call will succeed.
5197 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5198 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5199 * when requesting the focus change. This determines which request gets
5200 * precedence if there is a focus change request from another source such as pointer down.
5201 */
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005202void InputDispatcher::setFocusedWindow(const FocusRequest& request) {}
5203
5204void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocusedWindowHandle,
5205 const sp<InputWindowHandle>& newFocusedWindowHandle,
5206 int32_t displayId, std::string_view reason) {
5207 if (oldFocusedWindowHandle) {
5208 if (DEBUG_FOCUS) {
5209 ALOGD("Focus left window: %s in display %" PRId32,
5210 oldFocusedWindowHandle->getName().c_str(), displayId);
5211 }
5212 std::shared_ptr<InputChannel> focusedInputChannel =
5213 getInputChannelLocked(oldFocusedWindowHandle->getToken());
5214 if (focusedInputChannel) {
5215 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5216 "focus left window");
5217 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
5218 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/, reason);
5219 }
5220 mFocusedWindowHandlesByDisplay.erase(displayId);
5221 }
5222 if (newFocusedWindowHandle) {
5223 if (DEBUG_FOCUS) {
5224 ALOGD("Focus entered window: %s in display %" PRId32,
5225 newFocusedWindowHandle->getName().c_str(), displayId);
5226 }
5227 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
5228 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/, reason);
5229 }
5230
5231 if (mFocusedDisplayId == displayId) {
5232 notifyFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
5233 }
5234}
Garfield Tane84e6f92019-08-29 17:28:41 -07005235} // namespace android::inputdispatcher