blob: 3464b8f2e65b488766d78300560103d396007cbb [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
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001079void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001080 if (mPendingEvent != nullptr) {
1081 // Move the pending event to the front of the queue. This will give the chance
1082 // for the pending event to get dispatched to the newly focused window
1083 mInboundQueue.push_front(mPendingEvent);
1084 mPendingEvent = nullptr;
1085 }
1086
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001087 FocusEntry* focusEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001088 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001089
1090 // This event should go to the front of the queue, but behind all other focus events
1091 // Find the last focus event, and insert right after it
1092 std::deque<EventEntry*>::reverse_iterator it =
1093 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1094 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1095
1096 // Maintain the order of focus events. Insert the entry after all other focus events.
1097 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001098}
1099
1100void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001101 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001102 if (channel == nullptr) {
1103 return; // Window has gone away
1104 }
1105 InputTarget target;
1106 target.inputChannel = channel;
1107 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1108 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001109 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1110 channel->getName();
1111 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001112 dispatchEventLocked(currentTime, entry, {target});
1113}
1114
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001116 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001118 if (!entry->dispatchInProgress) {
1119 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1120 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1121 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1122 if (mKeyRepeatState.lastKeyEntry &&
1123 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 // We have seen two identical key downs in a row which indicates that the device
1125 // driver is automatically generating key repeats itself. We take note of the
1126 // repeat here, but we disable our own next key repeat timer since it is clear that
1127 // we will not need to synthesize key repeats ourselves.
1128 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1129 resetKeyRepeatLocked();
1130 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1131 } else {
1132 // Not a repeat. Save key down state in case we do see a repeat later.
1133 resetKeyRepeatLocked();
1134 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1135 }
1136 mKeyRepeatState.lastKeyEntry = entry;
1137 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001138 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 resetKeyRepeatLocked();
1140 }
1141
1142 if (entry->repeatCount == 1) {
1143 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1144 } else {
1145 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1146 }
1147
1148 entry->dispatchInProgress = true;
1149
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001150 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 }
1152
1153 // Handle case where the policy asked us to try again later last time.
1154 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1155 if (currentTime < entry->interceptKeyWakeupTime) {
1156 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1157 *nextWakeupTime = entry->interceptKeyWakeupTime;
1158 }
1159 return false; // wait until next wakeup
1160 }
1161 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1162 entry->interceptKeyWakeupTime = 0;
1163 }
1164
1165 // Give the policy a chance to intercept the key.
1166 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1167 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001168 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001169 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001170 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001171 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001172 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001173 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 }
1175 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001176 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 entry->refCount += 1;
1178 return false; // wait for the command to run
1179 } else {
1180 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1181 }
1182 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001183 if (*dropReason == DropReason::NOT_DROPPED) {
1184 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 }
1186 }
1187
1188 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001189 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001190 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001191 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001192 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001193 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 return true;
1195 }
1196
1197 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001198 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001199 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001200 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1202 return false;
1203 }
1204
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001205 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1207 return true;
1208 }
1209
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001210 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001211 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212
1213 // Dispatch the key.
1214 dispatchEventLocked(currentTime, entry, inputTargets);
1215 return true;
1216}
1217
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001218void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001220 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001221 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1222 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001223 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1224 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1225 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226#endif
1227}
1228
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1230 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001231 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001233 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 entry->dispatchInProgress = true;
1235
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001236 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 }
1238
1239 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001240 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001241 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001242 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001243 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 return true;
1245 }
1246
1247 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1248
1249 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001250 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251
1252 bool conflictingPointerActions = false;
1253 int32_t injectionResult;
1254 if (isPointerEvent) {
1255 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001256 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001257 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001258 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 } else {
1260 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001261 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001262 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 }
1264 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1265 return false;
1266 }
1267
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001268 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001269 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1270 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1271 return true;
1272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001274 CancelationOptions::Mode mode(isPointerEvent
1275 ? CancelationOptions::CANCEL_POINTER_EVENTS
1276 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1277 CancelationOptions options(mode, "input event injection failed");
1278 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 return true;
1280 }
1281
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001282 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001283 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001285 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001286 std::unordered_map<int32_t, TouchState>::iterator it =
1287 mTouchStatesByDisplay.find(entry->displayId);
1288 if (it != mTouchStatesByDisplay.end()) {
1289 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001290 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001291 // The event has gone through these portal windows, so we add monitoring targets of
1292 // the corresponding displays as well.
1293 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001294 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001295 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001296 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001297 }
1298 }
1299 }
1300 }
1301
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 // Dispatch the motion.
1303 if (conflictingPointerActions) {
1304 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001305 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 synthesizeCancelationEventsForAllConnectionsLocked(options);
1307 }
1308 dispatchEventLocked(currentTime, entry, inputTargets);
1309 return true;
1310}
1311
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001312void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001314 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001315 ", policyFlags=0x%x, "
1316 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1317 "metaState=0x%x, buttonState=0x%x,"
1318 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001319 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1320 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1321 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001323 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001325 "x=%f, y=%f, pressure=%f, size=%f, "
1326 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1327 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001328 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1329 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1330 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1331 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1332 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1333 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1334 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1335 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1336 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1337 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 }
1339#endif
1340}
1341
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001342void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1343 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001344 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345#if DEBUG_DISPATCH_CYCLE
1346 ALOGD("dispatchEventToCurrentInputTargets");
1347#endif
1348
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001349 updateInteractionTokensLocked(*eventEntry, inputTargets);
1350
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1352
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001353 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001355 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001356 sp<Connection> connection =
1357 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001358 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001359 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001361 if (DEBUG_FOCUS) {
1362 ALOGD("Dropping event delivery to target with channel '%s' because it "
1363 "is no longer registered with the input dispatcher.",
1364 inputTarget.inputChannel->getName().c_str());
1365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 }
1367 }
1368}
1369
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001370void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1371 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1372 // If the policy decides to close the app, we will get a channel removal event via
1373 // unregisterInputChannel, and will clean up the connection that way. We are already not
1374 // sending new pointers to the connection when it blocked, but focused events will continue to
1375 // pile up.
1376 ALOGW("Canceling events for %s because it is unresponsive",
1377 connection->inputChannel->getName().c_str());
1378 if (connection->status == Connection::STATUS_NORMAL) {
1379 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1380 "application not responding");
1381 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 }
1383}
1384
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001385void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001386 if (DEBUG_FOCUS) {
1387 ALOGD("Resetting ANR timeouts.");
1388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389
1390 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001391 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001392 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393}
1394
Tiger Huang721e26f2018-07-24 22:26:19 +08001395/**
1396 * Get the display id that the given event should go to. If this event specifies a valid display id,
1397 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1398 * Focused display is the display that the user most recently interacted with.
1399 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001401 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001402 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001403 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001404 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1405 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001406 break;
1407 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001408 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001409 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1410 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001411 break;
1412 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001413 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001414 case EventEntry::Type::CONFIGURATION_CHANGED:
1415 case EventEntry::Type::DEVICE_RESET: {
1416 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001417 return ADISPLAY_ID_NONE;
1418 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001419 }
1420 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1421}
1422
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001423bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1424 const char* focusedWindowName) {
1425 if (mAnrTracker.empty()) {
1426 // already processed all events that we waited for
1427 mKeyIsWaitingForEventsTimeout = std::nullopt;
1428 return false;
1429 }
1430
1431 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1432 // Start the timer
1433 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1434 "focus to change",
1435 focusedWindowName);
1436 mKeyIsWaitingForEventsTimeout = currentTime + KEY_WAITING_FOR_EVENTS_TIMEOUT.count();
1437 return true;
1438 }
1439
1440 // We still have pending events, and already started the timer
1441 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1442 return true; // Still waiting
1443 }
1444
1445 // Waited too long, and some connection still hasn't processed all motions
1446 // Just send the key to the focused window
1447 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1448 focusedWindowName);
1449 mKeyIsWaitingForEventsTimeout = std::nullopt;
1450 return false;
1451}
1452
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001454 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001455 std::vector<InputTarget>& inputTargets,
1456 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001457 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458
Tiger Huang721e26f2018-07-24 22:26:19 +08001459 int32_t displayId = getTargetDisplayId(entry);
1460 sp<InputWindowHandle> focusedWindowHandle =
1461 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001462 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001463 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1464
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465 // If there is no currently focused window and no focused application
1466 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001467 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1468 ALOGI("Dropping %s event because there is no focused window or focused application in "
1469 "display %" PRId32 ".",
1470 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001471 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 }
1473
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001474 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1475 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1476 // start interacting with another application via touch (app switch). This code can be removed
1477 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1478 // an app is expected to have a focused window.
1479 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1480 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1481 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001482 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1483 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1484 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001485 mAwaitedFocusedApplication = focusedApplicationHandle;
1486 ALOGW("Waiting because no window has focus but %s may eventually add a "
1487 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001488 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001489 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1490 return INPUT_EVENT_INJECTION_PENDING;
1491 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1492 // Already raised ANR. Drop the event
1493 ALOGE("Dropping %s event because there is no focused window",
1494 EventEntry::typeToString(entry.type));
1495 return INPUT_EVENT_INJECTION_FAILED;
1496 } else {
1497 // Still waiting for the focused window
1498 return INPUT_EVENT_INJECTION_PENDING;
1499 }
1500 }
1501
1502 // we have a valid, non-null focused window
1503 resetNoFocusedWindowTimeoutLocked();
1504
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001506 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001507 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 }
1509
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001510 if (focusedWindowHandle->getInfo()->paused) {
1511 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1512 return INPUT_EVENT_INJECTION_PENDING;
1513 }
1514
1515 // If the event is a key event, then we must wait for all previous events to
1516 // complete before delivering it because previous events may have the
1517 // side-effect of transferring focus to a different window and we want to
1518 // ensure that the following keys are sent to the new window.
1519 //
1520 // Suppose the user touches a button in a window then immediately presses "A".
1521 // If the button causes a pop-up window to appear then we want to ensure that
1522 // the "A" key is delivered to the new pop-up window. This is because users
1523 // often anticipate pending UI changes when typing on a keyboard.
1524 // To obtain this behavior, we must serialize key events with respect to all
1525 // prior input events.
1526 if (entry.type == EventEntry::Type::KEY) {
1527 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1528 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1529 return INPUT_EVENT_INJECTION_PENDING;
1530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 }
1532
1533 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001534 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001535 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1536 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537
1538 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001539 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540}
1541
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001542/**
1543 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1544 * that are currently unresponsive.
1545 */
1546std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1547 const std::vector<TouchedMonitor>& monitors) const {
1548 std::vector<TouchedMonitor> responsiveMonitors;
1549 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1550 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1551 sp<Connection> connection = getConnectionLocked(
1552 monitor.monitor.inputChannel->getConnectionToken());
1553 if (connection == nullptr) {
1554 ALOGE("Could not find connection for monitor %s",
1555 monitor.monitor.inputChannel->getName().c_str());
1556 return false;
1557 }
1558 if (!connection->responsive) {
1559 ALOGW("Unresponsive monitor %s will not get the new gesture",
1560 connection->inputChannel->getName().c_str());
1561 return false;
1562 }
1563 return true;
1564 });
1565 return responsiveMonitors;
1566}
1567
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001569 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001570 std::vector<InputTarget>& inputTargets,
1571 nsecs_t* nextWakeupTime,
1572 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001573 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 enum InjectionPermission {
1575 INJECTION_PERMISSION_UNKNOWN,
1576 INJECTION_PERMISSION_GRANTED,
1577 INJECTION_PERMISSION_DENIED
1578 };
1579
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 // For security reasons, we defer updating the touch state until we are sure that
1581 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001582 int32_t displayId = entry.displayId;
1583 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1585
1586 // Update the touch state as needed based on the properties of the touch event.
1587 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1588 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001589 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1590 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001592 // Copy current touch state into tempTouchState.
1593 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1594 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001595 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001596 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001597 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1598 mTouchStatesByDisplay.find(displayId);
1599 if (oldStateIt != mTouchStatesByDisplay.end()) {
1600 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001601 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001602 }
1603
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001604 bool isSplit = tempTouchState.split;
1605 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1606 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1607 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001608 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1609 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1610 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1611 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1612 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001613 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 bool wrongDevice = false;
1615 if (newGesture) {
1616 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001617 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001618 ALOGI("Dropping event because a pointer for a different device is already down "
1619 "in display %" PRId32,
1620 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001621 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1623 switchedDevice = false;
1624 wrongDevice = true;
1625 goto Failed;
1626 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001627 tempTouchState.reset();
1628 tempTouchState.down = down;
1629 tempTouchState.deviceId = entry.deviceId;
1630 tempTouchState.source = entry.source;
1631 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001633 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001634 ALOGI("Dropping move event because a pointer for a different device is already active "
1635 "in display %" PRId32,
1636 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001637 // TODO: test multiple simultaneous input streams.
1638 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1639 switchedDevice = false;
1640 wrongDevice = true;
1641 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 }
1643
1644 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1645 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1646
Garfield Tan00f511d2019-06-12 16:55:40 -07001647 int32_t x;
1648 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001650 // Always dispatch mouse events to cursor position.
1651 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001652 x = int32_t(entry.xCursorPosition);
1653 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001654 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001655 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1656 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001657 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001658 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001659 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001660 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1661 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001662
1663 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001664 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001665 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001668 if (newTouchedWindowHandle != nullptr &&
1669 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001670 // New window supports splitting, but we should never split mouse events.
1671 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 } else if (isSplit) {
1673 // New window does not support splitting but we have already split events.
1674 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001675 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 }
1677
1678 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001679 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001681 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001682 }
1683
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001684 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1685 ALOGI("Not sending touch event to %s because it is paused",
1686 newTouchedWindowHandle->getName().c_str());
1687 newTouchedWindowHandle = nullptr;
1688 }
1689
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001690 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001691 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001692 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1693 if (!isResponsive) {
1694 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001695 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1696 newTouchedWindowHandle = nullptr;
1697 }
1698 }
1699
1700 // Also don't send the new touch event to unresponsive gesture monitors
1701 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1702
Michael Wright3dd60e22019-03-27 22:06:44 +00001703 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1704 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001705 "(%d, %d) in display %" PRId32 ".",
1706 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001707 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1708 goto Failed;
1709 }
1710
1711 if (newTouchedWindowHandle != nullptr) {
1712 // Set target flags.
1713 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1714 if (isSplit) {
1715 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001717 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1718 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1719 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1720 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1721 }
1722
1723 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001724 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1725 newHoverWindowHandle = nullptr;
1726 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001727 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001728 }
1729
1730 // Update the temporary touch state.
1731 BitSet32 pointerIds;
1732 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001733 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001734 pointerIds.markBit(pointerId);
1735 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001736 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 }
1738
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001739 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 } else {
1741 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1742
1743 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001744 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001745 if (DEBUG_FOCUS) {
1746 ALOGD("Dropping event because the pointer is not down or we previously "
1747 "dropped the pointer down event in display %" PRId32,
1748 displayId);
1749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1751 goto Failed;
1752 }
1753
1754 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001755 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001756 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001757 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1758 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759
1760 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001761 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001762 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001763 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1764 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001765 if (DEBUG_FOCUS) {
1766 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1767 oldTouchedWindowHandle->getName().c_str(),
1768 newTouchedWindowHandle->getName().c_str(), displayId);
1769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001771 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1772 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1773 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774
1775 // Make a slippery entrance into the new window.
1776 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1777 isSplit = true;
1778 }
1779
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001780 int32_t targetFlags =
1781 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 if (isSplit) {
1783 targetFlags |= InputTarget::FLAG_SPLIT;
1784 }
1785 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1786 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1787 }
1788
1789 BitSet32 pointerIds;
1790 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001791 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001793 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
1795 }
1796 }
1797
1798 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001799 // Let the previous window know that the hover sequence is over, unless we already did it
1800 // when dispatching it as is to newTouchedWindowHandle.
1801 if (mLastHoverWindowHandle != nullptr &&
1802 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1803 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804#if DEBUG_HOVER
1805 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001806 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001808 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1809 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 }
1811
Garfield Tandf26e862020-07-01 20:18:19 -07001812 // Let the new window know that the hover sequence is starting, unless we already did it
1813 // when dispatching it as is to newTouchedWindowHandle.
1814 if (newHoverWindowHandle != nullptr &&
1815 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1816 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817#if DEBUG_HOVER
1818 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001819 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001821 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1822 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1823 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 }
1825 }
1826
1827 // Check permission to inject into all touched foreground windows and ensure there
1828 // is at least one touched foreground window.
1829 {
1830 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001831 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1833 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001834 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1836 injectionPermission = INJECTION_PERMISSION_DENIED;
1837 goto Failed;
1838 }
1839 }
1840 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001841 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001842 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001843 ALOGI("Dropping event because there is no touched foreground window in display "
1844 "%" PRId32 " or gesture monitor to receive it.",
1845 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1847 goto Failed;
1848 }
1849
1850 // Permission granted to injection into all touched foreground windows.
1851 injectionPermission = INJECTION_PERMISSION_GRANTED;
1852 }
1853
1854 // Check whether windows listening for outside touches are owned by the same UID. If it is
1855 // set the policy flag that we will not reveal coordinate information to this window.
1856 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1857 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001858 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001859 if (foregroundWindowHandle) {
1860 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001861 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001862 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1863 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1864 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001865 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1866 InputTarget::FLAG_ZERO_COORDS,
1867 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 }
1870 }
1871 }
1872 }
1873
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 // If this is the first pointer going down and the touched window has a wallpaper
1875 // then also add the touched wallpaper windows so they are locked in for the duration
1876 // of the touch gesture.
1877 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1878 // engine only supports touch events. We would need to add a mechanism similar
1879 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1880 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1881 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001882 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001883 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001884 const std::vector<sp<InputWindowHandle>> windowHandles =
1885 getWindowHandlesLocked(displayId);
1886 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001888 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001889 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001890 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001891 .addOrUpdateWindow(windowHandle,
1892 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1893 InputTarget::
1894 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1895 InputTarget::FLAG_DISPATCH_AS_IS,
1896 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 }
1898 }
1899 }
1900 }
1901
1902 // Success! Output targets.
1903 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1904
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001905 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001907 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 }
1909
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001910 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001911 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001912 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001913 }
1914
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 // Drop the outside or hover touch windows since we will not care about them
1916 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001917 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918
1919Failed:
1920 // Check injection permission once and for all.
1921 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001922 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 injectionPermission = INJECTION_PERMISSION_GRANTED;
1924 } else {
1925 injectionPermission = INJECTION_PERMISSION_DENIED;
1926 }
1927 }
1928
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001929 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1930 return injectionResult;
1931 }
1932
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001934 if (!wrongDevice) {
1935 if (switchedDevice) {
1936 if (DEBUG_FOCUS) {
1937 ALOGD("Conflicting pointer actions: Switched to a different device.");
1938 }
1939 *outConflictingPointerActions = true;
1940 }
1941
1942 if (isHoverAction) {
1943 // Started hovering, therefore no longer down.
1944 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001945 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001946 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1947 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949 *outConflictingPointerActions = true;
1950 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001951 tempTouchState.reset();
1952 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1953 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1954 tempTouchState.deviceId = entry.deviceId;
1955 tempTouchState.source = entry.source;
1956 tempTouchState.displayId = displayId;
1957 }
1958 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1959 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1960 // All pointers up or canceled.
1961 tempTouchState.reset();
1962 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1963 // First pointer went down.
1964 if (oldState && oldState->down) {
1965 if (DEBUG_FOCUS) {
1966 ALOGD("Conflicting pointer actions: Down received while already down.");
1967 }
1968 *outConflictingPointerActions = true;
1969 }
1970 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1971 // One pointer went up.
1972 if (isSplit) {
1973 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1974 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001976 for (size_t i = 0; i < tempTouchState.windows.size();) {
1977 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1978 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1979 touchedWindow.pointerIds.clearBit(pointerId);
1980 if (touchedWindow.pointerIds.isEmpty()) {
1981 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1982 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001985 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001987 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001988 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001989
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001990 // Save changes unless the action was scroll in which case the temporary touch
1991 // state was only valid for this one action.
1992 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1993 if (tempTouchState.displayId >= 0) {
1994 mTouchStatesByDisplay[displayId] = tempTouchState;
1995 } else {
1996 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002000 // Update hover state.
2001 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 }
2003
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 return injectionResult;
2005}
2006
2007void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002008 int32_t targetFlags, BitSet32 pointerIds,
2009 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002010 std::vector<InputTarget>::iterator it =
2011 std::find_if(inputTargets.begin(), inputTargets.end(),
2012 [&windowHandle](const InputTarget& inputTarget) {
2013 return inputTarget.inputChannel->getConnectionToken() ==
2014 windowHandle->getToken();
2015 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002016
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002017 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002018
2019 if (it == inputTargets.end()) {
2020 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002021 std::shared_ptr<InputChannel> inputChannel =
2022 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002023 if (inputChannel == nullptr) {
2024 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2025 return;
2026 }
2027 inputTarget.inputChannel = inputChannel;
2028 inputTarget.flags = targetFlags;
2029 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2030 inputTargets.push_back(inputTarget);
2031 it = inputTargets.end() - 1;
2032 }
2033
2034 ALOG_ASSERT(it->flags == targetFlags);
2035 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2036
chaviw1ff3d1e2020-07-01 15:53:47 -07002037 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038}
2039
Michael Wright3dd60e22019-03-27 22:06:44 +00002040void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002041 int32_t displayId, float xOffset,
2042 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002043 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2044 mGlobalMonitorsByDisplay.find(displayId);
2045
2046 if (it != mGlobalMonitorsByDisplay.end()) {
2047 const std::vector<Monitor>& monitors = it->second;
2048 for (const Monitor& monitor : monitors) {
2049 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 }
2052}
2053
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002054void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2055 float yOffset,
2056 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002057 InputTarget target;
2058 target.inputChannel = monitor.inputChannel;
2059 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002060 ui::Transform t;
2061 t.set(xOffset, yOffset);
2062 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002063 inputTargets.push_back(target);
2064}
2065
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002067 const InjectionState* injectionState) {
2068 if (injectionState &&
2069 (windowHandle == nullptr ||
2070 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2071 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002072 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002074 "owned by uid %d",
2075 injectionState->injectorPid, injectionState->injectorUid,
2076 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 } else {
2078 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002079 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 }
2081 return false;
2082 }
2083 return true;
2084}
2085
Robert Carrc9bf1d32020-04-13 17:21:08 -07002086/**
2087 * Indicate whether one window handle should be considered as obscuring
2088 * another window handle. We only check a few preconditions. Actually
2089 * checking the bounds is left to the caller.
2090 */
2091static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2092 const sp<InputWindowHandle>& otherHandle) {
2093 // Compare by token so cloned layers aren't counted
2094 if (haveSameToken(windowHandle, otherHandle)) {
2095 return false;
2096 }
2097 auto info = windowHandle->getInfo();
2098 auto otherInfo = otherHandle->getInfo();
2099 if (!otherInfo->visible) {
2100 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002101 } else if (info->ownerPid == otherInfo->ownerPid) {
2102 // If ownerPid is the same we don't generate occlusion events as there
2103 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002104 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002105 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002106 return false;
2107 } else if (otherInfo->displayId != info->displayId) {
2108 return false;
2109 }
2110 return true;
2111}
2112
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002113bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2114 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002116 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2117 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002118 if (windowHandle == otherHandle) {
2119 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002122 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002123 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 return true;
2125 }
2126 }
2127 return false;
2128}
2129
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002130bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2131 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002132 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002133 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002134 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002135 if (windowHandle == otherHandle) {
2136 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002137 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002138 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002139 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002140 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002141 return true;
2142 }
2143 }
2144 return false;
2145}
2146
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002147std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002148 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002150 if (applicationHandle != nullptr) {
2151 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002152 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 } else {
2154 return applicationHandle->getName();
2155 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002156 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002157 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002159 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 }
2161}
2162
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002163void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002164 if (eventEntry.type == EventEntry::Type::FOCUS) {
2165 // Focus events are passed to apps, but do not represent user activity.
2166 return;
2167 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002168 int32_t displayId = getTargetDisplayId(eventEntry);
2169 sp<InputWindowHandle> focusedWindowHandle =
2170 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2171 if (focusedWindowHandle != nullptr) {
2172 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002173 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002175 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176#endif
2177 return;
2178 }
2179 }
2180
2181 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002182 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002183 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002184 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2185 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002186 return;
2187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002189 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002190 eventType = USER_ACTIVITY_EVENT_TOUCH;
2191 }
2192 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002194 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002195 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2196 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002197 return;
2198 }
2199 eventType = USER_ACTIVITY_EVENT_BUTTON;
2200 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002202 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002203 case EventEntry::Type::CONFIGURATION_CHANGED:
2204 case EventEntry::Type::DEVICE_RESET: {
2205 LOG_ALWAYS_FATAL("%s events are not user activity",
2206 EventEntry::typeToString(eventEntry.type));
2207 break;
2208 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 }
2210
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002211 std::unique_ptr<CommandEntry> commandEntry =
2212 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002213 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002215 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216}
2217
2218void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002219 const sp<Connection>& connection,
2220 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002221 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002222 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002223 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002224 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002225 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002226 ATRACE_NAME(message.c_str());
2227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228#if DEBUG_DISPATCH_CYCLE
2229 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002230 "globalScaleFactor=%f, pointerIds=0x%x %s",
2231 connection->getInputChannelName().c_str(), inputTarget.flags,
2232 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2233 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234#endif
2235
2236 // Skip this event if the connection status is not normal.
2237 // We don't want to enqueue additional outbound events if the connection is broken.
2238 if (connection->status != Connection::STATUS_NORMAL) {
2239#if DEBUG_DISPATCH_CYCLE
2240 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002241 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242#endif
2243 return;
2244 }
2245
2246 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002247 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2248 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2249 "Entry type %s should not have FLAG_SPLIT",
2250 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002252 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002253 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002255 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 if (!splitMotionEntry) {
2257 return; // split event was dropped
2258 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002259 if (DEBUG_FOCUS) {
2260 ALOGD("channel '%s' ~ Split motion event.",
2261 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002262 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002263 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002264 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 splitMotionEntry->release();
2266 return;
2267 }
2268 }
2269
2270 // Not splitting. Enqueue dispatch entries for the event as is.
2271 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2272}
2273
2274void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002275 const sp<Connection>& connection,
2276 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002277 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002278 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002279 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002280 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002281 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002282 ATRACE_NAME(message.c_str());
2283 }
2284
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002285 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286
2287 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002288 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002290 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002291 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002292 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002293 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002294 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002296 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002298 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002299 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300
2301 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002302 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 startDispatchCycleLocked(currentTime, connection);
2304 }
2305}
2306
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002307void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2308 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002309 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002310 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002311 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002312 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2313 connection->getInputChannelName().c_str(),
2314 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002315 ATRACE_NAME(message.c_str());
2316 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002317 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 if (!(inputTargetFlags & dispatchMode)) {
2319 return;
2320 }
2321 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2322
2323 // This is a new event.
2324 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002325 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002326 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002328 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2329 // different EventEntry than what was passed in.
2330 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002332 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002333 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002334 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002335 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002336 dispatchEntry->resolvedAction = keyEntry.action;
2337 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002339 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2340 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002342 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2343 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002345 return; // skip the inconsistent event
2346 }
2347 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002350 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002351 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002352 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2353 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2354 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2355 static_cast<int32_t>(IdGenerator::Source::OTHER);
2356 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002357 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2358 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2359 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2360 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2361 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2362 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2363 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2364 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2365 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2366 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2367 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002368 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002369 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002370 }
2371 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002372 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2373 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002375 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2376 "event",
2377 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002379 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002382 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002383 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2384 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2385 }
2386 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2387 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002390 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2391 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002393 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2394 "event",
2395 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002397 return; // skip the inconsistent event
2398 }
2399
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002400 dispatchEntry->resolvedEventId =
2401 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2402 ? mIdGenerator.nextId()
2403 : motionEntry.id;
2404 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2405 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2406 ") to MotionEvent(id=0x%" PRIx32 ").",
2407 motionEntry.id, dispatchEntry->resolvedEventId);
2408 ATRACE_NAME(message.c_str());
2409 }
2410
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002411 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002412 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002413
2414 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002416 case EventEntry::Type::FOCUS: {
2417 break;
2418 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002419 case EventEntry::Type::CONFIGURATION_CHANGED:
2420 case EventEntry::Type::DEVICE_RESET: {
2421 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002422 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002423 break;
2424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 }
2426
2427 // Remember that we are waiting for this dispatch to complete.
2428 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002429 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 }
2431
2432 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002433 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002434 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002435}
2436
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002437/**
2438 * This function is purely for debugging. It helps us understand where the user interaction
2439 * was taking place. For example, if user is touching launcher, we will see a log that user
2440 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2441 * We will see both launcher and wallpaper in that list.
2442 * Once the interaction with a particular set of connections starts, no new logs will be printed
2443 * until the set of interacted connections changes.
2444 *
2445 * The following items are skipped, to reduce the logspam:
2446 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2447 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2448 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2449 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2450 * Both of those ACTION_UP events would not be logged
2451 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2452 * will not be logged. This is omitted to reduce the amount of data printed.
2453 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2454 * gesture monitor is the only connection receiving the remainder of the gesture.
2455 */
2456void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2457 const std::vector<InputTarget>& targets) {
2458 // Skip ACTION_UP events, and all events other than keys and motions
2459 if (entry.type == EventEntry::Type::KEY) {
2460 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2461 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2462 return;
2463 }
2464 } else if (entry.type == EventEntry::Type::MOTION) {
2465 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2466 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2467 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2468 return;
2469 }
2470 } else {
2471 return; // Not a key or a motion
2472 }
2473
2474 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2475 std::vector<sp<Connection>> newConnections;
2476 for (const InputTarget& target : targets) {
2477 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2478 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2479 continue; // Skip windows that receive ACTION_OUTSIDE
2480 }
2481
2482 sp<IBinder> token = target.inputChannel->getConnectionToken();
2483 sp<Connection> connection = getConnectionLocked(token);
2484 if (connection == nullptr || connection->monitor) {
2485 continue; // We only need to keep track of the non-monitor connections.
2486 }
2487 newConnectionTokens.insert(std::move(token));
2488 newConnections.emplace_back(connection);
2489 }
2490 if (newConnectionTokens == mInteractionConnectionTokens) {
2491 return; // no change
2492 }
2493 mInteractionConnectionTokens = newConnectionTokens;
2494
2495 std::string windowList;
2496 for (const sp<Connection>& connection : newConnections) {
2497 windowList += connection->getWindowName() + ", ";
2498 }
2499 std::string message = "Interaction with windows: " + windowList;
2500 if (windowList.empty()) {
2501 message += "<none>";
2502 }
2503 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2504}
2505
chaviwfd6d3512019-03-25 13:23:49 -07002506void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002507 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002508 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002509 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2510 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002511 return;
2512 }
2513
2514 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2515 if (inputWindowHandle == nullptr) {
2516 return;
2517 }
2518
chaviw8c9cf542019-03-25 13:02:48 -07002519 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002520 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002521
2522 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2523
2524 if (!hasFocusChanged) {
2525 return;
2526 }
2527
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002528 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2529 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002530 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002531 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532}
2533
2534void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002535 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002536 if (ATRACE_ENABLED()) {
2537 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002538 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002539 ATRACE_NAME(message.c_str());
2540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002542 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543#endif
2544
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002545 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2546 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002548 const nsecs_t timeout =
2549 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
2550 dispatchEntry->timeoutTime = currentTime + timeout;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551
2552 // Publish the event.
2553 status_t status;
2554 EventEntry* eventEntry = dispatchEntry->eventEntry;
2555 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002556 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002557 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2558 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002560 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002561 status =
2562 connection->inputPublisher
2563 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2564 keyEntry->deviceId, keyEntry->source,
2565 keyEntry->displayId, std::move(hmac),
2566 dispatchEntry->resolvedAction,
2567 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2568 keyEntry->scanCode, keyEntry->metaState,
2569 keyEntry->repeatCount, keyEntry->downTime,
2570 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002571 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 }
2573
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002574 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002575 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577 PointerCoords scaledCoords[MAX_POINTERS];
2578 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2579
chaviw82357092020-01-28 13:13:06 -08002580 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002581 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2582 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2583 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002584 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002585 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2586 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002587 // Don't apply window scale here since we don't want scale to affect raw
2588 // coordinates. The scale will be sent back to the client and applied
2589 // later when requesting relative coordinates.
2590 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2591 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002592 }
2593 usingCoords = scaledCoords;
2594 }
2595 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002596 // We don't want the dispatch target to know.
2597 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2598 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2599 scaledCoords[i].clear();
2600 }
2601 usingCoords = scaledCoords;
2602 }
2603 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002604
2605 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002606
2607 // Publish the motion event.
2608 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002609 .publishMotionEvent(dispatchEntry->seq,
2610 dispatchEntry->resolvedEventId,
2611 motionEntry->deviceId, motionEntry->source,
2612 motionEntry->displayId, std::move(hmac),
2613 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002614 motionEntry->actionButton,
2615 dispatchEntry->resolvedFlags,
2616 motionEntry->edgeFlags, motionEntry->metaState,
2617 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002618 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002619 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002620 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002621 motionEntry->yPrecision,
2622 motionEntry->xCursorPosition,
2623 motionEntry->yCursorPosition,
2624 motionEntry->downTime, motionEntry->eventTime,
2625 motionEntry->pointerCount,
2626 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002627 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002628 break;
2629 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002630 case EventEntry::Type::FOCUS: {
2631 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2632 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002633 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002634 focusEntry->hasFocus,
2635 mInTouchMode);
2636 break;
2637 }
2638
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002639 case EventEntry::Type::CONFIGURATION_CHANGED:
2640 case EventEntry::Type::DEVICE_RESET: {
2641 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2642 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002643 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002644 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645 }
2646
2647 // Check the result.
2648 if (status) {
2649 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002650 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002652 "This is unexpected because the wait queue is empty, so the pipe "
2653 "should be empty and we shouldn't have any problems writing an "
2654 "event to it, status=%d",
2655 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2657 } else {
2658 // Pipe is full and we are waiting for the app to finish process some events
2659 // before sending more events to it.
2660#if DEBUG_DISPATCH_CYCLE
2661 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002662 "waiting for the application to catch up",
2663 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665 }
2666 } else {
2667 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002668 "status=%d",
2669 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2671 }
2672 return;
2673 }
2674
2675 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002676 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2677 connection->outboundQueue.end(),
2678 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002679 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002680 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002681 if (connection->responsive) {
2682 mAnrTracker.insert(dispatchEntry->timeoutTime,
2683 connection->inputChannel->getConnectionToken());
2684 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002685 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 }
2687}
2688
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002689const std::array<uint8_t, 32> InputDispatcher::getSignature(
2690 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2691 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2692 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2693 // Only sign events up and down events as the purely move events
2694 // are tied to their up/down counterparts so signing would be redundant.
2695 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2696 verifiedEvent.actionMasked = actionMasked;
2697 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2698 return mHmacKeyManager.sign(verifiedEvent);
2699 }
2700 return INVALID_HMAC;
2701}
2702
2703const std::array<uint8_t, 32> InputDispatcher::getSignature(
2704 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2705 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2706 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2707 verifiedEvent.action = dispatchEntry.resolvedAction;
2708 return mHmacKeyManager.sign(verifiedEvent);
2709}
2710
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002712 const sp<Connection>& connection, uint32_t seq,
2713 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714#if DEBUG_DISPATCH_CYCLE
2715 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002716 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717#endif
2718
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002719 if (connection->status == Connection::STATUS_BROKEN ||
2720 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721 return;
2722 }
2723
2724 // Notify other system components and prepare to start the next dispatch cycle.
2725 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2726}
2727
2728void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002729 const sp<Connection>& connection,
2730 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002731#if DEBUG_DISPATCH_CYCLE
2732 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002733 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734#endif
2735
2736 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002737 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002738 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002739 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002740 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741
2742 // The connection appears to be unrecoverably broken.
2743 // Ignore already broken or zombie connections.
2744 if (connection->status == Connection::STATUS_NORMAL) {
2745 connection->status = Connection::STATUS_BROKEN;
2746
2747 if (notify) {
2748 // Notify other system components.
2749 onDispatchCycleBrokenLocked(currentTime, connection);
2750 }
2751 }
2752}
2753
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002754void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2755 while (!queue.empty()) {
2756 DispatchEntry* dispatchEntry = queue.front();
2757 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002758 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759 }
2760}
2761
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002762void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002764 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 }
2766 delete dispatchEntry;
2767}
2768
2769int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2770 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2771
2772 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002773 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002775 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002776 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002777 "fd=%d, events=0x%x",
2778 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779 return 0; // remove the callback
2780 }
2781
2782 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002783 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2785 if (!(events & ALOOPER_EVENT_INPUT)) {
2786 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002787 "events=0x%x",
2788 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789 return 1;
2790 }
2791
2792 nsecs_t currentTime = now();
2793 bool gotOne = false;
2794 status_t status;
2795 for (;;) {
2796 uint32_t seq;
2797 bool handled;
2798 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2799 if (status) {
2800 break;
2801 }
2802 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2803 gotOne = true;
2804 }
2805 if (gotOne) {
2806 d->runCommandsLockedInterruptible();
2807 if (status == WOULD_BLOCK) {
2808 return 1;
2809 }
2810 }
2811
2812 notify = status != DEAD_OBJECT || !connection->monitor;
2813 if (notify) {
2814 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002815 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816 }
2817 } else {
2818 // Monitor channels are never explicitly unregistered.
2819 // We do it automatically when the remote endpoint is closed so don't warn
2820 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002821 const bool stillHaveWindowHandle =
2822 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2823 nullptr;
2824 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 if (notify) {
2826 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002827 "events=0x%x",
2828 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 }
2830 }
2831
2832 // Unregister the channel.
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002833 d->unregisterInputChannelLocked(*connection->inputChannel, notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002835 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836}
2837
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002838void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002840 for (const auto& pair : mConnectionsByFd) {
2841 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 }
2843}
2844
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002845void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002846 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002847 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2848 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2849}
2850
2851void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2852 const CancelationOptions& options,
2853 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2854 for (const auto& it : monitorsByDisplay) {
2855 const std::vector<Monitor>& monitors = it.second;
2856 for (const Monitor& monitor : monitors) {
2857 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002858 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002859 }
2860}
2861
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002863 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002864 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002865 if (connection == nullptr) {
2866 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002868
2869 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870}
2871
2872void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2873 const sp<Connection>& connection, const CancelationOptions& options) {
2874 if (connection->status == Connection::STATUS_BROKEN) {
2875 return;
2876 }
2877
2878 nsecs_t currentTime = now();
2879
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002880 std::vector<EventEntry*> cancelationEvents =
2881 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002883 if (cancelationEvents.empty()) {
2884 return;
2885 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002887 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2888 "with reality: %s, mode=%d.",
2889 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2890 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002892
2893 InputTarget target;
2894 sp<InputWindowHandle> windowHandle =
2895 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2896 if (windowHandle != nullptr) {
2897 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002898 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002899 target.globalScaleFactor = windowInfo->globalScaleFactor;
2900 }
2901 target.inputChannel = connection->inputChannel;
2902 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2903
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002904 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2905 EventEntry* cancelationEventEntry = cancelationEvents[i];
2906 switch (cancelationEventEntry->type) {
2907 case EventEntry::Type::KEY: {
2908 logOutboundKeyDetails("cancel - ",
2909 static_cast<const KeyEntry&>(*cancelationEventEntry));
2910 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002912 case EventEntry::Type::MOTION: {
2913 logOutboundMotionDetails("cancel - ",
2914 static_cast<const MotionEntry&>(*cancelationEventEntry));
2915 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002917 case EventEntry::Type::FOCUS: {
2918 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2919 break;
2920 }
2921 case EventEntry::Type::CONFIGURATION_CHANGED:
2922 case EventEntry::Type::DEVICE_RESET: {
2923 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2924 EventEntry::typeToString(cancelationEventEntry->type));
2925 break;
2926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927 }
2928
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002929 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2930 target, InputTarget::FLAG_DISPATCH_AS_IS);
2931
2932 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002934
2935 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936}
2937
Svet Ganov5d3bc372020-01-26 23:11:07 -08002938void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2939 const sp<Connection>& connection) {
2940 if (connection->status == Connection::STATUS_BROKEN) {
2941 return;
2942 }
2943
2944 nsecs_t currentTime = now();
2945
2946 std::vector<EventEntry*> downEvents =
2947 connection->inputState.synthesizePointerDownEvents(currentTime);
2948
2949 if (downEvents.empty()) {
2950 return;
2951 }
2952
2953#if DEBUG_OUTBOUND_EVENT_DETAILS
2954 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2955 connection->getInputChannelName().c_str(), downEvents.size());
2956#endif
2957
2958 InputTarget target;
2959 sp<InputWindowHandle> windowHandle =
2960 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2961 if (windowHandle != nullptr) {
2962 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002963 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002964 target.globalScaleFactor = windowInfo->globalScaleFactor;
2965 }
2966 target.inputChannel = connection->inputChannel;
2967 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2968
2969 for (EventEntry* downEventEntry : downEvents) {
2970 switch (downEventEntry->type) {
2971 case EventEntry::Type::MOTION: {
2972 logOutboundMotionDetails("down - ",
2973 static_cast<const MotionEntry&>(*downEventEntry));
2974 break;
2975 }
2976
2977 case EventEntry::Type::KEY:
2978 case EventEntry::Type::FOCUS:
2979 case EventEntry::Type::CONFIGURATION_CHANGED:
2980 case EventEntry::Type::DEVICE_RESET: {
2981 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2982 EventEntry::typeToString(downEventEntry->type));
2983 break;
2984 }
2985 }
2986
2987 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2988 target, InputTarget::FLAG_DISPATCH_AS_IS);
2989
2990 downEventEntry->release();
2991 }
2992
2993 startDispatchCycleLocked(currentTime, connection);
2994}
2995
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002996MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002997 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002998 ALOG_ASSERT(pointerIds.value != 0);
2999
3000 uint32_t splitPointerIndexMap[MAX_POINTERS];
3001 PointerProperties splitPointerProperties[MAX_POINTERS];
3002 PointerCoords splitPointerCoords[MAX_POINTERS];
3003
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003004 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 uint32_t splitPointerCount = 0;
3006
3007 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003008 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003010 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011 uint32_t pointerId = uint32_t(pointerProperties.id);
3012 if (pointerIds.hasBit(pointerId)) {
3013 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3014 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3015 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003016 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 splitPointerCount += 1;
3018 }
3019 }
3020
3021 if (splitPointerCount != pointerIds.count()) {
3022 // This is bad. We are missing some of the pointers that we expected to deliver.
3023 // Most likely this indicates that we received an ACTION_MOVE events that has
3024 // different pointer ids than we expected based on the previous ACTION_DOWN
3025 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3026 // in this way.
3027 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003028 "we expected there to be %d pointers. This probably means we received "
3029 "a broken sequence of pointer ids from the input device.",
3030 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003031 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003032 }
3033
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003034 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003035 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003036 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3037 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3039 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003040 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041 uint32_t pointerId = uint32_t(pointerProperties.id);
3042 if (pointerIds.hasBit(pointerId)) {
3043 if (pointerIds.count() == 1) {
3044 // The first/last pointer went down/up.
3045 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 ? AMOTION_EVENT_ACTION_DOWN
3047 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048 } else {
3049 // A secondary pointer went down/up.
3050 uint32_t splitPointerIndex = 0;
3051 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3052 splitPointerIndex += 1;
3053 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003054 action = maskedAction |
3055 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 }
3057 } else {
3058 // An unrelated pointer changed.
3059 action = AMOTION_EVENT_ACTION_MOVE;
3060 }
3061 }
3062
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003063 int32_t newId = mIdGenerator.nextId();
3064 if (ATRACE_ENABLED()) {
3065 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3066 ") to MotionEvent(id=0x%" PRIx32 ").",
3067 originalMotionEntry.id, newId);
3068 ATRACE_NAME(message.c_str());
3069 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003070 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003071 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3072 originalMotionEntry.source, originalMotionEntry.displayId,
3073 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003074 originalMotionEntry.actionButton, originalMotionEntry.flags,
3075 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3076 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3077 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3078 originalMotionEntry.xCursorPosition,
3079 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003080 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003082 if (originalMotionEntry.injectionState) {
3083 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 splitMotionEntry->injectionState->refCount += 1;
3085 }
3086
3087 return splitMotionEntry;
3088}
3089
3090void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3091#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003092 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093#endif
3094
3095 bool needWake;
3096 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003097 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098
Prabir Pradhan42611e02018-11-27 14:04:02 -08003099 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003100 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 needWake = enqueueInboundEventLocked(newEntry);
3102 } // release lock
3103
3104 if (needWake) {
3105 mLooper->wake();
3106 }
3107}
3108
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003109/**
3110 * If one of the meta shortcuts is detected, process them here:
3111 * Meta + Backspace -> generate BACK
3112 * Meta + Enter -> generate HOME
3113 * This will potentially overwrite keyCode and metaState.
3114 */
3115void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003116 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003117 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3118 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3119 if (keyCode == AKEYCODE_DEL) {
3120 newKeyCode = AKEYCODE_BACK;
3121 } else if (keyCode == AKEYCODE_ENTER) {
3122 newKeyCode = AKEYCODE_HOME;
3123 }
3124 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003125 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003126 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003127 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003128 keyCode = newKeyCode;
3129 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3130 }
3131 } else if (action == AKEY_EVENT_ACTION_UP) {
3132 // In order to maintain a consistent stream of up and down events, check to see if the key
3133 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3134 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003135 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003136 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003137 auto replacementIt = mReplacedKeys.find(replacement);
3138 if (replacementIt != mReplacedKeys.end()) {
3139 keyCode = replacementIt->second;
3140 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003141 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3142 }
3143 }
3144}
3145
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3147#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003148 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3149 "policyFlags=0x%x, action=0x%x, "
3150 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3151 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3152 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3153 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154#endif
3155 if (!validateKeyEvent(args->action)) {
3156 return;
3157 }
3158
3159 uint32_t policyFlags = args->policyFlags;
3160 int32_t flags = args->flags;
3161 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003162 // InputDispatcher tracks and generates key repeats on behalf of
3163 // whatever notifies it, so repeatCount should always be set to 0
3164 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3166 policyFlags |= POLICY_FLAG_VIRTUAL;
3167 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 if (policyFlags & POLICY_FLAG_FUNCTION) {
3170 metaState |= AMETA_FUNCTION_ON;
3171 }
3172
3173 policyFlags |= POLICY_FLAG_TRUSTED;
3174
Michael Wright78f24442014-08-06 15:55:28 -07003175 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003176 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003177
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003179 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003180 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3181 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182
Michael Wright2b3c3302018-03-02 17:19:13 +00003183 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003185 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3186 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003187 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003188 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 bool needWake;
3191 { // acquire lock
3192 mLock.lock();
3193
3194 if (shouldSendKeyToInputFilterLocked(args)) {
3195 mLock.unlock();
3196
3197 policyFlags |= POLICY_FLAG_FILTERED;
3198 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3199 return; // event was consumed by the filter
3200 }
3201
3202 mLock.lock();
3203 }
3204
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003205 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003206 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003207 args->displayId, policyFlags, args->action, flags, keyCode,
3208 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209
3210 needWake = enqueueInboundEventLocked(newEntry);
3211 mLock.unlock();
3212 } // release lock
3213
3214 if (needWake) {
3215 mLooper->wake();
3216 }
3217}
3218
3219bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3220 return mInputFilterEnabled;
3221}
3222
3223void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3224#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003225 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3226 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003227 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3228 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003229 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003230 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3231 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3232 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3233 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234 for (uint32_t i = 0; i < args->pointerCount; i++) {
3235 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003236 "x=%f, y=%f, pressure=%f, size=%f, "
3237 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3238 "orientation=%f",
3239 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3240 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3241 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3242 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3243 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3244 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3245 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3246 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3247 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3248 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 }
3250#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003251 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3252 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 return;
3254 }
3255
3256 uint32_t policyFlags = args->policyFlags;
3257 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003258
3259 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003260 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003261 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3262 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003263 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265
3266 bool needWake;
3267 { // acquire lock
3268 mLock.lock();
3269
3270 if (shouldSendMotionToInputFilterLocked(args)) {
3271 mLock.unlock();
3272
3273 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003274 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003275 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3276 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003277 args->metaState, args->buttonState, args->classification, transform,
3278 args->xPrecision, args->yPrecision, args->xCursorPosition,
3279 args->yCursorPosition, args->downTime, args->eventTime,
3280 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281
3282 policyFlags |= POLICY_FLAG_FILTERED;
3283 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3284 return; // event was consumed by the filter
3285 }
3286
3287 mLock.lock();
3288 }
3289
3290 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003291 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003292 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003293 args->displayId, policyFlags, args->action, args->actionButton,
3294 args->flags, args->metaState, args->buttonState,
3295 args->classification, args->edgeFlags, args->xPrecision,
3296 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3297 args->downTime, args->pointerCount, args->pointerProperties,
3298 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299
3300 needWake = enqueueInboundEventLocked(newEntry);
3301 mLock.unlock();
3302 } // release lock
3303
3304 if (needWake) {
3305 mLooper->wake();
3306 }
3307}
3308
3309bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003310 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311}
3312
3313void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3314#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003315 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003316 "switchMask=0x%08x",
3317 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318#endif
3319
3320 uint32_t policyFlags = args->policyFlags;
3321 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323}
3324
3325void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3326#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003327 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3328 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329#endif
3330
3331 bool needWake;
3332 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003333 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334
Prabir Pradhan42611e02018-11-27 14:04:02 -08003335 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003336 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 needWake = enqueueInboundEventLocked(newEntry);
3338 } // release lock
3339
3340 if (needWake) {
3341 mLooper->wake();
3342 }
3343}
3344
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003345int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3346 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003347 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348#if DEBUG_INBOUND_EVENT_DETAILS
3349 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003350 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3351 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352#endif
3353
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003354 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355
3356 policyFlags |= POLICY_FLAG_INJECTED;
3357 if (hasInjectionPermission(injectorPid, injectorUid)) {
3358 policyFlags |= POLICY_FLAG_TRUSTED;
3359 }
3360
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003361 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003363 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003364 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3365 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 if (!validateKeyEvent(action)) {
3367 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003370 int32_t flags = incomingKey.getFlags();
3371 int32_t keyCode = incomingKey.getKeyCode();
3372 int32_t metaState = incomingKey.getMetaState();
3373 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003374 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003375 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003376 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003377 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3378 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3379 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003381 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3382 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003383 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003384
3385 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3386 android::base::Timer t;
3387 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3388 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3389 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3390 std::to_string(t.duration().count()).c_str());
3391 }
3392 }
3393
3394 mLock.lock();
3395 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003396 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3397 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003398 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3399 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003400 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003401 injectedEntries.push(injectedEntry);
3402 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403 }
3404
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003405 case AINPUT_EVENT_TYPE_MOTION: {
3406 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3407 int32_t action = motionEvent->getAction();
3408 size_t pointerCount = motionEvent->getPointerCount();
3409 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3410 int32_t actionButton = motionEvent->getActionButton();
3411 int32_t displayId = motionEvent->getDisplayId();
3412 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3413 return INPUT_EVENT_INJECTION_FAILED;
3414 }
3415
3416 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3417 nsecs_t eventTime = motionEvent->getEventTime();
3418 android::base::Timer t;
3419 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3420 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3421 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3422 std::to_string(t.duration().count()).c_str());
3423 }
3424 }
3425
3426 mLock.lock();
3427 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3428 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3429 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003430 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3431 motionEvent->getSource(), motionEvent->getDisplayId(),
3432 policyFlags, action, actionButton, motionEvent->getFlags(),
3433 motionEvent->getMetaState(), motionEvent->getButtonState(),
3434 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3435 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003436 motionEvent->getRawXCursorPosition(),
3437 motionEvent->getRawYCursorPosition(),
3438 motionEvent->getDownTime(), uint32_t(pointerCount),
3439 pointerProperties, samplePointerCoords,
3440 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003441 injectedEntries.push(injectedEntry);
3442 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3443 sampleEventTimes += 1;
3444 samplePointerCoords += pointerCount;
3445 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003446 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003447 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003448 motionEvent->getDisplayId(), policyFlags, action,
3449 actionButton, motionEvent->getFlags(),
3450 motionEvent->getMetaState(), motionEvent->getButtonState(),
3451 motionEvent->getClassification(),
3452 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3453 motionEvent->getYPrecision(),
3454 motionEvent->getRawXCursorPosition(),
3455 motionEvent->getRawYCursorPosition(),
3456 motionEvent->getDownTime(), uint32_t(pointerCount),
3457 pointerProperties, samplePointerCoords,
3458 motionEvent->getXOffset(), motionEvent->getYOffset());
3459 injectedEntries.push(nextInjectedEntry);
3460 }
3461 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003464 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003465 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003466 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467 }
3468
3469 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3470 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3471 injectionState->injectionIsAsync = true;
3472 }
3473
3474 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003475 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476
3477 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003478 while (!injectedEntries.empty()) {
3479 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3480 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481 }
3482
3483 mLock.unlock();
3484
3485 if (needWake) {
3486 mLooper->wake();
3487 }
3488
3489 int32_t injectionResult;
3490 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003491 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492
3493 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3494 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3495 } else {
3496 for (;;) {
3497 injectionResult = injectionState->injectionResult;
3498 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3499 break;
3500 }
3501
3502 nsecs_t remainingTimeout = endTime - now();
3503 if (remainingTimeout <= 0) {
3504#if DEBUG_INJECTION
3505 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003506 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507#endif
3508 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3509 break;
3510 }
3511
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003512 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 }
3514
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003515 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3516 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 while (injectionState->pendingForegroundDispatches != 0) {
3518#if DEBUG_INJECTION
3519 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003520 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521#endif
3522 nsecs_t remainingTimeout = endTime - now();
3523 if (remainingTimeout <= 0) {
3524#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003525 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3526 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527#endif
3528 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3529 break;
3530 }
3531
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003532 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 }
3534 }
3535 }
3536
3537 injectionState->release();
3538 } // release lock
3539
3540#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003541 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003542 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543#endif
3544
3545 return injectionResult;
3546}
3547
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003548std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003549 std::array<uint8_t, 32> calculatedHmac;
3550 std::unique_ptr<VerifiedInputEvent> result;
3551 switch (event.getType()) {
3552 case AINPUT_EVENT_TYPE_KEY: {
3553 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3554 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3555 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3556 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3557 break;
3558 }
3559 case AINPUT_EVENT_TYPE_MOTION: {
3560 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3561 VerifiedMotionEvent verifiedMotionEvent =
3562 verifiedMotionEventFromMotionEvent(motionEvent);
3563 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3564 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3565 break;
3566 }
3567 default: {
3568 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3569 return nullptr;
3570 }
3571 }
3572 if (calculatedHmac == INVALID_HMAC) {
3573 return nullptr;
3574 }
3575 if (calculatedHmac != event.getHmac()) {
3576 return nullptr;
3577 }
3578 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003579}
3580
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003582 return injectorUid == 0 ||
3583 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584}
3585
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003586void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587 InjectionState* injectionState = entry->injectionState;
3588 if (injectionState) {
3589#if DEBUG_INJECTION
3590 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003591 "injectorPid=%d, injectorUid=%d",
3592 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593#endif
3594
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003595 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 // Log the outcome since the injector did not wait for the injection result.
3597 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003598 case INPUT_EVENT_INJECTION_SUCCEEDED:
3599 ALOGV("Asynchronous input event injection succeeded.");
3600 break;
3601 case INPUT_EVENT_INJECTION_FAILED:
3602 ALOGW("Asynchronous input event injection failed.");
3603 break;
3604 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3605 ALOGW("Asynchronous input event injection permission denied.");
3606 break;
3607 case INPUT_EVENT_INJECTION_TIMED_OUT:
3608 ALOGW("Asynchronous input event injection timed out.");
3609 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 }
3611 }
3612
3613 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003614 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 }
3616}
3617
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003618void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 InjectionState* injectionState = entry->injectionState;
3620 if (injectionState) {
3621 injectionState->pendingForegroundDispatches += 1;
3622 }
3623}
3624
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003625void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 InjectionState* injectionState = entry->injectionState;
3627 if (injectionState) {
3628 injectionState->pendingForegroundDispatches -= 1;
3629
3630 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003631 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 }
3633 }
3634}
3635
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003636std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3637 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003638 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003639}
3640
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003642 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003643 if (windowHandleToken == nullptr) {
3644 return nullptr;
3645 }
3646
Arthur Hungb92218b2018-08-14 12:00:21 +08003647 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003648 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3649 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003650 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003651 return windowHandle;
3652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653 }
3654 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003655 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656}
3657
Mady Mellor017bcd12020-06-23 19:12:00 +00003658bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3659 for (auto& it : mWindowHandlesByDisplay) {
3660 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3661 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003662 if (handle->getId() == windowHandle->getId() &&
3663 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003664 if (windowHandle->getInfo()->displayId != it.first) {
3665 ALOGE("Found window %s in display %" PRId32
3666 ", but it should belong to display %" PRId32,
3667 windowHandle->getName().c_str(), it.first,
3668 windowHandle->getInfo()->displayId);
3669 }
3670 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003671 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 }
3673 }
3674 return false;
3675}
3676
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003677bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3678 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3679 const bool noInputChannel =
3680 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3681 if (connection != nullptr && noInputChannel) {
3682 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3683 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3684 return false;
3685 }
3686
3687 if (connection == nullptr) {
3688 if (!noInputChannel) {
3689 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3690 }
3691 return false;
3692 }
3693 if (!connection->responsive) {
3694 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3695 return false;
3696 }
3697 return true;
3698}
3699
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003700std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3701 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003702 size_t count = mInputChannelsByToken.count(token);
3703 if (count == 0) {
3704 return nullptr;
3705 }
3706 return mInputChannelsByToken.at(token);
3707}
3708
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003709void InputDispatcher::updateWindowHandlesForDisplayLocked(
3710 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3711 if (inputWindowHandles.empty()) {
3712 // Remove all handles on a display if there are no windows left.
3713 mWindowHandlesByDisplay.erase(displayId);
3714 return;
3715 }
3716
3717 // Since we compare the pointer of input window handles across window updates, we need
3718 // to make sure the handle object for the same window stays unchanged across updates.
3719 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003720 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003721 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003722 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003723 }
3724
3725 std::vector<sp<InputWindowHandle>> newHandles;
3726 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3727 if (!handle->updateInfo()) {
3728 // handle no longer valid
3729 continue;
3730 }
3731
3732 const InputWindowInfo* info = handle->getInfo();
3733 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3734 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3735 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003736 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3737 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3738 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003739 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003740 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003741 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003742 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003743 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003744 }
3745
3746 if (info->displayId != displayId) {
3747 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3748 handle->getName().c_str(), displayId, info->displayId);
3749 continue;
3750 }
3751
Robert Carredd13602020-04-13 17:24:34 -07003752 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3753 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003754 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003755 oldHandle->updateFrom(handle);
3756 newHandles.push_back(oldHandle);
3757 } else {
3758 newHandles.push_back(handle);
3759 }
3760 }
3761
3762 // Insert or replace
3763 mWindowHandlesByDisplay[displayId] = newHandles;
3764}
3765
Arthur Hung72d8dc32020-03-28 00:48:39 +00003766void InputDispatcher::setInputWindows(
3767 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3768 { // acquire lock
3769 std::scoped_lock _l(mLock);
3770 for (auto const& i : handlesPerDisplay) {
3771 setInputWindowsLocked(i.second, i.first);
3772 }
3773 }
3774 // Wake up poll loop since it may need to make new input dispatching choices.
3775 mLooper->wake();
3776}
3777
Arthur Hungb92218b2018-08-14 12:00:21 +08003778/**
3779 * Called from InputManagerService, update window handle list by displayId that can receive input.
3780 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3781 * If set an empty list, remove all handles from the specific display.
3782 * For focused handle, check if need to change and send a cancel event to previous one.
3783 * For removed handle, check if need to send a cancel event if already in touch.
3784 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003785void InputDispatcher::setInputWindowsLocked(
3786 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003787 if (DEBUG_FOCUS) {
3788 std::string windowList;
3789 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3790 windowList += iwh->getName() + " ";
3791 }
3792 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3793 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003795 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3796 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3797 const bool noInputWindow =
3798 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3799 if (noInputWindow && window->getToken() != nullptr) {
3800 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3801 window->getName().c_str());
3802 window->releaseChannel();
3803 }
3804 }
3805
Arthur Hung72d8dc32020-03-28 00:48:39 +00003806 // Copy old handles for release if they are no longer present.
3807 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808
Arthur Hung72d8dc32020-03-28 00:48:39 +00003809 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003810
Arthur Hung72d8dc32020-03-28 00:48:39 +00003811 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3812 bool foundHoveredWindow = false;
3813 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3814 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3815 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3816 windowHandle->getInfo()->visible) {
3817 newFocusedWindowHandle = windowHandle;
3818 }
3819 if (windowHandle == mLastHoverWindowHandle) {
3820 foundHoveredWindow = true;
3821 }
3822 }
3823
3824 if (!foundHoveredWindow) {
3825 mLastHoverWindowHandle = nullptr;
3826 }
3827
3828 sp<InputWindowHandle> oldFocusedWindowHandle =
3829 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3830
3831 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3832 if (oldFocusedWindowHandle != nullptr) {
3833 if (DEBUG_FOCUS) {
3834 ALOGD("Focus left window: %s in display %" PRId32,
3835 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003836 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003837 std::shared_ptr<InputChannel> focusedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003838 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3839 if (focusedInputChannel != nullptr) {
3840 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3841 "focus left window");
3842 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3843 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003844 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003845 mFocusedWindowHandlesByDisplay.erase(displayId);
3846 }
3847 if (newFocusedWindowHandle != nullptr) {
3848 if (DEBUG_FOCUS) {
3849 ALOGD("Focus entered window: %s in display %" PRId32,
3850 newFocusedWindowHandle->getName().c_str(), displayId);
3851 }
3852 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3853 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 }
3855
Arthur Hung72d8dc32020-03-28 00:48:39 +00003856 if (mFocusedDisplayId == displayId) {
3857 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003860
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003861 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3862 mTouchStatesByDisplay.find(displayId);
3863 if (stateIt != mTouchStatesByDisplay.end()) {
3864 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003865 for (size_t i = 0; i < state.windows.size();) {
3866 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003867 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003868 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003869 ALOGD("Touched window was removed: %s in display %" PRId32,
3870 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003871 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003872 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003873 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3874 if (touchedInputChannel != nullptr) {
3875 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3876 "touched window was removed");
3877 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003879 state.windows.erase(state.windows.begin() + i);
3880 } else {
3881 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882 }
3883 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003884 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003885
Arthur Hung72d8dc32020-03-28 00:48:39 +00003886 // Release information for windows that are no longer present.
3887 // This ensures that unused input channels are released promptly.
3888 // Otherwise, they might stick around until the window handle is destroyed
3889 // which might not happen until the next GC.
3890 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003891 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003892 if (DEBUG_FOCUS) {
3893 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003894 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003895 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003896 }
chaviw291d88a2019-02-14 10:33:58 -08003897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898}
3899
3900void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07003901 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003902 if (DEBUG_FOCUS) {
3903 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3904 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3905 }
Chris Yea209fde2020-07-22 13:54:51 -07003906 if (inputApplicationHandle != nullptr &&
3907 inputApplicationHandle->getApplicationToken() != nullptr) {
3908 // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003909 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910
Chris Yea209fde2020-07-22 13:54:51 -07003911 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08003912 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003913
Chris Yea209fde2020-07-22 13:54:51 -07003914 // If oldFocusedApplicationHandle already exists
3915 if (oldFocusedApplicationHandle != nullptr) {
3916 // If a new focused application handle is different from the old one and
3917 // old focus application info is awaited focused application info.
3918 if (*oldFocusedApplicationHandle != *inputApplicationHandle &&
3919 mAwaitedFocusedApplication != nullptr &&
3920 *oldFocusedApplicationHandle == *mAwaitedFocusedApplication) {
3921 resetNoFocusedWindowTimeoutLocked();
3922 }
3923 // Erase the old application from container first
3924 mFocusedApplicationHandlesByDisplay.erase(displayId);
3925 // Should already get freed after removed from container but just double check.
3926 oldFocusedApplicationHandle.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003927 }
3928
Chris Yea209fde2020-07-22 13:54:51 -07003929 // Set the new application handle.
3930 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 } // release lock
3932
3933 // Wake up poll loop since it may need to make new input dispatching choices.
3934 mLooper->wake();
3935}
3936
Tiger Huang721e26f2018-07-24 22:26:19 +08003937/**
3938 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3939 * the display not specified.
3940 *
3941 * We track any unreleased events for each window. If a window loses the ability to receive the
3942 * released event, we will send a cancel event to it. So when the focused display is changed, we
3943 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3944 * display. The display-specified events won't be affected.
3945 */
3946void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003947 if (DEBUG_FOCUS) {
3948 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3949 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003950 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003951 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003952
3953 if (mFocusedDisplayId != displayId) {
3954 sp<InputWindowHandle> oldFocusedWindowHandle =
3955 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3956 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003957 std::shared_ptr<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003958 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003959 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003960 CancelationOptions
3961 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3962 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003963 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003964 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3965 }
3966 }
3967 mFocusedDisplayId = displayId;
3968
3969 // Sanity check
3970 sp<InputWindowHandle> newFocusedWindowHandle =
3971 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003972 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003973
Tiger Huang721e26f2018-07-24 22:26:19 +08003974 if (newFocusedWindowHandle == nullptr) {
3975 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3976 if (!mFocusedWindowHandlesByDisplay.empty()) {
3977 ALOGE("But another display has a focused window:");
3978 for (auto& it : mFocusedWindowHandlesByDisplay) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003979 const sp<InputWindowHandle>& windowHandle = it.second;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05003980 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", it.first,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003981 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003982 }
3983 }
3984 }
3985 }
3986
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003987 if (DEBUG_FOCUS) {
3988 logDispatchStateLocked();
3989 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003990 } // release lock
3991
3992 // Wake up poll loop since it may need to make new input dispatching choices.
3993 mLooper->wake();
3994}
3995
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003997 if (DEBUG_FOCUS) {
3998 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000
4001 bool changed;
4002 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004003 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004
4005 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4006 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004007 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008 }
4009
4010 if (mDispatchEnabled && !enabled) {
4011 resetAndDropEverythingLocked("dispatcher is being disabled");
4012 }
4013
4014 mDispatchEnabled = enabled;
4015 mDispatchFrozen = frozen;
4016 changed = true;
4017 } else {
4018 changed = false;
4019 }
4020
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004021 if (DEBUG_FOCUS) {
4022 logDispatchStateLocked();
4023 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024 } // release lock
4025
4026 if (changed) {
4027 // Wake up poll loop since it may need to make new input dispatching choices.
4028 mLooper->wake();
4029 }
4030}
4031
4032void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004033 if (DEBUG_FOCUS) {
4034 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036
4037 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004038 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004039
4040 if (mInputFilterEnabled == enabled) {
4041 return;
4042 }
4043
4044 mInputFilterEnabled = enabled;
4045 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4046 } // release lock
4047
4048 // Wake up poll loop since there might be work to do to drop everything.
4049 mLooper->wake();
4050}
4051
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004052void InputDispatcher::setInTouchMode(bool inTouchMode) {
4053 std::scoped_lock lock(mLock);
4054 mInTouchMode = inTouchMode;
4055}
4056
chaviwfbe5d9c2018-12-26 12:23:37 -08004057bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4058 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004059 if (DEBUG_FOCUS) {
4060 ALOGD("Trivial transfer to same window.");
4061 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004062 return true;
4063 }
4064
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004066 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067
chaviwfbe5d9c2018-12-26 12:23:37 -08004068 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4069 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004070 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004071 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 return false;
4073 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004074 if (DEBUG_FOCUS) {
4075 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4076 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4077 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004079 if (DEBUG_FOCUS) {
4080 ALOGD("Cannot transfer focus because windows are on different displays.");
4081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 return false;
4083 }
4084
4085 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004086 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4087 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004088 for (size_t i = 0; i < state.windows.size(); i++) {
4089 const TouchedWindow& touchedWindow = state.windows[i];
4090 if (touchedWindow.windowHandle == fromWindowHandle) {
4091 int32_t oldTargetFlags = touchedWindow.targetFlags;
4092 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004094 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004096 int32_t newTargetFlags = oldTargetFlags &
4097 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4098 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004099 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100
Jeff Brownf086ddb2014-02-11 14:28:48 -08004101 found = true;
4102 goto Found;
4103 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104 }
4105 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004106 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004108 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004109 if (DEBUG_FOCUS) {
4110 ALOGD("Focus transfer failed because from window did not have focus.");
4111 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112 return false;
4113 }
4114
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004115 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4116 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004117 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004118 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004119 CancelationOptions
4120 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4121 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004123 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 }
4125
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004126 if (DEBUG_FOCUS) {
4127 logDispatchStateLocked();
4128 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 } // release lock
4130
4131 // Wake up poll loop since it may need to make new input dispatching choices.
4132 mLooper->wake();
4133 return true;
4134}
4135
4136void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004137 if (DEBUG_FOCUS) {
4138 ALOGD("Resetting and dropping all events (%s).", reason);
4139 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140
4141 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4142 synthesizeCancelationEventsForAllConnectionsLocked(options);
4143
4144 resetKeyRepeatLocked();
4145 releasePendingEventLocked();
4146 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004147 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004149 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004150 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004152 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153}
4154
4155void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004156 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 dumpDispatchStateLocked(dump);
4158
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004159 std::istringstream stream(dump);
4160 std::string line;
4161
4162 while (std::getline(stream, line, '\n')) {
4163 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 }
4165}
4166
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004167void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004168 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4169 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4170 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004171 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172
Tiger Huang721e26f2018-07-24 22:26:19 +08004173 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4174 dump += StringPrintf(INDENT "FocusedApplications:\n");
4175 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4176 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004177 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004178 const int64_t timeoutMillis = millis(
4179 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004181 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004182 displayId, applicationHandle->getName().c_str(), timeoutMillis);
Tiger Huang721e26f2018-07-24 22:26:19 +08004183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004185 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004187
4188 if (!mFocusedWindowHandlesByDisplay.empty()) {
4189 dump += StringPrintf(INDENT "FocusedWindows:\n");
4190 for (auto& it : mFocusedWindowHandlesByDisplay) {
4191 const int32_t displayId = it.first;
4192 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004193 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4194 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004195 }
4196 } else {
4197 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4198 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004200 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004201 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004202 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4203 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004204 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004205 state.displayId, toString(state.down), toString(state.split),
4206 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004207 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004208 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004209 for (size_t i = 0; i < state.windows.size(); i++) {
4210 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004211 dump += StringPrintf(INDENT4
4212 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4213 i, touchedWindow.windowHandle->getName().c_str(),
4214 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004215 }
4216 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004217 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004218 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004219 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004220 dump += INDENT3 "Portal windows:\n";
4221 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004222 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004223 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4224 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004225 }
4226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 }
4228 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004229 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230 }
4231
Arthur Hungb92218b2018-08-14 12:00:21 +08004232 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004234 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004235 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004236 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004237 dump += INDENT2 "Windows:\n";
4238 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004239 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004240 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241
Arthur Hungb92218b2018-08-14 12:00:21 +08004242 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004243 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004244 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004245 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004247 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004248 i, windowInfo->name.c_str(), windowInfo->displayId,
4249 windowInfo->portalToDisplayId,
4250 toString(windowInfo->paused),
4251 toString(windowInfo->hasFocus),
4252 toString(windowInfo->hasWallpaper),
4253 toString(windowInfo->visible),
4254 toString(windowInfo->canReceiveKeys),
Michael Wright8759d672020-07-21 00:46:45 +01004255 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004256 static_cast<int32_t>(windowInfo->type),
4257 windowInfo->frameLeft, windowInfo->frameTop,
4258 windowInfo->frameRight, windowInfo->frameBottom,
chaviw1ff3d1e2020-07-01 15:53:47 -07004259 windowInfo->globalScaleFactor);
Arthur Hungb92218b2018-08-14 12:00:21 +08004260 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004261 dump += StringPrintf(", inputFeatures=%s",
4262 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004263 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4264 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004265 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004266 millis(windowInfo->dispatchingTimeout));
chaviw1ff3d1e2020-07-01 15:53:47 -07004267 windowInfo->transform.dump(dump, INDENT4 "transform=");
Arthur Hungb92218b2018-08-14 12:00:21 +08004268 }
4269 } else {
4270 dump += INDENT2 "Windows: <none>\n";
4271 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 }
4273 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004274 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 }
4276
Michael Wright3dd60e22019-03-27 22:06:44 +00004277 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004278 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004279 const std::vector<Monitor>& monitors = it.second;
4280 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4281 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004282 }
4283 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004284 const std::vector<Monitor>& monitors = it.second;
4285 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4286 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004289 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 }
4291
4292 nsecs_t currentTime = now();
4293
4294 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004295 if (!mRecentQueue.empty()) {
4296 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4297 for (EventEntry* entry : mRecentQueue) {
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 "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 }
4305
4306 // Dump event currently being dispatched.
4307 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004308 dump += INDENT "PendingEvent:\n";
4309 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004311 dump += StringPrintf(", age=%" PRId64 "ms\n",
4312 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004314 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315 }
4316
4317 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004318 if (!mInboundQueue.empty()) {
4319 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4320 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004321 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004323 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 }
4325 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004326 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
4328
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004329 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004330 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004331 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4332 const KeyReplacement& replacement = pair.first;
4333 int32_t newKeyCode = pair.second;
4334 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004335 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004336 }
4337 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004338 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004339 }
4340
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004341 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004342 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004343 for (const auto& pair : mConnectionsByFd) {
4344 const sp<Connection>& connection = pair.second;
4345 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004346 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004347 pair.first, connection->getInputChannelName().c_str(),
4348 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004349 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004351 if (!connection->outboundQueue.empty()) {
4352 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4353 connection->outboundQueue.size());
4354 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 dump.append(INDENT4);
4356 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004357 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4358 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004359 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004360 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 }
4362 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004363 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 }
4365
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004366 if (!connection->waitQueue.empty()) {
4367 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4368 connection->waitQueue.size());
4369 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004370 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004372 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004373 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004374 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004375 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004376 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 }
4378 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004379 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 }
4381 }
4382 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004383 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 }
4385
4386 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004387 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4388 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004390 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 }
4392
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004393 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004394 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4395 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4396 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397}
4398
Michael Wright3dd60e22019-03-27 22:06:44 +00004399void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4400 const size_t numMonitors = monitors.size();
4401 for (size_t i = 0; i < numMonitors; i++) {
4402 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004403 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004404 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4405 dump += "\n";
4406 }
4407}
4408
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004409status_t InputDispatcher::registerInputChannel(const std::shared_ptr<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004411 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412#endif
4413
4414 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004415 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004416 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004417 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004419 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 return BAD_VALUE;
4421 }
4422
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004423 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424
4425 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004426 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004427 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4430 } // release lock
4431
4432 // Wake the looper because some connections have changed.
4433 mLooper->wake();
4434 return OK;
4435}
4436
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004437status_t InputDispatcher::registerInputMonitor(const std::shared_ptr<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004438 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004439 { // acquire lock
4440 std::scoped_lock _l(mLock);
4441
4442 if (displayId < 0) {
4443 ALOGW("Attempted to register input monitor without a specified display.");
4444 return BAD_VALUE;
4445 }
4446
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004447 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004448 ALOGW("Attempted to register input monitor without an identifying token.");
4449 return BAD_VALUE;
4450 }
4451
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004452 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004453
4454 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004455 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004456 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004457
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004458 auto& monitorsByDisplay =
4459 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004460 monitorsByDisplay[displayId].emplace_back(inputChannel);
4461
4462 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004463 }
4464 // Wake the looper because some connections have changed.
4465 mLooper->wake();
4466 return OK;
4467}
4468
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004469status_t InputDispatcher::unregisterInputChannel(const InputChannel& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470#if DEBUG_REGISTRATION
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004471 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472#endif
4473
4474 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004475 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476
4477 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4478 if (status) {
4479 return status;
4480 }
4481 } // release lock
4482
4483 // Wake the poll loop because removing the connection may have changed the current
4484 // synchronization state.
4485 mLooper->wake();
4486 return OK;
4487}
4488
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004489status_t InputDispatcher::unregisterInputChannelLocked(const InputChannel& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004490 bool notify) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004491 sp<Connection> connection = getConnectionLocked(inputChannel.getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004492 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004494 inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 return BAD_VALUE;
4496 }
4497
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004498 removeConnectionLocked(connection);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004499 mInputChannelsByToken.erase(inputChannel.getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004500
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 if (connection->monitor) {
4502 removeMonitorChannelLocked(inputChannel);
4503 }
4504
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004505 mLooper->removeFd(inputChannel.getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506
4507 nsecs_t currentTime = now();
4508 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4509
4510 connection->status = Connection::STATUS_ZOMBIE;
4511 return OK;
4512}
4513
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004514void InputDispatcher::removeMonitorChannelLocked(const InputChannel& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004515 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4516 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4517}
4518
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004519void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004520 const InputChannel& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004521 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004522 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004523 std::vector<Monitor>& monitors = it->second;
4524 const size_t numMonitors = monitors.size();
4525 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004526 if (*monitors[i].inputChannel == inputChannel) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004527 monitors.erase(monitors.begin() + i);
4528 break;
4529 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004530 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004531 if (monitors.empty()) {
4532 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004533 } else {
4534 ++it;
4535 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536 }
4537}
4538
Michael Wright3dd60e22019-03-27 22:06:44 +00004539status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4540 { // acquire lock
4541 std::scoped_lock _l(mLock);
4542 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4543
4544 if (!foundDisplayId) {
4545 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4546 return BAD_VALUE;
4547 }
4548 int32_t displayId = foundDisplayId.value();
4549
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004550 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4551 mTouchStatesByDisplay.find(displayId);
4552 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004553 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4554 return BAD_VALUE;
4555 }
4556
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004557 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004558 std::optional<int32_t> foundDeviceId;
4559 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004560 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004561 foundDeviceId = state.deviceId;
4562 }
4563 }
4564 if (!foundDeviceId || !state.down) {
4565 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004566 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004567 return BAD_VALUE;
4568 }
4569 int32_t deviceId = foundDeviceId.value();
4570
4571 // Send cancel events to all the input channels we're stealing from.
4572 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004573 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004574 options.deviceId = deviceId;
4575 options.displayId = displayId;
4576 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004577 std::shared_ptr<InputChannel> channel =
4578 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004579 if (channel != nullptr) {
4580 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4581 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004582 }
4583 // Then clear the current touch state so we stop dispatching to them as well.
4584 state.filterNonMonitors();
4585 }
4586 return OK;
4587}
4588
Michael Wright3dd60e22019-03-27 22:06:44 +00004589std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4590 const sp<IBinder>& token) {
4591 for (const auto& it : mGestureMonitorsByDisplay) {
4592 const std::vector<Monitor>& monitors = it.second;
4593 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004594 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004595 return it.first;
4596 }
4597 }
4598 }
4599 return std::nullopt;
4600}
4601
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004602sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004603 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004604 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004605 }
4606
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004607 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004608 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004609 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004610 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 }
4612 }
Robert Carr4e670e52018-08-15 13:26:12 -07004613
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004614 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615}
4616
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004617void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004618 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004619 removeByValue(mConnectionsByFd, connection);
4620}
4621
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004622void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4623 const sp<Connection>& connection, uint32_t seq,
4624 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004625 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4626 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627 commandEntry->connection = connection;
4628 commandEntry->eventTime = currentTime;
4629 commandEntry->seq = seq;
4630 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004631 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632}
4633
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004634void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4635 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004637 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004639 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4640 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004642 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643}
4644
chaviw0c06c6e2019-01-09 13:27:07 -08004645void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004646 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004647 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4648 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004649 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4650 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004651 commandEntry->oldToken = oldToken;
4652 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004653 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004654}
4655
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004656void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4657 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4658 // is already healthy again. Don't raise ANR in this situation
4659 if (connection->waitQueue.empty()) {
4660 ALOGI("Not raising ANR because the connection %s has recovered",
4661 connection->inputChannel->getName().c_str());
4662 return;
4663 }
4664 /**
4665 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4666 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4667 * has changed. This could cause newer entries to time out before the already dispatched
4668 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4669 * processes the events linearly. So providing information about the oldest entry seems to be
4670 * most useful.
4671 */
4672 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4673 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4674 std::string reason =
4675 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4676 connection->inputChannel->getName().c_str(),
4677 ns2ms(currentWait),
4678 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004680 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4681 reason);
4682
4683 std::unique_ptr<CommandEntry> commandEntry =
4684 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4685 commandEntry->inputApplicationHandle = nullptr;
4686 commandEntry->inputChannel = connection->inputChannel;
4687 commandEntry->reason = std::move(reason);
4688 postCommandLocked(std::move(commandEntry));
4689}
4690
Chris Yea209fde2020-07-22 13:54:51 -07004691void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004692 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4693 application->getName().c_str());
4694
4695 updateLastAnrStateLocked(application, reason);
4696
4697 std::unique_ptr<CommandEntry> commandEntry =
4698 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4699 commandEntry->inputApplicationHandle = application;
4700 commandEntry->inputChannel = nullptr;
4701 commandEntry->reason = std::move(reason);
4702 postCommandLocked(std::move(commandEntry));
4703}
4704
4705void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4706 const std::string& reason) {
4707 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4708 updateLastAnrStateLocked(windowLabel, reason);
4709}
4710
Chris Yea209fde2020-07-22 13:54:51 -07004711void InputDispatcher::updateLastAnrStateLocked(
4712 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004713 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4714 updateLastAnrStateLocked(windowLabel, reason);
4715}
4716
4717void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4718 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004720 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721 struct tm tm;
4722 localtime_r(&t, &tm);
4723 char timestr[64];
4724 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004725 mLastAnrState.clear();
4726 mLastAnrState += INDENT "ANR:\n";
4727 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004728 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4729 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004730 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731}
4732
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004733void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734 mLock.unlock();
4735
4736 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4737
4738 mLock.lock();
4739}
4740
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004741void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742 sp<Connection> connection = commandEntry->connection;
4743
4744 if (connection->status != Connection::STATUS_ZOMBIE) {
4745 mLock.unlock();
4746
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004747 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748
4749 mLock.lock();
4750 }
4751}
4752
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004753void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004754 sp<IBinder> oldToken = commandEntry->oldToken;
4755 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004756 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004757 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004758 mLock.lock();
4759}
4760
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004761void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004762 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004763 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004764 mLock.unlock();
4765
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004766 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004767 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768
4769 mLock.lock();
4770
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004771 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004772 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4773 } else {
4774 // stop waking up for events in this connection, it is already not responding
4775 sp<Connection> connection = getConnectionLocked(token);
4776 if (connection == nullptr) {
4777 return;
4778 }
4779 cancelEventsForAnrLocked(connection);
4780 }
4781}
4782
Chris Yea209fde2020-07-22 13:54:51 -07004783void InputDispatcher::extendAnrTimeoutsLocked(
4784 const std::shared_ptr<InputApplicationHandle>& application,
4785 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004786 sp<Connection> connection = getConnectionLocked(connectionToken);
4787 if (connection == nullptr) {
4788 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4789 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004790 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004791 mAwaitedFocusedApplication = application;
4792 } else {
4793 // It's also possible that the connection already disappeared. No action necessary.
4794 }
4795 return;
4796 }
4797
4798 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004799 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004800
4801 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004802 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004803 for (DispatchEntry* entry : connection->waitQueue) {
4804 if (newTimeout >= entry->timeoutTime) {
4805 // Already removed old entries when connection was marked unresponsive
4806 entry->timeoutTime = newTimeout;
4807 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4808 }
4809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810}
4811
4812void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4813 CommandEntry* commandEntry) {
4814 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004815 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816
4817 mLock.unlock();
4818
Michael Wright2b3c3302018-03-02 17:19:13 +00004819 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004820 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004821 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004822 : nullptr;
4823 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004824 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4825 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004826 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828
4829 mLock.lock();
4830
4831 if (delay < 0) {
4832 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4833 } else if (!delay) {
4834 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4835 } else {
4836 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4837 entry->interceptKeyWakeupTime = now() + delay;
4838 }
4839 entry->release();
4840}
4841
chaviwfd6d3512019-03-25 13:23:49 -07004842void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4843 mLock.unlock();
4844 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4845 mLock.lock();
4846}
4847
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004848/**
4849 * Connection is responsive if it has no events in the waitQueue that are older than the
4850 * current time.
4851 */
4852static bool isConnectionResponsive(const Connection& connection) {
4853 const nsecs_t currentTime = now();
4854 for (const DispatchEntry* entry : connection.waitQueue) {
4855 if (entry->timeoutTime < currentTime) {
4856 return false;
4857 }
4858 }
4859 return true;
4860}
4861
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004862void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004864 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004866 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867
4868 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004869 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004870 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004871 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004873 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004874 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004875 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004876 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4877 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004878 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004879 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004880
4881 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004882 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004883 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4884 restartEvent =
4885 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004886 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004887 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4888 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4889 handled);
4890 } else {
4891 restartEvent = false;
4892 }
4893
4894 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004895 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004896 // contents of the wait queue to have been drained, so we need to double-check
4897 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004898 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4899 if (dispatchEntryIt != connection->waitQueue.end()) {
4900 dispatchEntry = *dispatchEntryIt;
4901 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004902 mAnrTracker.erase(dispatchEntry->timeoutTime,
4903 connection->inputChannel->getConnectionToken());
4904 if (!connection->responsive) {
4905 connection->responsive = isConnectionResponsive(*connection);
4906 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004907 traceWaitQueueLength(connection);
4908 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004909 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004910 traceOutboundQueueLength(connection);
4911 } else {
4912 releaseDispatchEntry(dispatchEntry);
4913 }
4914 }
4915
4916 // Start the next dispatch cycle for this connection.
4917 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918}
4919
4920bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004921 DispatchEntry* dispatchEntry,
4922 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004923 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004924 if (!handled) {
4925 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004926 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004927 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004928 return false;
4929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004931 // Get the fallback key state.
4932 // Clear it out after dispatching the UP.
4933 int32_t originalKeyCode = keyEntry->keyCode;
4934 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4935 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4936 connection->inputState.removeFallbackKey(originalKeyCode);
4937 }
4938
4939 if (handled || !dispatchEntry->hasForegroundTarget()) {
4940 // If the application handles the original key for which we previously
4941 // generated a fallback or if the window is not a foreground window,
4942 // then cancel the associated fallback key, if any.
4943 if (fallbackKeyCode != -1) {
4944 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004946 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004947 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4948 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4949 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004951 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004952 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953
4954 mLock.unlock();
4955
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004956 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004957 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958
4959 mLock.lock();
4960
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004961 // Cancel the fallback key.
4962 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004964 "application handled the original non-fallback key "
4965 "or is no longer a foreground target, "
4966 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967 options.keyCode = fallbackKeyCode;
4968 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004969 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004970 connection->inputState.removeFallbackKey(originalKeyCode);
4971 }
4972 } else {
4973 // If the application did not handle a non-fallback key, first check
4974 // that we are in a good state to perform unhandled key event processing
4975 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004976 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004977 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004978#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004979 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004980 "since this is not an initial down. "
4981 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4982 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004984 return false;
4985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004987 // Dispatch the unhandled key to the policy.
4988#if DEBUG_OUTBOUND_EVENT_DETAILS
4989 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004990 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4991 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004992#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004993 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004994
4995 mLock.unlock();
4996
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004997 bool fallback =
4998 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4999 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005000
5001 mLock.lock();
5002
5003 if (connection->status != Connection::STATUS_NORMAL) {
5004 connection->inputState.removeFallbackKey(originalKeyCode);
5005 return false;
5006 }
5007
5008 // Latch the fallback keycode for this key on an initial down.
5009 // The fallback keycode cannot change at any other point in the lifecycle.
5010 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005012 fallbackKeyCode = event.getKeyCode();
5013 } else {
5014 fallbackKeyCode = AKEYCODE_UNKNOWN;
5015 }
5016 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
5017 }
5018
5019 ALOG_ASSERT(fallbackKeyCode != -1);
5020
5021 // Cancel the fallback key if the policy decides not to send it anymore.
5022 // We will continue to dispatch the key to the policy but we will no
5023 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005024 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5025 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005026#if DEBUG_OUTBOUND_EVENT_DETAILS
5027 if (fallback) {
5028 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005029 "as a fallback for %d, but on the DOWN it had requested "
5030 "to send %d instead. Fallback canceled.",
5031 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005032 } else {
5033 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005034 "but on the DOWN it had requested to send %d. "
5035 "Fallback canceled.",
5036 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005037 }
5038#endif
5039
5040 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5041 "canceling fallback, policy no longer desires it");
5042 options.keyCode = fallbackKeyCode;
5043 synthesizeCancelationEventsForConnectionLocked(connection, options);
5044
5045 fallback = false;
5046 fallbackKeyCode = AKEYCODE_UNKNOWN;
5047 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005048 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005049 }
5050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051
5052#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005053 {
5054 std::string msg;
5055 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5056 connection->inputState.getFallbackKeys();
5057 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005058 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005059 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005060 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005061 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005062 }
5063#endif
5064
5065 if (fallback) {
5066 // Restart the dispatch cycle using the fallback key.
5067 keyEntry->eventTime = event.getEventTime();
5068 keyEntry->deviceId = event.getDeviceId();
5069 keyEntry->source = event.getSource();
5070 keyEntry->displayId = event.getDisplayId();
5071 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5072 keyEntry->keyCode = fallbackKeyCode;
5073 keyEntry->scanCode = event.getScanCode();
5074 keyEntry->metaState = event.getMetaState();
5075 keyEntry->repeatCount = event.getRepeatCount();
5076 keyEntry->downTime = event.getDownTime();
5077 keyEntry->syntheticRepeat = false;
5078
5079#if DEBUG_OUTBOUND_EVENT_DETAILS
5080 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005081 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5082 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005083#endif
5084 return true; // restart the event
5085 } else {
5086#if DEBUG_OUTBOUND_EVENT_DETAILS
5087 ALOGD("Unhandled key event: No fallback key.");
5088#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005089
5090 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005091 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 }
5093 }
5094 return false;
5095}
5096
5097bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005098 DispatchEntry* dispatchEntry,
5099 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 return false;
5101}
5102
5103void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5104 mLock.unlock();
5105
5106 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5107
5108 mLock.lock();
5109}
5110
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005111KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5112 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005113 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005114 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5115 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005116 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117}
5118
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005119void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5120 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121 // TODO Write some statistics about how long we spend waiting.
5122}
5123
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005124/**
5125 * Report the touch event latency to the statsd server.
5126 * Input events are reported for statistics if:
5127 * - This is a touchscreen event
5128 * - InputFilter is not enabled
5129 * - Event is not injected or synthesized
5130 *
5131 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5132 * from getting aggregated with the "old" data.
5133 */
5134void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5135 REQUIRES(mLock) {
5136 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5137 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5138 if (!reportForStatistics) {
5139 return;
5140 }
5141
5142 if (mTouchStatistics.shouldReport()) {
5143 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5144 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5145 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5146 mTouchStatistics.reset();
5147 }
5148 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5149 mTouchStatistics.addValue(latencyMicros);
5150}
5151
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152void InputDispatcher::traceInboundQueueLengthLocked() {
5153 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005154 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155 }
5156}
5157
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005158void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 if (ATRACE_ENABLED()) {
5160 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005161 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005162 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163 }
5164}
5165
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005166void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 if (ATRACE_ENABLED()) {
5168 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005169 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005170 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 }
5172}
5173
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005174void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005175 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005177 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178 dumpDispatchStateLocked(dump);
5179
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005180 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005181 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005182 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 }
5184}
5185
5186void InputDispatcher::monitor() {
5187 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005188 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005189 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005190 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005191}
5192
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005193/**
5194 * Wake up the dispatcher and wait until it processes all events and commands.
5195 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5196 * this method can be safely called from any thread, as long as you've ensured that
5197 * the work you are interested in completing has already been queued.
5198 */
5199bool InputDispatcher::waitForIdle() {
5200 /**
5201 * Timeout should represent the longest possible time that a device might spend processing
5202 * events and commands.
5203 */
5204 constexpr std::chrono::duration TIMEOUT = 100ms;
5205 std::unique_lock lock(mLock);
5206 mLooper->wake();
5207 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5208 return result == std::cv_status::no_timeout;
5209}
5210
Vishnu Naire798b472020-07-23 13:52:21 -07005211/**
5212 * Sets focus to the window identified by the token. This must be called
5213 * after updating any input window handles.
5214 *
5215 * Params:
5216 * request.token - input channel token used to identify the window that should gain focus.
5217 * request.focusedToken - the token that the caller expects currently to be focused. If the
5218 * specified token does not match the currently focused window, this request will be dropped.
5219 * If the specified focused token matches the currently focused window, the call will succeed.
5220 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5221 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5222 * when requesting the focus change. This determines which request gets
5223 * precedence if there is a focus change request from another source such as pointer down.
5224 */
5225void InputDispatcher::setFocusedWindow(const FocusRequest&) {}
Garfield Tane84e6f92019-08-29 17:28:41 -07005226} // namespace android::inputdispatcher