blob: 3bdbcce79b5923f328ba125ea665ab0605fcf1e4 [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) {
274 if (inputTarget.useDefaultPointerInfo()) {
275 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
276 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
277 inputTargetFlags, pointerInfo.xOffset,
278 pointerInfo.yOffset, inputTarget.globalScaleFactor,
279 pointerInfo.windowXScale, pointerInfo.windowYScale);
280 }
281
282 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
283 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
284
285 PointerCoords pointerCoords[motionEntry.pointerCount];
286
287 // Use the first pointer information to normalize all other pointers. This could be any pointer
288 // as long as all other pointers are normalized to the same value and the final DispatchEntry
289 // uses the offset and scale for the normalized pointer.
290 const PointerInfo& firstPointerInfo =
291 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
292
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);
297 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
298
299 // The scale factor is the ratio of the current pointers scale to the normalized scale.
300 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
301 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
302
303 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
304 // First apply the current pointers offset to set the window at 0,0
305 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
306 // Next scale the coordinates.
307 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
308 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
309 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
310 -firstPointerInfo.yOffset);
311 }
312
313 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800314 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000315 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
316 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
317 motionEntry.metaState, motionEntry.buttonState,
318 motionEntry.classification, motionEntry.edgeFlags,
319 motionEntry.xPrecision, motionEntry.yPrecision,
320 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
321 motionEntry.downTime, motionEntry.pointerCount,
322 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
323 0 /* yOffset */);
324
325 if (motionEntry.injectionState) {
326 combinedMotionEntry->injectionState = motionEntry.injectionState;
327 combinedMotionEntry->injectionState->refCount += 1;
328 }
329
330 std::unique_ptr<DispatchEntry> dispatchEntry =
331 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
332 inputTargetFlags, firstPointerInfo.xOffset,
333 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
334 firstPointerInfo.windowXScale,
335 firstPointerInfo.windowYScale);
336 combinedMotionEntry->release();
337 return dispatchEntry;
338}
339
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700340static void addGestureMonitors(const std::vector<Monitor>& monitors,
341 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
342 float yOffset = 0) {
343 if (monitors.empty()) {
344 return;
345 }
346 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
347 for (const Monitor& monitor : monitors) {
348 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
349 }
350}
351
Gang Wang342c9272020-01-13 13:15:04 -0500352static std::array<uint8_t, 128> getRandomKey() {
353 std::array<uint8_t, 128> key;
354 if (RAND_bytes(key.data(), key.size()) != 1) {
355 LOG_ALWAYS_FATAL("Can't generate HMAC key");
356 }
357 return key;
358}
359
360// --- HmacKeyManager ---
361
362HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
363
364std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
365 size_t size;
366 switch (event.type) {
367 case VerifiedInputEvent::Type::KEY: {
368 size = sizeof(VerifiedKeyEvent);
369 break;
370 }
371 case VerifiedInputEvent::Type::MOTION: {
372 size = sizeof(VerifiedMotionEvent);
373 break;
374 }
375 }
Gang Wang342c9272020-01-13 13:15:04 -0500376 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700377 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500378}
379
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700380std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500381 // SHA256 always generates 32-bytes result
382 std::array<uint8_t, 32> hash;
383 unsigned int hashLen = 0;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700384 uint8_t* result =
385 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500386 if (result == nullptr) {
387 ALOGE("Could not sign the data using HMAC");
388 return INVALID_HMAC;
389 }
390
391 if (hashLen != hash.size()) {
392 ALOGE("HMAC-SHA256 has unexpected length");
393 return INVALID_HMAC;
394 }
395
396 return hash;
397}
398
Michael Wrightd02c5b62014-02-10 15:10:22 -0800399// --- InputDispatcher ---
400
Garfield Tan00f511d2019-06-12 16:55:40 -0700401InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
402 : mPolicy(policy),
403 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700404 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800405 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700406 mAppSwitchSawKeyDown(false),
407 mAppSwitchDueTime(LONG_LONG_MAX),
408 mNextUnblockedEvent(nullptr),
409 mDispatchEnabled(false),
410 mDispatchFrozen(false),
411 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800412 // mInTouchMode will be initialized by the WindowManager to the default device config.
413 // To avoid leaking stack in case that call never comes, and for tests,
414 // initialize it here anyways.
415 mInTouchMode(true),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700416 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800418 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419
Yi Kong9b14ac62018-07-17 13:48:38 -0700420 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800421
422 policy->getDispatcherConfiguration(&mConfig);
423}
424
425InputDispatcher::~InputDispatcher() {
426 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800427 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800428
429 resetKeyRepeatLocked();
430 releasePendingEventLocked();
431 drainInboundQueueLocked();
432 }
433
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700434 while (!mConnectionsByFd.empty()) {
435 sp<Connection> connection = mConnectionsByFd.begin()->second;
436 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437 }
438}
439
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700440status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700441 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700442 return ALREADY_EXISTS;
443 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700444 mThread = std::make_unique<InputThread>(
445 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
446 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700447}
448
449status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700450 if (mThread && mThread->isCallingThread()) {
451 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700452 return INVALID_OPERATION;
453 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700454 mThread.reset();
455 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700456}
457
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458void InputDispatcher::dispatchOnce() {
459 nsecs_t nextWakeupTime = LONG_LONG_MAX;
460 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800461 std::scoped_lock _l(mLock);
462 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463
464 // Run a dispatch loop if there are no pending commands.
465 // The dispatch loop might enqueue commands to run afterwards.
466 if (!haveCommandsLocked()) {
467 dispatchOnceInnerLocked(&nextWakeupTime);
468 }
469
470 // Run all pending commands if there are any.
471 // If any commands were run then force the next poll to wake up immediately.
472 if (runCommandsLockedInterruptible()) {
473 nextWakeupTime = LONG_LONG_MIN;
474 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800475
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700476 // If we are still waiting for ack on some events,
477 // we might have to wake up earlier to check if an app is anr'ing.
478 const nsecs_t nextAnrCheck = processAnrsLocked();
479 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
480
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800481 // We are about to enter an infinitely long sleep, because we have no commands or
482 // pending or queued events
483 if (nextWakeupTime == LONG_LONG_MAX) {
484 mDispatcherEnteredIdle.notify_all();
485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800486 } // release lock
487
488 // Wait for callback or timeout or wake. (make sure we round up, not down)
489 nsecs_t currentTime = now();
490 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
491 mLooper->pollOnce(timeoutMillis);
492}
493
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700494/**
495 * Check if any of the connections' wait queues have events that are too old.
496 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
497 * Return the time at which we should wake up next.
498 */
499nsecs_t InputDispatcher::processAnrsLocked() {
500 const nsecs_t currentTime = now();
501 nsecs_t nextAnrCheck = LONG_LONG_MAX;
502 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
503 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
504 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
505 onAnrLocked(mAwaitedFocusedApplication);
506 mAwaitedFocusedApplication.clear();
507 return LONG_LONG_MIN;
508 } else {
509 // Keep waiting
510 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
511 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
512 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
513 }
514 }
515
516 // Check if any connection ANRs are due
517 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
518 if (currentTime < nextAnrCheck) { // most likely scenario
519 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
520 }
521
522 // If we reached here, we have an unresponsive connection.
523 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
524 if (connection == nullptr) {
525 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
526 return nextAnrCheck;
527 }
528 connection->responsive = false;
529 // Stop waking up for this unresponsive connection
530 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
531 onAnrLocked(connection);
532 return LONG_LONG_MIN;
533}
534
535nsecs_t InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
536 sp<InputWindowHandle> window = getWindowHandleLocked(token);
537 if (window != nullptr) {
538 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT).count();
539 }
540 return DEFAULT_INPUT_DISPATCHING_TIMEOUT.count();
541}
542
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
544 nsecs_t currentTime = now();
545
Jeff Browndc5992e2014-04-11 01:27:26 -0700546 // Reset the key repeat timer whenever normal dispatch is suspended while the
547 // device is in a non-interactive state. This is to ensure that we abort a key
548 // repeat if the device is just coming out of sleep.
549 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 resetKeyRepeatLocked();
551 }
552
553 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
554 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100555 if (DEBUG_FOCUS) {
556 ALOGD("Dispatch frozen. Waiting some more.");
557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 return;
559 }
560
561 // Optimize latency of app switches.
562 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
563 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
564 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
565 if (mAppSwitchDueTime < *nextWakeupTime) {
566 *nextWakeupTime = mAppSwitchDueTime;
567 }
568
569 // Ready to start a new event.
570 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700571 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700572 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800573 if (isAppSwitchDue) {
574 // The inbound queue is empty so the app switch key we were waiting
575 // for will never arrive. Stop waiting for it.
576 resetPendingAppSwitchLocked(false);
577 isAppSwitchDue = false;
578 }
579
580 // Synthesize a key repeat if appropriate.
581 if (mKeyRepeatState.lastKeyEntry) {
582 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
583 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
584 } else {
585 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
586 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
587 }
588 }
589 }
590
591 // Nothing to do if there is no pending event.
592 if (!mPendingEvent) {
593 return;
594 }
595 } else {
596 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700597 mPendingEvent = mInboundQueue.front();
598 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599 traceInboundQueueLengthLocked();
600 }
601
602 // Poke user activity for this event.
603 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700604 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606 }
607
608 // Now we have an event to dispatch.
609 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700610 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700612 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800613 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700614 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800615 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700616 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 }
618
619 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700620 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 }
622
623 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700624 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700625 ConfigurationChangedEntry* typedEntry =
626 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
627 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700628 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700629 break;
630 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700632 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700633 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
634 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700635 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700636 break;
637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800638
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100639 case EventEntry::Type::FOCUS: {
640 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
641 dispatchFocusLocked(currentTime, typedEntry);
642 done = true;
643 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
644 break;
645 }
646
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700647 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700648 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
649 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700650 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700651 resetPendingAppSwitchLocked(true);
652 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700653 } else if (dropReason == DropReason::NOT_DROPPED) {
654 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700655 }
656 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700657 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700658 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700659 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700660 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
661 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700662 }
663 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
664 break;
665 }
666
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700667 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700668 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700669 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
670 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700672 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700673 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700674 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700675 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
676 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700677 }
678 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
679 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 }
682
683 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700684 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700685 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 }
Michael Wright3a981722015-06-10 15:26:13 +0100687 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688
689 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700690 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691 }
692}
693
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700694/**
695 * Return true if the events preceding this incoming motion event should be dropped
696 * Return false otherwise (the default behaviour)
697 */
698bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700699 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700700 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700701
702 // Optimize case where the current application is unresponsive and the user
703 // decides to touch a window in a different application.
704 // If the application takes too long to catch up then we drop all events preceding
705 // the touch into the other window.
706 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700707 int32_t displayId = motionEntry.displayId;
708 int32_t x = static_cast<int32_t>(
709 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
710 int32_t y = static_cast<int32_t>(
711 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
712 sp<InputWindowHandle> touchedWindowHandle =
713 findTouchedWindowAtLocked(displayId, x, y, nullptr);
714 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700715 touchedWindowHandle->getApplicationToken() !=
716 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700717 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700718 ALOGI("Pruning input queue because user touched a different application while waiting "
719 "for %s",
720 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700721 return true;
722 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700723
724 // Alternatively, maybe there's a gesture monitor that could handle this event
725 std::vector<TouchedMonitor> gestureMonitors =
726 findTouchedGestureMonitorsLocked(displayId, {});
727 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
728 sp<Connection> connection =
729 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000730 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700731 // This monitor could take more input. Drop all events preceding this
732 // event, so that gesture monitor could get a chance to receive the stream
733 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
734 "responsive gesture monitor that may handle the event",
735 mAwaitedFocusedApplication->getName().c_str());
736 return true;
737 }
738 }
739 }
740
741 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
742 // yet been processed by some connections, the dispatcher will wait for these motion
743 // events to be processed before dispatching the key event. This is because these motion events
744 // may cause a new window to be launched, which the user might expect to receive focus.
745 // To prevent waiting forever for such events, just send the key to the currently focused window
746 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
747 ALOGD("Received a new pointer down event, stop waiting for events to process and "
748 "just send the pending key event to the focused window.");
749 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700750 }
751 return false;
752}
753
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700755 bool needWake = mInboundQueue.empty();
756 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757 traceInboundQueueLengthLocked();
758
759 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700760 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700761 // Optimize app switch latency.
762 // If the application takes too long to catch up then we drop all events preceding
763 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700764 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700765 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700766 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700767 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700768 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700769 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700771 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700773 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700774 mAppSwitchSawKeyDown = false;
775 needWake = true;
776 }
777 }
778 }
779 break;
780 }
781
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700782 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700783 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
784 mNextUnblockedEvent = entry;
785 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700787 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100789 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700790 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
791 break;
792 }
793 case EventEntry::Type::CONFIGURATION_CHANGED:
794 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700795 // nothing to do
796 break;
797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 }
799
800 return needWake;
801}
802
803void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
804 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700805 mRecentQueue.push_back(entry);
806 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
807 mRecentQueue.front()->release();
808 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809 }
810}
811
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700813 int32_t y, TouchState* touchState,
814 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700815 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700816 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
817 LOG_ALWAYS_FATAL(
818 "Must provide a valid touch state if adding portal windows or outside targets");
819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800821 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
822 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 const InputWindowInfo* windowInfo = windowHandle->getInfo();
824 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100825 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826
827 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100828 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
829 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
830 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800832 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700833 if (portalToDisplayId != ADISPLAY_ID_NONE &&
834 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800835 if (addPortalWindows) {
836 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700837 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800838 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700839 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700840 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 // Found window.
843 return windowHandle;
844 }
845 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800846
Michael Wright44753b12020-07-08 13:48:11 +0100847 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700848 touchState->addOrUpdateWindow(windowHandle,
849 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
850 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 }
854 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700855 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856}
857
Garfield Tane84e6f92019-08-29 17:28:41 -0700858std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700859 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000860 std::vector<TouchedMonitor> touchedMonitors;
861
862 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
863 addGestureMonitors(monitors, touchedMonitors);
864 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
865 const InputWindowInfo* windowInfo = portalWindow->getInfo();
866 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700867 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
868 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000869 }
870 return touchedMonitors;
871}
872
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700873void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 const char* reason;
875 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700876 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700878 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700880 reason = "inbound event was dropped because the policy consumed it";
881 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700882 case DropReason::DISABLED:
883 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 ALOGI("Dropped event because input dispatch is disabled.");
885 }
886 reason = "inbound event was dropped because input dispatch is disabled";
887 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700888 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700889 ALOGI("Dropped event because of pending overdue app switch.");
890 reason = "inbound event was dropped because of pending overdue app switch";
891 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700892 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700893 ALOGI("Dropped event because the current application is not responding and the user "
894 "has started interacting with a different application.");
895 reason = "inbound event was dropped because the current application is not responding "
896 "and the user has started interacting with a different application";
897 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700898 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 ALOGI("Dropped event because it is stale.");
900 reason = "inbound event was dropped because it is stale";
901 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700902 case DropReason::NOT_DROPPED: {
903 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700904 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700905 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 }
907
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700908 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700909 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
911 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700912 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700914 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700915 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
916 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700917 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
918 synthesizeCancelationEventsForAllConnectionsLocked(options);
919 } else {
920 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
921 synthesizeCancelationEventsForAllConnectionsLocked(options);
922 }
923 break;
924 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100925 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700926 case EventEntry::Type::CONFIGURATION_CHANGED:
927 case EventEntry::Type::DEVICE_RESET: {
928 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
929 break;
930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 }
932}
933
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800934static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700935 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
936 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937}
938
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700939bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
940 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
941 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
942 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943}
944
945bool InputDispatcher::isAppSwitchPendingLocked() {
946 return mAppSwitchDueTime != LONG_LONG_MAX;
947}
948
949void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
950 mAppSwitchDueTime = LONG_LONG_MAX;
951
952#if DEBUG_APP_SWITCH
953 if (handled) {
954 ALOGD("App switch has arrived.");
955 } else {
956 ALOGD("App switch was abandoned.");
957 }
958#endif
959}
960
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700962 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963}
964
965bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700966 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 return false;
968 }
969
970 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700971 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700972 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700974 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975
976 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700977 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 return true;
979}
980
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700981void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
982 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983}
984
985void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700986 while (!mInboundQueue.empty()) {
987 EventEntry* entry = mInboundQueue.front();
988 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 releaseInboundEventLocked(entry);
990 }
991 traceInboundQueueLengthLocked();
992}
993
994void InputDispatcher::releasePendingEventLocked() {
995 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700997 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 }
999}
1000
1001void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
1002 InjectionState* injectionState = entry->injectionState;
1003 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1004#if DEBUG_DISPATCH_CYCLE
1005 ALOGD("Injected inbound event was dropped.");
1006#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001007 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 }
1009 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001010 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 }
1012 addRecentEventLocked(entry);
1013 entry->release();
1014}
1015
1016void InputDispatcher::resetKeyRepeatLocked() {
1017 if (mKeyRepeatState.lastKeyEntry) {
1018 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001019 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 }
1021}
1022
Garfield Tane84e6f92019-08-29 17:28:41 -07001023KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1025
1026 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001027 uint32_t policyFlags = entry->policyFlags &
1028 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 if (entry->refCount == 1) {
1030 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001031 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 entry->eventTime = currentTime;
1033 entry->policyFlags = policyFlags;
1034 entry->repeatCount += 1;
1035 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001036 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001037 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001038 entry->displayId, policyFlags, entry->action, entry->flags,
1039 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001040 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041
1042 mKeyRepeatState.lastKeyEntry = newEntry;
1043 entry->release();
1044
1045 entry = newEntry;
1046 }
1047 entry->syntheticRepeat = true;
1048
1049 // Increment reference count since we keep a reference to the event in
1050 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1051 entry->refCount += 1;
1052
1053 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1054 return entry;
1055}
1056
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001057bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1058 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001060 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061#endif
1062
1063 // Reset key repeating in case a keyboard device was added or removed or something.
1064 resetKeyRepeatLocked();
1065
1066 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001067 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1068 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001070 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 return true;
1072}
1073
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001074bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001076 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078#endif
1079
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081 options.deviceId = entry->deviceId;
1082 synthesizeCancelationEventsForAllConnectionsLocked(options);
1083 return true;
1084}
1085
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001086void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001087 if (mPendingEvent != nullptr) {
1088 // Move the pending event to the front of the queue. This will give the chance
1089 // for the pending event to get dispatched to the newly focused window
1090 mInboundQueue.push_front(mPendingEvent);
1091 mPendingEvent = nullptr;
1092 }
1093
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001094 FocusEntry* focusEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001095 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001096
1097 // This event should go to the front of the queue, but behind all other focus events
1098 // Find the last focus event, and insert right after it
1099 std::deque<EventEntry*>::reverse_iterator it =
1100 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1101 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1102
1103 // Maintain the order of focus events. Insert the entry after all other focus events.
1104 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001105}
1106
1107void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1108 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1109 if (channel == nullptr) {
1110 return; // Window has gone away
1111 }
1112 InputTarget target;
1113 target.inputChannel = channel;
1114 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1115 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001116 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1117 channel->getName();
1118 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001119 dispatchEventLocked(currentTime, entry, {target});
1120}
1121
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001123 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001125 if (!entry->dispatchInProgress) {
1126 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1127 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1128 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1129 if (mKeyRepeatState.lastKeyEntry &&
1130 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 // We have seen two identical key downs in a row which indicates that the device
1132 // driver is automatically generating key repeats itself. We take note of the
1133 // repeat here, but we disable our own next key repeat timer since it is clear that
1134 // we will not need to synthesize key repeats ourselves.
1135 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1136 resetKeyRepeatLocked();
1137 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1138 } else {
1139 // Not a repeat. Save key down state in case we do see a repeat later.
1140 resetKeyRepeatLocked();
1141 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1142 }
1143 mKeyRepeatState.lastKeyEntry = entry;
1144 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001145 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 resetKeyRepeatLocked();
1147 }
1148
1149 if (entry->repeatCount == 1) {
1150 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1151 } else {
1152 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1153 }
1154
1155 entry->dispatchInProgress = true;
1156
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001157 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 }
1159
1160 // Handle case where the policy asked us to try again later last time.
1161 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1162 if (currentTime < entry->interceptKeyWakeupTime) {
1163 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1164 *nextWakeupTime = entry->interceptKeyWakeupTime;
1165 }
1166 return false; // wait until next wakeup
1167 }
1168 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1169 entry->interceptKeyWakeupTime = 0;
1170 }
1171
1172 // Give the policy a chance to intercept the key.
1173 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1174 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001175 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001176 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001177 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001178 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001179 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001180 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 }
1182 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001183 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 entry->refCount += 1;
1185 return false; // wait for the command to run
1186 } else {
1187 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1188 }
1189 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001190 if (*dropReason == DropReason::NOT_DROPPED) {
1191 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 }
1193 }
1194
1195 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001196 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001197 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001198 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001199 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001200 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 return true;
1202 }
1203
1204 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001205 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001206 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001207 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1209 return false;
1210 }
1211
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001212 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1214 return true;
1215 }
1216
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001217 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001218 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219
1220 // Dispatch the key.
1221 dispatchEventLocked(currentTime, entry, inputTargets);
1222 return true;
1223}
1224
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001225void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001227 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001228 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1229 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001230 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1231 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1232 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233#endif
1234}
1235
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001236bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1237 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001238 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001240 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 entry->dispatchInProgress = true;
1242
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001243 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 }
1245
1246 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001247 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001248 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001249 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001250 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 return true;
1252 }
1253
1254 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1255
1256 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001257 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258
1259 bool conflictingPointerActions = false;
1260 int32_t injectionResult;
1261 if (isPointerEvent) {
1262 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001263 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001264 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001265 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 } else {
1267 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001268 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001269 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 }
1271 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1272 return false;
1273 }
1274
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001275 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001276 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1277 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1278 return true;
1279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001281 CancelationOptions::Mode mode(isPointerEvent
1282 ? CancelationOptions::CANCEL_POINTER_EVENTS
1283 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1284 CancelationOptions options(mode, "input event injection failed");
1285 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 return true;
1287 }
1288
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001289 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001290 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001292 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001293 std::unordered_map<int32_t, TouchState>::iterator it =
1294 mTouchStatesByDisplay.find(entry->displayId);
1295 if (it != mTouchStatesByDisplay.end()) {
1296 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001297 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001298 // The event has gone through these portal windows, so we add monitoring targets of
1299 // the corresponding displays as well.
1300 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001301 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001302 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001303 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001304 }
1305 }
1306 }
1307 }
1308
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309 // Dispatch the motion.
1310 if (conflictingPointerActions) {
1311 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001312 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 synthesizeCancelationEventsForAllConnectionsLocked(options);
1314 }
1315 dispatchEventLocked(currentTime, entry, inputTargets);
1316 return true;
1317}
1318
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001319void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001321 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001322 ", policyFlags=0x%x, "
1323 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1324 "metaState=0x%x, buttonState=0x%x,"
1325 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001326 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1327 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1328 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001330 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001332 "x=%f, y=%f, pressure=%f, size=%f, "
1333 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1334 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001335 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1336 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1337 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1338 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1339 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1340 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1341 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1342 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1343 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1344 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 }
1346#endif
1347}
1348
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001349void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1350 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001351 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352#if DEBUG_DISPATCH_CYCLE
1353 ALOGD("dispatchEventToCurrentInputTargets");
1354#endif
1355
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001356 updateInteractionTokensLocked(*eventEntry, inputTargets);
1357
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1359
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001360 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001362 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001363 sp<Connection> connection =
1364 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001365 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001366 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001368 if (DEBUG_FOCUS) {
1369 ALOGD("Dropping event delivery to target with channel '%s' because it "
1370 "is no longer registered with the input dispatcher.",
1371 inputTarget.inputChannel->getName().c_str());
1372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373 }
1374 }
1375}
1376
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001377void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1378 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1379 // If the policy decides to close the app, we will get a channel removal event via
1380 // unregisterInputChannel, and will clean up the connection that way. We are already not
1381 // sending new pointers to the connection when it blocked, but focused events will continue to
1382 // pile up.
1383 ALOGW("Canceling events for %s because it is unresponsive",
1384 connection->inputChannel->getName().c_str());
1385 if (connection->status == Connection::STATUS_NORMAL) {
1386 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1387 "application not responding");
1388 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 }
1390}
1391
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001392void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001393 if (DEBUG_FOCUS) {
1394 ALOGD("Resetting ANR timeouts.");
1395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396
1397 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001398 mNoFocusedWindowTimeoutTime = std::nullopt;
1399 mAwaitedFocusedApplication.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400}
1401
Tiger Huang721e26f2018-07-24 22:26:19 +08001402/**
1403 * Get the display id that the given event should go to. If this event specifies a valid display id,
1404 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1405 * Focused display is the display that the user most recently interacted with.
1406 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001407int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001408 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001409 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001410 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001411 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1412 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001413 break;
1414 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001415 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001416 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1417 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001418 break;
1419 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001420 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001421 case EventEntry::Type::CONFIGURATION_CHANGED:
1422 case EventEntry::Type::DEVICE_RESET: {
1423 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001424 return ADISPLAY_ID_NONE;
1425 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001426 }
1427 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1428}
1429
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001430bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1431 const char* focusedWindowName) {
1432 if (mAnrTracker.empty()) {
1433 // already processed all events that we waited for
1434 mKeyIsWaitingForEventsTimeout = std::nullopt;
1435 return false;
1436 }
1437
1438 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1439 // Start the timer
1440 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1441 "focus to change",
1442 focusedWindowName);
1443 mKeyIsWaitingForEventsTimeout = currentTime + KEY_WAITING_FOR_EVENTS_TIMEOUT.count();
1444 return true;
1445 }
1446
1447 // We still have pending events, and already started the timer
1448 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1449 return true; // Still waiting
1450 }
1451
1452 // Waited too long, and some connection still hasn't processed all motions
1453 // Just send the key to the focused window
1454 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1455 focusedWindowName);
1456 mKeyIsWaitingForEventsTimeout = std::nullopt;
1457 return false;
1458}
1459
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001461 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001462 std::vector<InputTarget>& inputTargets,
1463 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001464 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465
Tiger Huang721e26f2018-07-24 22:26:19 +08001466 int32_t displayId = getTargetDisplayId(entry);
1467 sp<InputWindowHandle> focusedWindowHandle =
1468 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1469 sp<InputApplicationHandle> focusedApplicationHandle =
1470 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1471
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 // If there is no currently focused window and no focused application
1473 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001474 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1475 ALOGI("Dropping %s event because there is no focused window or focused application in "
1476 "display %" PRId32 ".",
1477 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001478 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 }
1480
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001481 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1482 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1483 // start interacting with another application via touch (app switch). This code can be removed
1484 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1485 // an app is expected to have a focused window.
1486 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1487 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1488 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001489 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1490 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1491 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001492 mAwaitedFocusedApplication = focusedApplicationHandle;
1493 ALOGW("Waiting because no window has focus but %s may eventually add a "
1494 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001495 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001496 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1497 return INPUT_EVENT_INJECTION_PENDING;
1498 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1499 // Already raised ANR. Drop the event
1500 ALOGE("Dropping %s event because there is no focused window",
1501 EventEntry::typeToString(entry.type));
1502 return INPUT_EVENT_INJECTION_FAILED;
1503 } else {
1504 // Still waiting for the focused window
1505 return INPUT_EVENT_INJECTION_PENDING;
1506 }
1507 }
1508
1509 // we have a valid, non-null focused window
1510 resetNoFocusedWindowTimeoutLocked();
1511
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001513 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001514 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 }
1516
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001517 if (focusedWindowHandle->getInfo()->paused) {
1518 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1519 return INPUT_EVENT_INJECTION_PENDING;
1520 }
1521
1522 // If the event is a key event, then we must wait for all previous events to
1523 // complete before delivering it because previous events may have the
1524 // side-effect of transferring focus to a different window and we want to
1525 // ensure that the following keys are sent to the new window.
1526 //
1527 // Suppose the user touches a button in a window then immediately presses "A".
1528 // If the button causes a pop-up window to appear then we want to ensure that
1529 // the "A" key is delivered to the new pop-up window. This is because users
1530 // often anticipate pending UI changes when typing on a keyboard.
1531 // To obtain this behavior, we must serialize key events with respect to all
1532 // prior input events.
1533 if (entry.type == EventEntry::Type::KEY) {
1534 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1535 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1536 return INPUT_EVENT_INJECTION_PENDING;
1537 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 }
1539
1540 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001541 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001542 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1543 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544
1545 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001546 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547}
1548
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001549/**
1550 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1551 * that are currently unresponsive.
1552 */
1553std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1554 const std::vector<TouchedMonitor>& monitors) const {
1555 std::vector<TouchedMonitor> responsiveMonitors;
1556 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1557 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1558 sp<Connection> connection = getConnectionLocked(
1559 monitor.monitor.inputChannel->getConnectionToken());
1560 if (connection == nullptr) {
1561 ALOGE("Could not find connection for monitor %s",
1562 monitor.monitor.inputChannel->getName().c_str());
1563 return false;
1564 }
1565 if (!connection->responsive) {
1566 ALOGW("Unresponsive monitor %s will not get the new gesture",
1567 connection->inputChannel->getName().c_str());
1568 return false;
1569 }
1570 return true;
1571 });
1572 return responsiveMonitors;
1573}
1574
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001576 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001577 std::vector<InputTarget>& inputTargets,
1578 nsecs_t* nextWakeupTime,
1579 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001580 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 enum InjectionPermission {
1582 INJECTION_PERMISSION_UNKNOWN,
1583 INJECTION_PERMISSION_GRANTED,
1584 INJECTION_PERMISSION_DENIED
1585 };
1586
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 // For security reasons, we defer updating the touch state until we are sure that
1588 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001589 int32_t displayId = entry.displayId;
1590 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1592
1593 // Update the touch state as needed based on the properties of the touch event.
1594 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1595 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001596 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1597 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001599 // Copy current touch state into tempTouchState.
1600 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1601 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001602 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001603 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001604 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1605 mTouchStatesByDisplay.find(displayId);
1606 if (oldStateIt != mTouchStatesByDisplay.end()) {
1607 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001608 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001609 }
1610
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001611 bool isSplit = tempTouchState.split;
1612 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1613 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1614 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001615 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1616 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1617 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1618 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1619 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001620 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 bool wrongDevice = false;
1622 if (newGesture) {
1623 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001624 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001625 ALOGI("Dropping event because a pointer for a different device is already down "
1626 "in display %" PRId32,
1627 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001628 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1630 switchedDevice = false;
1631 wrongDevice = true;
1632 goto Failed;
1633 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001634 tempTouchState.reset();
1635 tempTouchState.down = down;
1636 tempTouchState.deviceId = entry.deviceId;
1637 tempTouchState.source = entry.source;
1638 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001640 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001641 ALOGI("Dropping move event because a pointer for a different device is already active "
1642 "in display %" PRId32,
1643 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001644 // TODO: test multiple simultaneous input streams.
1645 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1646 switchedDevice = false;
1647 wrongDevice = true;
1648 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 }
1650
1651 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1652 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1653
Garfield Tan00f511d2019-06-12 16:55:40 -07001654 int32_t x;
1655 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001657 // Always dispatch mouse events to cursor position.
1658 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001659 x = int32_t(entry.xCursorPosition);
1660 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001661 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001662 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1663 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001664 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001665 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001666 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001667 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1668 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001669
1670 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001671 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001672 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001675 if (newTouchedWindowHandle != nullptr &&
1676 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001677 // New window supports splitting, but we should never split mouse events.
1678 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 } else if (isSplit) {
1680 // New window does not support splitting but we have already split events.
1681 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001682 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 }
1684
1685 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001686 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001688 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001689 }
1690
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001691 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1692 ALOGI("Not sending touch event to %s because it is paused",
1693 newTouchedWindowHandle->getName().c_str());
1694 newTouchedWindowHandle = nullptr;
1695 }
1696
1697 if (newTouchedWindowHandle != nullptr) {
1698 sp<Connection> connection = getConnectionLocked(newTouchedWindowHandle->getToken());
1699 if (connection == nullptr) {
1700 ALOGI("Could not find connection for %s",
1701 newTouchedWindowHandle->getName().c_str());
1702 newTouchedWindowHandle = nullptr;
1703 } else if (!connection->responsive) {
1704 // don't send the new touch to an unresponsive window
1705 ALOGW("Unresponsive window %s will not get the new gesture at %" PRIu64,
1706 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1707 newTouchedWindowHandle = nullptr;
1708 }
1709 }
1710
1711 // Also don't send the new touch event to unresponsive gesture monitors
1712 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1713
Michael Wright3dd60e22019-03-27 22:06:44 +00001714 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1715 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001716 "(%d, %d) in display %" PRId32 ".",
1717 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001718 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1719 goto Failed;
1720 }
1721
1722 if (newTouchedWindowHandle != nullptr) {
1723 // Set target flags.
1724 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1725 if (isSplit) {
1726 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001728 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1729 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1730 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1731 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1732 }
1733
1734 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001735 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1736 newHoverWindowHandle = nullptr;
1737 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001738 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001739 }
1740
1741 // Update the temporary touch state.
1742 BitSet32 pointerIds;
1743 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001744 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001745 pointerIds.markBit(pointerId);
1746 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001747 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 }
1749
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001750 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 } else {
1752 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1753
1754 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001755 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001756 if (DEBUG_FOCUS) {
1757 ALOGD("Dropping event because the pointer is not down or we previously "
1758 "dropped the pointer down event in display %" PRId32,
1759 displayId);
1760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1762 goto Failed;
1763 }
1764
1765 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001766 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001767 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001768 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1769 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770
1771 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001772 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001773 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001774 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1775 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001776 if (DEBUG_FOCUS) {
1777 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1778 oldTouchedWindowHandle->getName().c_str(),
1779 newTouchedWindowHandle->getName().c_str(), displayId);
1780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001782 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1783 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1784 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785
1786 // Make a slippery entrance into the new window.
1787 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1788 isSplit = true;
1789 }
1790
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001791 int32_t targetFlags =
1792 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 if (isSplit) {
1794 targetFlags |= InputTarget::FLAG_SPLIT;
1795 }
1796 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1797 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1798 }
1799
1800 BitSet32 pointerIds;
1801 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001802 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001804 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805 }
1806 }
1807 }
1808
1809 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001810 // Let the previous window know that the hover sequence is over, unless we already did it
1811 // when dispatching it as is to newTouchedWindowHandle.
1812 if (mLastHoverWindowHandle != nullptr &&
1813 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1814 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815#if DEBUG_HOVER
1816 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001817 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001819 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1820 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 }
1822
Garfield Tandf26e862020-07-01 20:18:19 -07001823 // Let the new window know that the hover sequence is starting, unless we already did it
1824 // when dispatching it as is to newTouchedWindowHandle.
1825 if (newHoverWindowHandle != nullptr &&
1826 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1827 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828#if DEBUG_HOVER
1829 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001830 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001832 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1833 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1834 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001835 }
1836 }
1837
1838 // Check permission to inject into all touched foreground windows and ensure there
1839 // is at least one touched foreground window.
1840 {
1841 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001842 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1844 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001845 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1847 injectionPermission = INJECTION_PERMISSION_DENIED;
1848 goto Failed;
1849 }
1850 }
1851 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001852 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001853 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001854 ALOGI("Dropping event because there is no touched foreground window in display "
1855 "%" PRId32 " or gesture monitor to receive it.",
1856 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1858 goto Failed;
1859 }
1860
1861 // Permission granted to injection into all touched foreground windows.
1862 injectionPermission = INJECTION_PERMISSION_GRANTED;
1863 }
1864
1865 // Check whether windows listening for outside touches are owned by the same UID. If it is
1866 // set the policy flag that we will not reveal coordinate information to this window.
1867 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1868 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001869 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001870 if (foregroundWindowHandle) {
1871 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001872 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001873 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1874 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1875 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001876 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1877 InputTarget::FLAG_ZERO_COORDS,
1878 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880 }
1881 }
1882 }
1883 }
1884
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 // If this is the first pointer going down and the touched window has a wallpaper
1886 // then also add the touched wallpaper windows so they are locked in for the duration
1887 // of the touch gesture.
1888 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1889 // engine only supports touch events. We would need to add a mechanism similar
1890 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1891 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1892 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001893 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001894 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001895 const std::vector<sp<InputWindowHandle>> windowHandles =
1896 getWindowHandlesLocked(displayId);
1897 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001899 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001900 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001901 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001902 .addOrUpdateWindow(windowHandle,
1903 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1904 InputTarget::
1905 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1906 InputTarget::FLAG_DISPATCH_AS_IS,
1907 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 }
1909 }
1910 }
1911 }
1912
1913 // Success! Output targets.
1914 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1915
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001916 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001918 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919 }
1920
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001921 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001922 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001923 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001924 }
1925
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 // Drop the outside or hover touch windows since we will not care about them
1927 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001928 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929
1930Failed:
1931 // Check injection permission once and for all.
1932 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001933 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 injectionPermission = INJECTION_PERMISSION_GRANTED;
1935 } else {
1936 injectionPermission = INJECTION_PERMISSION_DENIED;
1937 }
1938 }
1939
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001940 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1941 return injectionResult;
1942 }
1943
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001945 if (!wrongDevice) {
1946 if (switchedDevice) {
1947 if (DEBUG_FOCUS) {
1948 ALOGD("Conflicting pointer actions: Switched to a different device.");
1949 }
1950 *outConflictingPointerActions = true;
1951 }
1952
1953 if (isHoverAction) {
1954 // Started hovering, therefore no longer down.
1955 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001956 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001957 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1958 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 *outConflictingPointerActions = true;
1961 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001962 tempTouchState.reset();
1963 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1964 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1965 tempTouchState.deviceId = entry.deviceId;
1966 tempTouchState.source = entry.source;
1967 tempTouchState.displayId = displayId;
1968 }
1969 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1970 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1971 // All pointers up or canceled.
1972 tempTouchState.reset();
1973 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1974 // First pointer went down.
1975 if (oldState && oldState->down) {
1976 if (DEBUG_FOCUS) {
1977 ALOGD("Conflicting pointer actions: Down received while already down.");
1978 }
1979 *outConflictingPointerActions = true;
1980 }
1981 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1982 // One pointer went up.
1983 if (isSplit) {
1984 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1985 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001987 for (size_t i = 0; i < tempTouchState.windows.size();) {
1988 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1989 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1990 touchedWindow.pointerIds.clearBit(pointerId);
1991 if (touchedWindow.pointerIds.isEmpty()) {
1992 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1993 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001996 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001998 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001999 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002000
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002001 // Save changes unless the action was scroll in which case the temporary touch
2002 // state was only valid for this one action.
2003 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2004 if (tempTouchState.displayId >= 0) {
2005 mTouchStatesByDisplay[displayId] = tempTouchState;
2006 } else {
2007 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002011 // Update hover state.
2012 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 }
2014
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 return injectionResult;
2016}
2017
2018void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002019 int32_t targetFlags, BitSet32 pointerIds,
2020 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002021 std::vector<InputTarget>::iterator it =
2022 std::find_if(inputTargets.begin(), inputTargets.end(),
2023 [&windowHandle](const InputTarget& inputTarget) {
2024 return inputTarget.inputChannel->getConnectionToken() ==
2025 windowHandle->getToken();
2026 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002027
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002028 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002029
2030 if (it == inputTargets.end()) {
2031 InputTarget inputTarget;
2032 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2033 if (inputChannel == nullptr) {
2034 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2035 return;
2036 }
2037 inputTarget.inputChannel = inputChannel;
2038 inputTarget.flags = targetFlags;
2039 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2040 inputTargets.push_back(inputTarget);
2041 it = inputTargets.end() - 1;
2042 }
2043
2044 ALOG_ASSERT(it->flags == targetFlags);
2045 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2046
2047 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
2048 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049}
2050
Michael Wright3dd60e22019-03-27 22:06:44 +00002051void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002052 int32_t displayId, float xOffset,
2053 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002054 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2055 mGlobalMonitorsByDisplay.find(displayId);
2056
2057 if (it != mGlobalMonitorsByDisplay.end()) {
2058 const std::vector<Monitor>& monitors = it->second;
2059 for (const Monitor& monitor : monitors) {
2060 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 }
2063}
2064
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002065void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2066 float yOffset,
2067 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002068 InputTarget target;
2069 target.inputChannel = monitor.inputChannel;
2070 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002071 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00002072 inputTargets.push_back(target);
2073}
2074
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002076 const InjectionState* injectionState) {
2077 if (injectionState &&
2078 (windowHandle == nullptr ||
2079 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2080 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002081 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002083 "owned by uid %d",
2084 injectionState->injectorPid, injectionState->injectorUid,
2085 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086 } else {
2087 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002088 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 }
2090 return false;
2091 }
2092 return true;
2093}
2094
Robert Carrc9bf1d32020-04-13 17:21:08 -07002095/**
2096 * Indicate whether one window handle should be considered as obscuring
2097 * another window handle. We only check a few preconditions. Actually
2098 * checking the bounds is left to the caller.
2099 */
2100static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2101 const sp<InputWindowHandle>& otherHandle) {
2102 // Compare by token so cloned layers aren't counted
2103 if (haveSameToken(windowHandle, otherHandle)) {
2104 return false;
2105 }
2106 auto info = windowHandle->getInfo();
2107 auto otherInfo = otherHandle->getInfo();
2108 if (!otherInfo->visible) {
2109 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002110 } else if (info->ownerPid == otherInfo->ownerPid) {
2111 // If ownerPid is the same we don't generate occlusion events as there
2112 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002113 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002114 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002115 return false;
2116 } else if (otherInfo->displayId != info->displayId) {
2117 return false;
2118 }
2119 return true;
2120}
2121
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002122bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2123 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002125 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2126 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002127 if (windowHandle == otherHandle) {
2128 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002131 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002132 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133 return true;
2134 }
2135 }
2136 return false;
2137}
2138
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002139bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2140 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002141 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002142 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002143 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002144 if (windowHandle == otherHandle) {
2145 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002146 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002147 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002148 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002149 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002150 return true;
2151 }
2152 }
2153 return false;
2154}
2155
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002156std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 const sp<InputApplicationHandle>& applicationHandle,
2158 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002159 if (applicationHandle != nullptr) {
2160 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002161 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 } else {
2163 return applicationHandle->getName();
2164 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002165 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002166 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002168 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 }
2170}
2171
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002172void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002173 if (eventEntry.type == EventEntry::Type::FOCUS) {
2174 // Focus events are passed to apps, but do not represent user activity.
2175 return;
2176 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002177 int32_t displayId = getTargetDisplayId(eventEntry);
2178 sp<InputWindowHandle> focusedWindowHandle =
2179 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2180 if (focusedWindowHandle != nullptr) {
2181 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002182 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002184 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185#endif
2186 return;
2187 }
2188 }
2189
2190 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002191 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002192 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002193 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2194 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002195 return;
2196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002198 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002199 eventType = USER_ACTIVITY_EVENT_TOUCH;
2200 }
2201 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002203 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002204 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2205 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002206 return;
2207 }
2208 eventType = USER_ACTIVITY_EVENT_BUTTON;
2209 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002211 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002212 case EventEntry::Type::CONFIGURATION_CHANGED:
2213 case EventEntry::Type::DEVICE_RESET: {
2214 LOG_ALWAYS_FATAL("%s events are not user activity",
2215 EventEntry::typeToString(eventEntry.type));
2216 break;
2217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218 }
2219
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002220 std::unique_ptr<CommandEntry> commandEntry =
2221 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002222 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002224 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225}
2226
2227void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002228 const sp<Connection>& connection,
2229 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002230 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002231 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002232 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002233 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002234 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002235 ATRACE_NAME(message.c_str());
2236 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237#if DEBUG_DISPATCH_CYCLE
2238 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002239 "globalScaleFactor=%f, pointerIds=0x%x %s",
2240 connection->getInputChannelName().c_str(), inputTarget.flags,
2241 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2242 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243#endif
2244
2245 // Skip this event if the connection status is not normal.
2246 // We don't want to enqueue additional outbound events if the connection is broken.
2247 if (connection->status != Connection::STATUS_NORMAL) {
2248#if DEBUG_DISPATCH_CYCLE
2249 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002250 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251#endif
2252 return;
2253 }
2254
2255 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002256 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2257 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2258 "Entry type %s should not have FLAG_SPLIT",
2259 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002261 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002262 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002263 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002264 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 if (!splitMotionEntry) {
2266 return; // split event was dropped
2267 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002268 if (DEBUG_FOCUS) {
2269 ALOGD("channel '%s' ~ Split motion event.",
2270 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002271 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002272 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002273 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 splitMotionEntry->release();
2275 return;
2276 }
2277 }
2278
2279 // Not splitting. Enqueue dispatch entries for the event as is.
2280 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2281}
2282
2283void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002284 const sp<Connection>& connection,
2285 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002286 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002287 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002288 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002289 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002290 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002291 ATRACE_NAME(message.c_str());
2292 }
2293
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002294 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295
2296 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002297 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002298 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002299 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002300 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002301 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002302 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002303 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002304 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002305 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002306 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002307 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002308 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309
2310 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002311 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 startDispatchCycleLocked(currentTime, connection);
2313 }
2314}
2315
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002316void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2317 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002318 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002319 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002320 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002321 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2322 connection->getInputChannelName().c_str(),
2323 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002324 ATRACE_NAME(message.c_str());
2325 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002326 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 if (!(inputTargetFlags & dispatchMode)) {
2328 return;
2329 }
2330 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2331
2332 // This is a new event.
2333 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002334 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002335 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002337 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2338 // different EventEntry than what was passed in.
2339 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002341 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002342 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002343 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002344 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002345 dispatchEntry->resolvedAction = keyEntry.action;
2346 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002348 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2349 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002351 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2352 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002354 return; // skip the inconsistent event
2355 }
2356 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002359 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002360 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002361 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2362 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2363 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2364 static_cast<int32_t>(IdGenerator::Source::OTHER);
2365 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002366 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2367 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2368 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2369 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2370 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2371 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2372 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2373 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2374 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2375 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2376 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002377 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002378 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002379 }
2380 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002381 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2382 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002384 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2385 "event",
2386 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002388 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002391 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002392 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2393 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2394 }
2395 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2396 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2397 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002399 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2400 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002402 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2403 "event",
2404 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002405#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002406 return; // skip the inconsistent event
2407 }
2408
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002409 dispatchEntry->resolvedEventId =
2410 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2411 ? mIdGenerator.nextId()
2412 : motionEntry.id;
2413 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2414 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2415 ") to MotionEvent(id=0x%" PRIx32 ").",
2416 motionEntry.id, dispatchEntry->resolvedEventId);
2417 ATRACE_NAME(message.c_str());
2418 }
2419
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002420 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002421 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002422
2423 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002425 case EventEntry::Type::FOCUS: {
2426 break;
2427 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002428 case EventEntry::Type::CONFIGURATION_CHANGED:
2429 case EventEntry::Type::DEVICE_RESET: {
2430 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002431 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002432 break;
2433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434 }
2435
2436 // Remember that we are waiting for this dispatch to complete.
2437 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002438 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439 }
2440
2441 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002442 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002443 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002444}
2445
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002446/**
2447 * This function is purely for debugging. It helps us understand where the user interaction
2448 * was taking place. For example, if user is touching launcher, we will see a log that user
2449 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2450 * We will see both launcher and wallpaper in that list.
2451 * Once the interaction with a particular set of connections starts, no new logs will be printed
2452 * until the set of interacted connections changes.
2453 *
2454 * The following items are skipped, to reduce the logspam:
2455 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2456 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2457 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2458 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2459 * Both of those ACTION_UP events would not be logged
2460 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2461 * will not be logged. This is omitted to reduce the amount of data printed.
2462 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2463 * gesture monitor is the only connection receiving the remainder of the gesture.
2464 */
2465void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2466 const std::vector<InputTarget>& targets) {
2467 // Skip ACTION_UP events, and all events other than keys and motions
2468 if (entry.type == EventEntry::Type::KEY) {
2469 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2470 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2471 return;
2472 }
2473 } else if (entry.type == EventEntry::Type::MOTION) {
2474 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2475 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2476 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2477 return;
2478 }
2479 } else {
2480 return; // Not a key or a motion
2481 }
2482
2483 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2484 std::vector<sp<Connection>> newConnections;
2485 for (const InputTarget& target : targets) {
2486 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2487 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2488 continue; // Skip windows that receive ACTION_OUTSIDE
2489 }
2490
2491 sp<IBinder> token = target.inputChannel->getConnectionToken();
2492 sp<Connection> connection = getConnectionLocked(token);
2493 if (connection == nullptr || connection->monitor) {
2494 continue; // We only need to keep track of the non-monitor connections.
2495 }
2496 newConnectionTokens.insert(std::move(token));
2497 newConnections.emplace_back(connection);
2498 }
2499 if (newConnectionTokens == mInteractionConnectionTokens) {
2500 return; // no change
2501 }
2502 mInteractionConnectionTokens = newConnectionTokens;
2503
2504 std::string windowList;
2505 for (const sp<Connection>& connection : newConnections) {
2506 windowList += connection->getWindowName() + ", ";
2507 }
2508 std::string message = "Interaction with windows: " + windowList;
2509 if (windowList.empty()) {
2510 message += "<none>";
2511 }
2512 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2513}
2514
chaviwfd6d3512019-03-25 13:23:49 -07002515void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002516 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002517 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002518 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2519 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002520 return;
2521 }
2522
2523 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2524 if (inputWindowHandle == nullptr) {
2525 return;
2526 }
2527
chaviw8c9cf542019-03-25 13:02:48 -07002528 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002529 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002530
2531 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2532
2533 if (!hasFocusChanged) {
2534 return;
2535 }
2536
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002537 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2538 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002539 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002540 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541}
2542
2543void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002544 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002545 if (ATRACE_ENABLED()) {
2546 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002547 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002548 ATRACE_NAME(message.c_str());
2549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002550#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002551 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552#endif
2553
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002554 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2555 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002557 const nsecs_t timeout =
2558 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
2559 dispatchEntry->timeoutTime = currentTime + timeout;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002560
2561 // Publish the event.
2562 status_t status;
2563 EventEntry* eventEntry = dispatchEntry->eventEntry;
2564 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002565 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002566 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2567 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002569 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002570 status =
2571 connection->inputPublisher
2572 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2573 keyEntry->deviceId, keyEntry->source,
2574 keyEntry->displayId, std::move(hmac),
2575 dispatchEntry->resolvedAction,
2576 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2577 keyEntry->scanCode, keyEntry->metaState,
2578 keyEntry->repeatCount, keyEntry->downTime,
2579 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002580 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 }
2582
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002583 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002584 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002586 PointerCoords scaledCoords[MAX_POINTERS];
2587 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2588
chaviw82357092020-01-28 13:13:06 -08002589 // Set the X and Y offset and X and Y scale depending on the input source.
2590 float xOffset = 0.0f, yOffset = 0.0f;
2591 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002592 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2593 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2594 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002595 xScale = dispatchEntry->windowXScale;
2596 yScale = dispatchEntry->windowYScale;
2597 xOffset = dispatchEntry->xOffset * xScale;
2598 yOffset = dispatchEntry->yOffset * yScale;
2599 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002600 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2601 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002602 // Don't apply window scale here since we don't want scale to affect raw
2603 // coordinates. The scale will be sent back to the client and applied
2604 // later when requesting relative coordinates.
2605 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2606 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002607 }
2608 usingCoords = scaledCoords;
2609 }
2610 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002611 // We don't want the dispatch target to know.
2612 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2613 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2614 scaledCoords[i].clear();
2615 }
2616 usingCoords = scaledCoords;
2617 }
2618 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002619
2620 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002621
2622 // Publish the motion event.
2623 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002624 .publishMotionEvent(dispatchEntry->seq,
2625 dispatchEntry->resolvedEventId,
2626 motionEntry->deviceId, motionEntry->source,
2627 motionEntry->displayId, std::move(hmac),
2628 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002629 motionEntry->actionButton,
2630 dispatchEntry->resolvedFlags,
2631 motionEntry->edgeFlags, motionEntry->metaState,
2632 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002633 motionEntry->classification, xScale, yScale,
2634 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002635 motionEntry->yPrecision,
2636 motionEntry->xCursorPosition,
2637 motionEntry->yCursorPosition,
2638 motionEntry->downTime, motionEntry->eventTime,
2639 motionEntry->pointerCount,
2640 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002641 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002642 break;
2643 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002644 case EventEntry::Type::FOCUS: {
2645 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2646 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002647 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002648 focusEntry->hasFocus,
2649 mInTouchMode);
2650 break;
2651 }
2652
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002653 case EventEntry::Type::CONFIGURATION_CHANGED:
2654 case EventEntry::Type::DEVICE_RESET: {
2655 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2656 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002657 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 }
2660
2661 // Check the result.
2662 if (status) {
2663 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002664 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002666 "This is unexpected because the wait queue is empty, so the pipe "
2667 "should be empty and we shouldn't have any problems writing an "
2668 "event to it, status=%d",
2669 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2671 } else {
2672 // Pipe is full and we are waiting for the app to finish process some events
2673 // before sending more events to it.
2674#if DEBUG_DISPATCH_CYCLE
2675 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002676 "waiting for the application to catch up",
2677 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679 }
2680 } else {
2681 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002682 "status=%d",
2683 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2685 }
2686 return;
2687 }
2688
2689 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002690 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2691 connection->outboundQueue.end(),
2692 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002693 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002694 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002695 if (connection->responsive) {
2696 mAnrTracker.insert(dispatchEntry->timeoutTime,
2697 connection->inputChannel->getConnectionToken());
2698 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002699 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 }
2701}
2702
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002703const std::array<uint8_t, 32> InputDispatcher::getSignature(
2704 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2705 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2706 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2707 // Only sign events up and down events as the purely move events
2708 // are tied to their up/down counterparts so signing would be redundant.
2709 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2710 verifiedEvent.actionMasked = actionMasked;
2711 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2712 return mHmacKeyManager.sign(verifiedEvent);
2713 }
2714 return INVALID_HMAC;
2715}
2716
2717const std::array<uint8_t, 32> InputDispatcher::getSignature(
2718 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2719 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2720 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2721 verifiedEvent.action = dispatchEntry.resolvedAction;
2722 return mHmacKeyManager.sign(verifiedEvent);
2723}
2724
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002726 const sp<Connection>& connection, uint32_t seq,
2727 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728#if DEBUG_DISPATCH_CYCLE
2729 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002730 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002731#endif
2732
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002733 if (connection->status == Connection::STATUS_BROKEN ||
2734 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735 return;
2736 }
2737
2738 // Notify other system components and prepare to start the next dispatch cycle.
2739 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2740}
2741
2742void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002743 const sp<Connection>& connection,
2744 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745#if DEBUG_DISPATCH_CYCLE
2746 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002747 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748#endif
2749
2750 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002751 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002752 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002753 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002754 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755
2756 // The connection appears to be unrecoverably broken.
2757 // Ignore already broken or zombie connections.
2758 if (connection->status == Connection::STATUS_NORMAL) {
2759 connection->status = Connection::STATUS_BROKEN;
2760
2761 if (notify) {
2762 // Notify other system components.
2763 onDispatchCycleBrokenLocked(currentTime, connection);
2764 }
2765 }
2766}
2767
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002768void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2769 while (!queue.empty()) {
2770 DispatchEntry* dispatchEntry = queue.front();
2771 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002772 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773 }
2774}
2775
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002776void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002778 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779 }
2780 delete dispatchEntry;
2781}
2782
2783int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2784 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2785
2786 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002787 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002789 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002791 "fd=%d, events=0x%x",
2792 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 return 0; // remove the callback
2794 }
2795
2796 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002797 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002798 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2799 if (!(events & ALOOPER_EVENT_INPUT)) {
2800 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002801 "events=0x%x",
2802 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803 return 1;
2804 }
2805
2806 nsecs_t currentTime = now();
2807 bool gotOne = false;
2808 status_t status;
2809 for (;;) {
2810 uint32_t seq;
2811 bool handled;
2812 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2813 if (status) {
2814 break;
2815 }
2816 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2817 gotOne = true;
2818 }
2819 if (gotOne) {
2820 d->runCommandsLockedInterruptible();
2821 if (status == WOULD_BLOCK) {
2822 return 1;
2823 }
2824 }
2825
2826 notify = status != DEAD_OBJECT || !connection->monitor;
2827 if (notify) {
2828 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002829 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 }
2831 } else {
2832 // Monitor channels are never explicitly unregistered.
2833 // We do it automatically when the remote endpoint is closed so don't warn
2834 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002835 const bool stillHaveWindowHandle =
2836 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2837 nullptr;
2838 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839 if (notify) {
2840 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002841 "events=0x%x",
2842 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 }
2844 }
2845
2846 // Unregister the channel.
2847 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2848 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002849 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850}
2851
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002852void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002854 for (const auto& pair : mConnectionsByFd) {
2855 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856 }
2857}
2858
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002859void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002860 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002861 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2862 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2863}
2864
2865void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2866 const CancelationOptions& options,
2867 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2868 for (const auto& it : monitorsByDisplay) {
2869 const std::vector<Monitor>& monitors = it.second;
2870 for (const Monitor& monitor : monitors) {
2871 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002872 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002873 }
2874}
2875
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2877 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002878 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002879 if (connection == nullptr) {
2880 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002882
2883 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884}
2885
2886void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2887 const sp<Connection>& connection, const CancelationOptions& options) {
2888 if (connection->status == Connection::STATUS_BROKEN) {
2889 return;
2890 }
2891
2892 nsecs_t currentTime = now();
2893
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002894 std::vector<EventEntry*> cancelationEvents =
2895 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002896
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002897 if (cancelationEvents.empty()) {
2898 return;
2899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002901 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2902 "with reality: %s, mode=%d.",
2903 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2904 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002906
2907 InputTarget target;
2908 sp<InputWindowHandle> windowHandle =
2909 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2910 if (windowHandle != nullptr) {
2911 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2912 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2913 windowInfo->windowXScale, windowInfo->windowYScale);
2914 target.globalScaleFactor = windowInfo->globalScaleFactor;
2915 }
2916 target.inputChannel = connection->inputChannel;
2917 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2918
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002919 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2920 EventEntry* cancelationEventEntry = cancelationEvents[i];
2921 switch (cancelationEventEntry->type) {
2922 case EventEntry::Type::KEY: {
2923 logOutboundKeyDetails("cancel - ",
2924 static_cast<const KeyEntry&>(*cancelationEventEntry));
2925 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002927 case EventEntry::Type::MOTION: {
2928 logOutboundMotionDetails("cancel - ",
2929 static_cast<const MotionEntry&>(*cancelationEventEntry));
2930 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002932 case EventEntry::Type::FOCUS: {
2933 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2934 break;
2935 }
2936 case EventEntry::Type::CONFIGURATION_CHANGED:
2937 case EventEntry::Type::DEVICE_RESET: {
2938 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2939 EventEntry::typeToString(cancelationEventEntry->type));
2940 break;
2941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942 }
2943
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002944 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2945 target, InputTarget::FLAG_DISPATCH_AS_IS);
2946
2947 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002949
2950 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951}
2952
Svet Ganov5d3bc372020-01-26 23:11:07 -08002953void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2954 const sp<Connection>& connection) {
2955 if (connection->status == Connection::STATUS_BROKEN) {
2956 return;
2957 }
2958
2959 nsecs_t currentTime = now();
2960
2961 std::vector<EventEntry*> downEvents =
2962 connection->inputState.synthesizePointerDownEvents(currentTime);
2963
2964 if (downEvents.empty()) {
2965 return;
2966 }
2967
2968#if DEBUG_OUTBOUND_EVENT_DETAILS
2969 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2970 connection->getInputChannelName().c_str(), downEvents.size());
2971#endif
2972
2973 InputTarget target;
2974 sp<InputWindowHandle> windowHandle =
2975 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2976 if (windowHandle != nullptr) {
2977 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2978 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2979 windowInfo->windowXScale, windowInfo->windowYScale);
2980 target.globalScaleFactor = windowInfo->globalScaleFactor;
2981 }
2982 target.inputChannel = connection->inputChannel;
2983 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2984
2985 for (EventEntry* downEventEntry : downEvents) {
2986 switch (downEventEntry->type) {
2987 case EventEntry::Type::MOTION: {
2988 logOutboundMotionDetails("down - ",
2989 static_cast<const MotionEntry&>(*downEventEntry));
2990 break;
2991 }
2992
2993 case EventEntry::Type::KEY:
2994 case EventEntry::Type::FOCUS:
2995 case EventEntry::Type::CONFIGURATION_CHANGED:
2996 case EventEntry::Type::DEVICE_RESET: {
2997 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2998 EventEntry::typeToString(downEventEntry->type));
2999 break;
3000 }
3001 }
3002
3003 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
3004 target, InputTarget::FLAG_DISPATCH_AS_IS);
3005
3006 downEventEntry->release();
3007 }
3008
3009 startDispatchCycleLocked(currentTime, connection);
3010}
3011
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003012MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07003013 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014 ALOG_ASSERT(pointerIds.value != 0);
3015
3016 uint32_t splitPointerIndexMap[MAX_POINTERS];
3017 PointerProperties splitPointerProperties[MAX_POINTERS];
3018 PointerCoords splitPointerCoords[MAX_POINTERS];
3019
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003020 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021 uint32_t splitPointerCount = 0;
3022
3023 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003026 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003027 uint32_t pointerId = uint32_t(pointerProperties.id);
3028 if (pointerIds.hasBit(pointerId)) {
3029 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3030 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3031 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003032 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033 splitPointerCount += 1;
3034 }
3035 }
3036
3037 if (splitPointerCount != pointerIds.count()) {
3038 // This is bad. We are missing some of the pointers that we expected to deliver.
3039 // Most likely this indicates that we received an ACTION_MOVE events that has
3040 // different pointer ids than we expected based on the previous ACTION_DOWN
3041 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3042 // in this way.
3043 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003044 "we expected there to be %d pointers. This probably means we received "
3045 "a broken sequence of pointer ids from the input device.",
3046 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003047 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048 }
3049
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003050 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003052 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3053 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3055 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003056 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057 uint32_t pointerId = uint32_t(pointerProperties.id);
3058 if (pointerIds.hasBit(pointerId)) {
3059 if (pointerIds.count() == 1) {
3060 // The first/last pointer went down/up.
3061 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003062 ? AMOTION_EVENT_ACTION_DOWN
3063 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064 } else {
3065 // A secondary pointer went down/up.
3066 uint32_t splitPointerIndex = 0;
3067 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3068 splitPointerIndex += 1;
3069 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003070 action = maskedAction |
3071 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003072 }
3073 } else {
3074 // An unrelated pointer changed.
3075 action = AMOTION_EVENT_ACTION_MOVE;
3076 }
3077 }
3078
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003079 int32_t newId = mIdGenerator.nextId();
3080 if (ATRACE_ENABLED()) {
3081 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3082 ") to MotionEvent(id=0x%" PRIx32 ").",
3083 originalMotionEntry.id, newId);
3084 ATRACE_NAME(message.c_str());
3085 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003086 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003087 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3088 originalMotionEntry.source, originalMotionEntry.displayId,
3089 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003090 originalMotionEntry.actionButton, originalMotionEntry.flags,
3091 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3092 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3093 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3094 originalMotionEntry.xCursorPosition,
3095 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003096 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003098 if (originalMotionEntry.injectionState) {
3099 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 splitMotionEntry->injectionState->refCount += 1;
3101 }
3102
3103 return splitMotionEntry;
3104}
3105
3106void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3107#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003108 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109#endif
3110
3111 bool needWake;
3112 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003113 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114
Prabir Pradhan42611e02018-11-27 14:04:02 -08003115 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003116 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 needWake = enqueueInboundEventLocked(newEntry);
3118 } // release lock
3119
3120 if (needWake) {
3121 mLooper->wake();
3122 }
3123}
3124
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003125/**
3126 * If one of the meta shortcuts is detected, process them here:
3127 * Meta + Backspace -> generate BACK
3128 * Meta + Enter -> generate HOME
3129 * This will potentially overwrite keyCode and metaState.
3130 */
3131void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003132 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003133 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3134 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3135 if (keyCode == AKEYCODE_DEL) {
3136 newKeyCode = AKEYCODE_BACK;
3137 } else if (keyCode == AKEYCODE_ENTER) {
3138 newKeyCode = AKEYCODE_HOME;
3139 }
3140 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003141 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003142 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003143 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003144 keyCode = newKeyCode;
3145 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3146 }
3147 } else if (action == AKEY_EVENT_ACTION_UP) {
3148 // In order to maintain a consistent stream of up and down events, check to see if the key
3149 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3150 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003151 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003152 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003153 auto replacementIt = mReplacedKeys.find(replacement);
3154 if (replacementIt != mReplacedKeys.end()) {
3155 keyCode = replacementIt->second;
3156 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003157 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3158 }
3159 }
3160}
3161
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3163#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003164 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3165 "policyFlags=0x%x, action=0x%x, "
3166 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3167 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3168 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3169 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170#endif
3171 if (!validateKeyEvent(args->action)) {
3172 return;
3173 }
3174
3175 uint32_t policyFlags = args->policyFlags;
3176 int32_t flags = args->flags;
3177 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003178 // InputDispatcher tracks and generates key repeats on behalf of
3179 // whatever notifies it, so repeatCount should always be set to 0
3180 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3182 policyFlags |= POLICY_FLAG_VIRTUAL;
3183 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 if (policyFlags & POLICY_FLAG_FUNCTION) {
3186 metaState |= AMETA_FUNCTION_ON;
3187 }
3188
3189 policyFlags |= POLICY_FLAG_TRUSTED;
3190
Michael Wright78f24442014-08-06 15:55:28 -07003191 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003192 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003193
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003195 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003196 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3197 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198
Michael Wright2b3c3302018-03-02 17:19:13 +00003199 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003201 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3202 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 bool needWake;
3207 { // acquire lock
3208 mLock.lock();
3209
3210 if (shouldSendKeyToInputFilterLocked(args)) {
3211 mLock.unlock();
3212
3213 policyFlags |= POLICY_FLAG_FILTERED;
3214 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3215 return; // event was consumed by the filter
3216 }
3217
3218 mLock.lock();
3219 }
3220
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003221 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003222 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003223 args->displayId, policyFlags, args->action, flags, keyCode,
3224 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225
3226 needWake = enqueueInboundEventLocked(newEntry);
3227 mLock.unlock();
3228 } // release lock
3229
3230 if (needWake) {
3231 mLooper->wake();
3232 }
3233}
3234
3235bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3236 return mInputFilterEnabled;
3237}
3238
3239void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3240#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003241 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3242 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003243 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3244 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003245 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003246 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3247 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3248 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3249 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 for (uint32_t i = 0; i < args->pointerCount; i++) {
3251 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003252 "x=%f, y=%f, pressure=%f, size=%f, "
3253 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3254 "orientation=%f",
3255 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3256 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3257 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3258 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3259 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3260 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3261 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3262 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3263 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3264 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265 }
3266#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003267 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3268 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269 return;
3270 }
3271
3272 uint32_t policyFlags = args->policyFlags;
3273 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003274
3275 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003276 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003277 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3278 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003279 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003280 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281
3282 bool needWake;
3283 { // acquire lock
3284 mLock.lock();
3285
3286 if (shouldSendMotionToInputFilterLocked(args)) {
3287 mLock.unlock();
3288
3289 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003290 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3291 args->action, args->actionButton, args->flags, args->edgeFlags,
3292 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3293 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3294 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3295 args->downTime, args->eventTime, args->pointerCount,
3296 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297
3298 policyFlags |= POLICY_FLAG_FILTERED;
3299 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3300 return; // event was consumed by the filter
3301 }
3302
3303 mLock.lock();
3304 }
3305
3306 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003307 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003308 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003309 args->displayId, policyFlags, args->action, args->actionButton,
3310 args->flags, args->metaState, args->buttonState,
3311 args->classification, args->edgeFlags, args->xPrecision,
3312 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3313 args->downTime, args->pointerCount, args->pointerProperties,
3314 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315
3316 needWake = enqueueInboundEventLocked(newEntry);
3317 mLock.unlock();
3318 } // release lock
3319
3320 if (needWake) {
3321 mLooper->wake();
3322 }
3323}
3324
3325bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003326 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327}
3328
3329void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3330#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003331 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003332 "switchMask=0x%08x",
3333 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334#endif
3335
3336 uint32_t policyFlags = args->policyFlags;
3337 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339}
3340
3341void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3342#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003343 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3344 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345#endif
3346
3347 bool needWake;
3348 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003349 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350
Prabir Pradhan42611e02018-11-27 14:04:02 -08003351 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003352 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353 needWake = enqueueInboundEventLocked(newEntry);
3354 } // release lock
3355
3356 if (needWake) {
3357 mLooper->wake();
3358 }
3359}
3360
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003361int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3362 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003363 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364#if DEBUG_INBOUND_EVENT_DETAILS
3365 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003366 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3367 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368#endif
3369
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003370 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371
3372 policyFlags |= POLICY_FLAG_INJECTED;
3373 if (hasInjectionPermission(injectorPid, injectorUid)) {
3374 policyFlags |= POLICY_FLAG_TRUSTED;
3375 }
3376
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003377 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003380 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3381 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003382 if (!validateKeyEvent(action)) {
3383 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003384 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003386 int32_t flags = incomingKey.getFlags();
3387 int32_t keyCode = incomingKey.getKeyCode();
3388 int32_t metaState = incomingKey.getMetaState();
3389 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003390 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003391 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003392 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003393 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3394 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3395 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003397 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3398 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003399 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003400
3401 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3402 android::base::Timer t;
3403 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3404 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3405 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3406 std::to_string(t.duration().count()).c_str());
3407 }
3408 }
3409
3410 mLock.lock();
3411 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003412 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3413 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003414 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3415 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003416 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003417 injectedEntries.push(injectedEntry);
3418 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 }
3420
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003421 case AINPUT_EVENT_TYPE_MOTION: {
3422 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3423 int32_t action = motionEvent->getAction();
3424 size_t pointerCount = motionEvent->getPointerCount();
3425 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3426 int32_t actionButton = motionEvent->getActionButton();
3427 int32_t displayId = motionEvent->getDisplayId();
3428 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3429 return INPUT_EVENT_INJECTION_FAILED;
3430 }
3431
3432 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3433 nsecs_t eventTime = motionEvent->getEventTime();
3434 android::base::Timer t;
3435 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3436 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3437 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3438 std::to_string(t.duration().count()).c_str());
3439 }
3440 }
3441
3442 mLock.lock();
3443 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3444 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3445 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003446 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3447 motionEvent->getSource(), motionEvent->getDisplayId(),
3448 policyFlags, action, actionButton, motionEvent->getFlags(),
3449 motionEvent->getMetaState(), motionEvent->getButtonState(),
3450 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3451 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003452 motionEvent->getRawXCursorPosition(),
3453 motionEvent->getRawYCursorPosition(),
3454 motionEvent->getDownTime(), uint32_t(pointerCount),
3455 pointerProperties, samplePointerCoords,
3456 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003457 injectedEntries.push(injectedEntry);
3458 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3459 sampleEventTimes += 1;
3460 samplePointerCoords += pointerCount;
3461 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003462 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003463 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003464 motionEvent->getDisplayId(), policyFlags, action,
3465 actionButton, motionEvent->getFlags(),
3466 motionEvent->getMetaState(), motionEvent->getButtonState(),
3467 motionEvent->getClassification(),
3468 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3469 motionEvent->getYPrecision(),
3470 motionEvent->getRawXCursorPosition(),
3471 motionEvent->getRawYCursorPosition(),
3472 motionEvent->getDownTime(), uint32_t(pointerCount),
3473 pointerProperties, samplePointerCoords,
3474 motionEvent->getXOffset(), motionEvent->getYOffset());
3475 injectedEntries.push(nextInjectedEntry);
3476 }
3477 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003480 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003481 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003482 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 }
3484
3485 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3486 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3487 injectionState->injectionIsAsync = true;
3488 }
3489
3490 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003491 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492
3493 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003494 while (!injectedEntries.empty()) {
3495 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3496 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497 }
3498
3499 mLock.unlock();
3500
3501 if (needWake) {
3502 mLooper->wake();
3503 }
3504
3505 int32_t injectionResult;
3506 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003507 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508
3509 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3510 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3511 } else {
3512 for (;;) {
3513 injectionResult = injectionState->injectionResult;
3514 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3515 break;
3516 }
3517
3518 nsecs_t remainingTimeout = endTime - now();
3519 if (remainingTimeout <= 0) {
3520#if DEBUG_INJECTION
3521 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003522 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523#endif
3524 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3525 break;
3526 }
3527
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003528 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 }
3530
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003531 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3532 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 while (injectionState->pendingForegroundDispatches != 0) {
3534#if DEBUG_INJECTION
3535 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003536 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537#endif
3538 nsecs_t remainingTimeout = endTime - now();
3539 if (remainingTimeout <= 0) {
3540#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003541 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3542 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543#endif
3544 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3545 break;
3546 }
3547
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003548 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549 }
3550 }
3551 }
3552
3553 injectionState->release();
3554 } // release lock
3555
3556#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003557 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003558 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559#endif
3560
3561 return injectionResult;
3562}
3563
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003564std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003565 std::array<uint8_t, 32> calculatedHmac;
3566 std::unique_ptr<VerifiedInputEvent> result;
3567 switch (event.getType()) {
3568 case AINPUT_EVENT_TYPE_KEY: {
3569 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3570 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3571 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3572 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3573 break;
3574 }
3575 case AINPUT_EVENT_TYPE_MOTION: {
3576 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3577 VerifiedMotionEvent verifiedMotionEvent =
3578 verifiedMotionEventFromMotionEvent(motionEvent);
3579 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3580 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3581 break;
3582 }
3583 default: {
3584 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3585 return nullptr;
3586 }
3587 }
3588 if (calculatedHmac == INVALID_HMAC) {
3589 return nullptr;
3590 }
3591 if (calculatedHmac != event.getHmac()) {
3592 return nullptr;
3593 }
3594 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003595}
3596
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003598 return injectorUid == 0 ||
3599 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600}
3601
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003602void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 InjectionState* injectionState = entry->injectionState;
3604 if (injectionState) {
3605#if DEBUG_INJECTION
3606 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003607 "injectorPid=%d, injectorUid=%d",
3608 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609#endif
3610
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003611 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 // Log the outcome since the injector did not wait for the injection result.
3613 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003614 case INPUT_EVENT_INJECTION_SUCCEEDED:
3615 ALOGV("Asynchronous input event injection succeeded.");
3616 break;
3617 case INPUT_EVENT_INJECTION_FAILED:
3618 ALOGW("Asynchronous input event injection failed.");
3619 break;
3620 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3621 ALOGW("Asynchronous input event injection permission denied.");
3622 break;
3623 case INPUT_EVENT_INJECTION_TIMED_OUT:
3624 ALOGW("Asynchronous input event injection timed out.");
3625 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 }
3627 }
3628
3629 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003630 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 }
3632}
3633
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003634void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 InjectionState* injectionState = entry->injectionState;
3636 if (injectionState) {
3637 injectionState->pendingForegroundDispatches += 1;
3638 }
3639}
3640
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003641void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 InjectionState* injectionState = entry->injectionState;
3643 if (injectionState) {
3644 injectionState->pendingForegroundDispatches -= 1;
3645
3646 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003647 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 }
3649 }
3650}
3651
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003652std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3653 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003654 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003655}
3656
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003658 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003659 if (windowHandleToken == nullptr) {
3660 return nullptr;
3661 }
3662
Arthur Hungb92218b2018-08-14 12:00:21 +08003663 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003664 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3665 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003666 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003667 return windowHandle;
3668 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 }
3670 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003671 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672}
3673
Mady Mellor017bcd12020-06-23 19:12:00 +00003674bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3675 for (auto& it : mWindowHandlesByDisplay) {
3676 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3677 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003678 if (handle->getId() == windowHandle->getId() &&
3679 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003680 if (windowHandle->getInfo()->displayId != it.first) {
3681 ALOGE("Found window %s in display %" PRId32
3682 ", but it should belong to display %" PRId32,
3683 windowHandle->getName().c_str(), it.first,
3684 windowHandle->getInfo()->displayId);
3685 }
3686 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003687 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688 }
3689 }
3690 return false;
3691}
3692
Robert Carr5c8a0262018-10-03 16:30:44 -07003693sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3694 size_t count = mInputChannelsByToken.count(token);
3695 if (count == 0) {
3696 return nullptr;
3697 }
3698 return mInputChannelsByToken.at(token);
3699}
3700
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003701void InputDispatcher::updateWindowHandlesForDisplayLocked(
3702 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3703 if (inputWindowHandles.empty()) {
3704 // Remove all handles on a display if there are no windows left.
3705 mWindowHandlesByDisplay.erase(displayId);
3706 return;
3707 }
3708
3709 // Since we compare the pointer of input window handles across window updates, we need
3710 // to make sure the handle object for the same window stays unchanged across updates.
3711 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003712 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003713 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003714 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003715 }
3716
3717 std::vector<sp<InputWindowHandle>> newHandles;
3718 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3719 if (!handle->updateInfo()) {
3720 // handle no longer valid
3721 continue;
3722 }
3723
3724 const InputWindowInfo* info = handle->getInfo();
3725 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3726 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3727 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003728 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3729 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3730 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003731 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003732 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003733 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003734 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003735 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003736 }
3737
3738 if (info->displayId != displayId) {
3739 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3740 handle->getName().c_str(), displayId, info->displayId);
3741 continue;
3742 }
3743
Robert Carredd13602020-04-13 17:24:34 -07003744 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3745 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003746 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003747 oldHandle->updateFrom(handle);
3748 newHandles.push_back(oldHandle);
3749 } else {
3750 newHandles.push_back(handle);
3751 }
3752 }
3753
3754 // Insert or replace
3755 mWindowHandlesByDisplay[displayId] = newHandles;
3756}
3757
Arthur Hung72d8dc32020-03-28 00:48:39 +00003758void InputDispatcher::setInputWindows(
3759 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3760 { // acquire lock
3761 std::scoped_lock _l(mLock);
3762 for (auto const& i : handlesPerDisplay) {
3763 setInputWindowsLocked(i.second, i.first);
3764 }
3765 }
3766 // Wake up poll loop since it may need to make new input dispatching choices.
3767 mLooper->wake();
3768}
3769
Arthur Hungb92218b2018-08-14 12:00:21 +08003770/**
3771 * Called from InputManagerService, update window handle list by displayId that can receive input.
3772 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3773 * If set an empty list, remove all handles from the specific display.
3774 * For focused handle, check if need to change and send a cancel event to previous one.
3775 * For removed handle, check if need to send a cancel event if already in touch.
3776 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003777void InputDispatcher::setInputWindowsLocked(
3778 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003779 if (DEBUG_FOCUS) {
3780 std::string windowList;
3781 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3782 windowList += iwh->getName() + " ";
3783 }
3784 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3785 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786
Arthur Hung72d8dc32020-03-28 00:48:39 +00003787 // Copy old handles for release if they are no longer present.
3788 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789
Arthur Hung72d8dc32020-03-28 00:48:39 +00003790 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003791
Arthur Hung72d8dc32020-03-28 00:48:39 +00003792 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3793 bool foundHoveredWindow = false;
3794 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3795 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3796 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3797 windowHandle->getInfo()->visible) {
3798 newFocusedWindowHandle = windowHandle;
3799 }
3800 if (windowHandle == mLastHoverWindowHandle) {
3801 foundHoveredWindow = true;
3802 }
3803 }
3804
3805 if (!foundHoveredWindow) {
3806 mLastHoverWindowHandle = nullptr;
3807 }
3808
3809 sp<InputWindowHandle> oldFocusedWindowHandle =
3810 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3811
3812 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3813 if (oldFocusedWindowHandle != nullptr) {
3814 if (DEBUG_FOCUS) {
3815 ALOGD("Focus left window: %s in display %" PRId32,
3816 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003817 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003818 sp<InputChannel> focusedInputChannel =
3819 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3820 if (focusedInputChannel != nullptr) {
3821 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3822 "focus left window");
3823 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3824 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003825 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003826 mFocusedWindowHandlesByDisplay.erase(displayId);
3827 }
3828 if (newFocusedWindowHandle != nullptr) {
3829 if (DEBUG_FOCUS) {
3830 ALOGD("Focus entered window: %s in display %" PRId32,
3831 newFocusedWindowHandle->getName().c_str(), displayId);
3832 }
3833 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3834 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 }
3836
Arthur Hung72d8dc32020-03-28 00:48:39 +00003837 if (mFocusedDisplayId == displayId) {
3838 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003840 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003842 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3843 mTouchStatesByDisplay.find(displayId);
3844 if (stateIt != mTouchStatesByDisplay.end()) {
3845 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003846 for (size_t i = 0; i < state.windows.size();) {
3847 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003848 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003849 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003850 ALOGD("Touched window was removed: %s in display %" PRId32,
3851 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003852 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003853 sp<InputChannel> touchedInputChannel =
3854 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3855 if (touchedInputChannel != nullptr) {
3856 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3857 "touched window was removed");
3858 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003860 state.windows.erase(state.windows.begin() + i);
3861 } else {
3862 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 }
3864 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003865 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003866
Arthur Hung72d8dc32020-03-28 00:48:39 +00003867 // Release information for windows that are no longer present.
3868 // This ensures that unused input channels are released promptly.
3869 // Otherwise, they might stick around until the window handle is destroyed
3870 // which might not happen until the next GC.
3871 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003872 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003873 if (DEBUG_FOCUS) {
3874 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003875 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003876 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003877 }
chaviw291d88a2019-02-14 10:33:58 -08003878 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879}
3880
3881void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003882 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003883 if (DEBUG_FOCUS) {
3884 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3885 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3886 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003888 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889
Tiger Huang721e26f2018-07-24 22:26:19 +08003890 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3891 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003892
3893 if (oldFocusedApplicationHandle == mAwaitedFocusedApplication &&
3894 inputApplicationHandle != oldFocusedApplicationHandle) {
3895 resetNoFocusedWindowTimeoutLocked();
3896 }
3897
Yi Kong9b14ac62018-07-17 13:48:38 -07003898 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003899 if (oldFocusedApplicationHandle != inputApplicationHandle) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003900 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003902 } else if (oldFocusedApplicationHandle != nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003903 oldFocusedApplicationHandle.clear();
3904 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906 } // release lock
3907
3908 // Wake up poll loop since it may need to make new input dispatching choices.
3909 mLooper->wake();
3910}
3911
Tiger Huang721e26f2018-07-24 22:26:19 +08003912/**
3913 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3914 * the display not specified.
3915 *
3916 * We track any unreleased events for each window. If a window loses the ability to receive the
3917 * released event, we will send a cancel event to it. So when the focused display is changed, we
3918 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3919 * display. The display-specified events won't be affected.
3920 */
3921void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003922 if (DEBUG_FOCUS) {
3923 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3924 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003925 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003926 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003927
3928 if (mFocusedDisplayId != displayId) {
3929 sp<InputWindowHandle> oldFocusedWindowHandle =
3930 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3931 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003932 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003933 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003934 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003935 CancelationOptions
3936 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3937 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003938 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003939 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3940 }
3941 }
3942 mFocusedDisplayId = displayId;
3943
3944 // Sanity check
3945 sp<InputWindowHandle> newFocusedWindowHandle =
3946 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003947 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003948
Tiger Huang721e26f2018-07-24 22:26:19 +08003949 if (newFocusedWindowHandle == nullptr) {
3950 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3951 if (!mFocusedWindowHandlesByDisplay.empty()) {
3952 ALOGE("But another display has a focused window:");
3953 for (auto& it : mFocusedWindowHandlesByDisplay) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003954 const sp<InputWindowHandle>& windowHandle = it.second;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05003955 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", it.first,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003956 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003957 }
3958 }
3959 }
3960 }
3961
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003962 if (DEBUG_FOCUS) {
3963 logDispatchStateLocked();
3964 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003965 } // release lock
3966
3967 // Wake up poll loop since it may need to make new input dispatching choices.
3968 mLooper->wake();
3969}
3970
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003972 if (DEBUG_FOCUS) {
3973 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975
3976 bool changed;
3977 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003978 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979
3980 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3981 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003982 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 }
3984
3985 if (mDispatchEnabled && !enabled) {
3986 resetAndDropEverythingLocked("dispatcher is being disabled");
3987 }
3988
3989 mDispatchEnabled = enabled;
3990 mDispatchFrozen = frozen;
3991 changed = true;
3992 } else {
3993 changed = false;
3994 }
3995
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003996 if (DEBUG_FOCUS) {
3997 logDispatchStateLocked();
3998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999 } // release lock
4000
4001 if (changed) {
4002 // Wake up poll loop since it may need to make new input dispatching choices.
4003 mLooper->wake();
4004 }
4005}
4006
4007void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004008 if (DEBUG_FOCUS) {
4009 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011
4012 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004013 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014
4015 if (mInputFilterEnabled == enabled) {
4016 return;
4017 }
4018
4019 mInputFilterEnabled = enabled;
4020 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4021 } // release lock
4022
4023 // Wake up poll loop since there might be work to do to drop everything.
4024 mLooper->wake();
4025}
4026
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004027void InputDispatcher::setInTouchMode(bool inTouchMode) {
4028 std::scoped_lock lock(mLock);
4029 mInTouchMode = inTouchMode;
4030}
4031
chaviwfbe5d9c2018-12-26 12:23:37 -08004032bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4033 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004034 if (DEBUG_FOCUS) {
4035 ALOGD("Trivial transfer to same window.");
4036 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004037 return true;
4038 }
4039
Michael Wrightd02c5b62014-02-10 15:10:22 -08004040 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004041 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042
chaviwfbe5d9c2018-12-26 12:23:37 -08004043 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4044 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004045 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004046 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047 return false;
4048 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004049 if (DEBUG_FOCUS) {
4050 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4051 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004054 if (DEBUG_FOCUS) {
4055 ALOGD("Cannot transfer focus because windows are on different displays.");
4056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057 return false;
4058 }
4059
4060 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004061 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4062 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004063 for (size_t i = 0; i < state.windows.size(); i++) {
4064 const TouchedWindow& touchedWindow = state.windows[i];
4065 if (touchedWindow.windowHandle == fromWindowHandle) {
4066 int32_t oldTargetFlags = touchedWindow.targetFlags;
4067 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004069 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004071 int32_t newTargetFlags = oldTargetFlags &
4072 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4073 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004074 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075
Jeff Brownf086ddb2014-02-11 14:28:48 -08004076 found = true;
4077 goto Found;
4078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 }
4080 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004081 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004083 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004084 if (DEBUG_FOCUS) {
4085 ALOGD("Focus transfer failed because from window did not have focus.");
4086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 return false;
4088 }
4089
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004090 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4091 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004092 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004093 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004094 CancelationOptions
4095 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4096 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004098 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099 }
4100
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004101 if (DEBUG_FOCUS) {
4102 logDispatchStateLocked();
4103 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104 } // release lock
4105
4106 // Wake up poll loop since it may need to make new input dispatching choices.
4107 mLooper->wake();
4108 return true;
4109}
4110
4111void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004112 if (DEBUG_FOCUS) {
4113 ALOGD("Resetting and dropping all events (%s).", reason);
4114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115
4116 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4117 synthesizeCancelationEventsForAllConnectionsLocked(options);
4118
4119 resetKeyRepeatLocked();
4120 releasePendingEventLocked();
4121 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004122 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004124 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004125 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004127 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128}
4129
4130void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004131 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 dumpDispatchStateLocked(dump);
4133
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004134 std::istringstream stream(dump);
4135 std::string line;
4136
4137 while (std::getline(stream, line, '\n')) {
4138 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 }
4140}
4141
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004142void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004143 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4144 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4145 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004146 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147
Tiger Huang721e26f2018-07-24 22:26:19 +08004148 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4149 dump += StringPrintf(INDENT "FocusedApplications:\n");
4150 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4151 const int32_t displayId = it.first;
4152 const sp<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004153 const int64_t timeoutMillis = millis(
4154 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004155 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004156 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004157 displayId, applicationHandle->getName().c_str(), timeoutMillis);
Tiger Huang721e26f2018-07-24 22:26:19 +08004158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004160 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004162
4163 if (!mFocusedWindowHandlesByDisplay.empty()) {
4164 dump += StringPrintf(INDENT "FocusedWindows:\n");
4165 for (auto& it : mFocusedWindowHandlesByDisplay) {
4166 const int32_t displayId = it.first;
4167 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004168 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4169 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004170 }
4171 } else {
4172 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004175 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004176 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004177 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4178 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004179 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 state.displayId, toString(state.down), toString(state.split),
4181 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004182 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004183 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004184 for (size_t i = 0; i < state.windows.size(); i++) {
4185 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004186 dump += StringPrintf(INDENT4
4187 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4188 i, touchedWindow.windowHandle->getName().c_str(),
4189 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004190 }
4191 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004192 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004193 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004194 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004195 dump += INDENT3 "Portal windows:\n";
4196 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004197 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004198 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4199 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004200 }
4201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 }
4203 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004204 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205 }
4206
Arthur Hungb92218b2018-08-14 12:00:21 +08004207 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004208 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004209 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004210 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004211 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004212 dump += INDENT2 "Windows:\n";
4213 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004214 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004215 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216
Arthur Hungb92218b2018-08-14 12:00:21 +08004217 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004218 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004219 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004220 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004221 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004222 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004223 i, windowInfo->name.c_str(), windowInfo->displayId,
4224 windowInfo->portalToDisplayId,
4225 toString(windowInfo->paused),
4226 toString(windowInfo->hasFocus),
4227 toString(windowInfo->hasWallpaper),
4228 toString(windowInfo->visible),
4229 toString(windowInfo->canReceiveKeys),
Michael Wright44753b12020-07-08 13:48:11 +01004230 windowInfo->flags.string(InputWindowInfo::flagToString)
4231 .c_str(),
4232 static_cast<int32_t>(windowInfo->type),
4233 windowInfo->frameLeft, windowInfo->frameTop,
4234 windowInfo->frameRight, windowInfo->frameBottom,
4235 windowInfo->globalScaleFactor, windowInfo->windowXScale,
4236 windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004237 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004238 dump += StringPrintf(", inputFeatures=%s",
4239 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004240 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4241 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004242 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004243 millis(windowInfo->dispatchingTimeout));
Arthur Hungb92218b2018-08-14 12:00:21 +08004244 }
4245 } else {
4246 dump += INDENT2 "Windows: <none>\n";
4247 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 }
4249 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004250 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 }
4252
Michael Wright3dd60e22019-03-27 22:06:44 +00004253 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004254 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004255 const std::vector<Monitor>& monitors = it.second;
4256 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4257 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004258 }
4259 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004260 const std::vector<Monitor>& monitors = it.second;
4261 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4262 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004265 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 }
4267
4268 nsecs_t currentTime = now();
4269
4270 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004271 if (!mRecentQueue.empty()) {
4272 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4273 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004274 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004276 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 }
4278 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004279 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 }
4281
4282 // Dump event currently being dispatched.
4283 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004284 dump += INDENT "PendingEvent:\n";
4285 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004287 dump += StringPrintf(", age=%" PRId64 "ms\n",
4288 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004290 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 }
4292
4293 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004294 if (!mInboundQueue.empty()) {
4295 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4296 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004297 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004299 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 }
4301 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004302 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303 }
4304
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004305 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004306 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004307 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4308 const KeyReplacement& replacement = pair.first;
4309 int32_t newKeyCode = pair.second;
4310 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004311 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004312 }
4313 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004314 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004315 }
4316
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004317 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004318 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004319 for (const auto& pair : mConnectionsByFd) {
4320 const sp<Connection>& connection = pair.second;
4321 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004322 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004323 pair.first, connection->getInputChannelName().c_str(),
4324 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004325 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004327 if (!connection->outboundQueue.empty()) {
4328 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4329 connection->outboundQueue.size());
4330 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 dump.append(INDENT4);
4332 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004333 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4334 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004335 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004336 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337 }
4338 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004339 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 }
4341
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004342 if (!connection->waitQueue.empty()) {
4343 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4344 connection->waitQueue.size());
4345 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004346 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004348 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004349 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004350 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004351 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004352 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353 }
4354 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004355 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356 }
4357 }
4358 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004359 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 }
4361
4362 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004363 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4364 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004366 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 }
4368
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004369 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004370 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4371 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4372 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373}
4374
Michael Wright3dd60e22019-03-27 22:06:44 +00004375void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4376 const size_t numMonitors = monitors.size();
4377 for (size_t i = 0; i < numMonitors; i++) {
4378 const Monitor& monitor = monitors[i];
4379 const sp<InputChannel>& channel = monitor.inputChannel;
4380 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4381 dump += "\n";
4382 }
4383}
4384
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004385status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004387 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388#endif
4389
4390 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004391 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004392 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004393 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004395 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 return BAD_VALUE;
4397 }
4398
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004399 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400
4401 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004402 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004403 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4406 } // release lock
4407
4408 // Wake the looper because some connections have changed.
4409 mLooper->wake();
4410 return OK;
4411}
4412
Michael Wright3dd60e22019-03-27 22:06:44 +00004413status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004414 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004415 { // acquire lock
4416 std::scoped_lock _l(mLock);
4417
4418 if (displayId < 0) {
4419 ALOGW("Attempted to register input monitor without a specified display.");
4420 return BAD_VALUE;
4421 }
4422
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004423 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004424 ALOGW("Attempted to register input monitor without an identifying token.");
4425 return BAD_VALUE;
4426 }
4427
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004428 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004429
4430 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004431 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004432 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004433
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004434 auto& monitorsByDisplay =
4435 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004436 monitorsByDisplay[displayId].emplace_back(inputChannel);
4437
4438 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004439 }
4440 // Wake the looper because some connections have changed.
4441 mLooper->wake();
4442 return OK;
4443}
4444
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4446#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004447 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448#endif
4449
4450 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004451 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452
4453 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4454 if (status) {
4455 return status;
4456 }
4457 } // release lock
4458
4459 // Wake the poll loop because removing the connection may have changed the current
4460 // synchronization state.
4461 mLooper->wake();
4462 return OK;
4463}
4464
4465status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004466 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004467 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004468 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004470 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 return BAD_VALUE;
4472 }
4473
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004474 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004475 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004476
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477 if (connection->monitor) {
4478 removeMonitorChannelLocked(inputChannel);
4479 }
4480
4481 mLooper->removeFd(inputChannel->getFd());
4482
4483 nsecs_t currentTime = now();
4484 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4485
4486 connection->status = Connection::STATUS_ZOMBIE;
4487 return OK;
4488}
4489
4490void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004491 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4492 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4493}
4494
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004495void InputDispatcher::removeMonitorChannelLocked(
4496 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004497 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004498 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004499 std::vector<Monitor>& monitors = it->second;
4500 const size_t numMonitors = monitors.size();
4501 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004502 if (monitors[i].inputChannel == inputChannel) {
4503 monitors.erase(monitors.begin() + i);
4504 break;
4505 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004506 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004507 if (monitors.empty()) {
4508 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004509 } else {
4510 ++it;
4511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 }
4513}
4514
Michael Wright3dd60e22019-03-27 22:06:44 +00004515status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4516 { // acquire lock
4517 std::scoped_lock _l(mLock);
4518 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4519
4520 if (!foundDisplayId) {
4521 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4522 return BAD_VALUE;
4523 }
4524 int32_t displayId = foundDisplayId.value();
4525
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004526 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4527 mTouchStatesByDisplay.find(displayId);
4528 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004529 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4530 return BAD_VALUE;
4531 }
4532
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004533 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004534 std::optional<int32_t> foundDeviceId;
4535 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004536 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004537 foundDeviceId = state.deviceId;
4538 }
4539 }
4540 if (!foundDeviceId || !state.down) {
4541 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004542 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004543 return BAD_VALUE;
4544 }
4545 int32_t deviceId = foundDeviceId.value();
4546
4547 // Send cancel events to all the input channels we're stealing from.
4548 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004549 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004550 options.deviceId = deviceId;
4551 options.displayId = displayId;
4552 for (const TouchedWindow& window : state.windows) {
4553 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004554 if (channel != nullptr) {
4555 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4556 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004557 }
4558 // Then clear the current touch state so we stop dispatching to them as well.
4559 state.filterNonMonitors();
4560 }
4561 return OK;
4562}
4563
Michael Wright3dd60e22019-03-27 22:06:44 +00004564std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4565 const sp<IBinder>& token) {
4566 for (const auto& it : mGestureMonitorsByDisplay) {
4567 const std::vector<Monitor>& monitors = it.second;
4568 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004569 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004570 return it.first;
4571 }
4572 }
4573 }
4574 return std::nullopt;
4575}
4576
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004577sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004578 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004579 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004580 }
4581
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004582 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004583 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004584 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004585 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004586 }
4587 }
Robert Carr4e670e52018-08-15 13:26:12 -07004588
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004589 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004590}
4591
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004592void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004593 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004594 removeByValue(mConnectionsByFd, connection);
4595}
4596
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004597void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4598 const sp<Connection>& connection, uint32_t seq,
4599 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004600 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4601 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602 commandEntry->connection = connection;
4603 commandEntry->eventTime = currentTime;
4604 commandEntry->seq = seq;
4605 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004606 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607}
4608
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004609void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4610 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004612 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004614 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4615 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004617 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618}
4619
chaviw0c06c6e2019-01-09 13:27:07 -08004620void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004621 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004622 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4623 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004624 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4625 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004626 commandEntry->oldToken = oldToken;
4627 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004628 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004629}
4630
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004631void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4632 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4633 // is already healthy again. Don't raise ANR in this situation
4634 if (connection->waitQueue.empty()) {
4635 ALOGI("Not raising ANR because the connection %s has recovered",
4636 connection->inputChannel->getName().c_str());
4637 return;
4638 }
4639 /**
4640 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4641 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4642 * has changed. This could cause newer entries to time out before the already dispatched
4643 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4644 * processes the events linearly. So providing information about the oldest entry seems to be
4645 * most useful.
4646 */
4647 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4648 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4649 std::string reason =
4650 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4651 connection->inputChannel->getName().c_str(),
4652 ns2ms(currentWait),
4653 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004655 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4656 reason);
4657
4658 std::unique_ptr<CommandEntry> commandEntry =
4659 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4660 commandEntry->inputApplicationHandle = nullptr;
4661 commandEntry->inputChannel = connection->inputChannel;
4662 commandEntry->reason = std::move(reason);
4663 postCommandLocked(std::move(commandEntry));
4664}
4665
4666void InputDispatcher::onAnrLocked(const sp<InputApplicationHandle>& application) {
4667 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4668 application->getName().c_str());
4669
4670 updateLastAnrStateLocked(application, reason);
4671
4672 std::unique_ptr<CommandEntry> commandEntry =
4673 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4674 commandEntry->inputApplicationHandle = application;
4675 commandEntry->inputChannel = nullptr;
4676 commandEntry->reason = std::move(reason);
4677 postCommandLocked(std::move(commandEntry));
4678}
4679
4680void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4681 const std::string& reason) {
4682 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4683 updateLastAnrStateLocked(windowLabel, reason);
4684}
4685
4686void InputDispatcher::updateLastAnrStateLocked(const sp<InputApplicationHandle>& application,
4687 const std::string& reason) {
4688 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4689 updateLastAnrStateLocked(windowLabel, reason);
4690}
4691
4692void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4693 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004695 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 struct tm tm;
4697 localtime_r(&t, &tm);
4698 char timestr[64];
4699 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004700 mLastAnrState.clear();
4701 mLastAnrState += INDENT "ANR:\n";
4702 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004703 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4704 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004705 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706}
4707
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004708void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709 mLock.unlock();
4710
4711 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4712
4713 mLock.lock();
4714}
4715
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004716void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717 sp<Connection> connection = commandEntry->connection;
4718
4719 if (connection->status != Connection::STATUS_ZOMBIE) {
4720 mLock.unlock();
4721
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004722 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723
4724 mLock.lock();
4725 }
4726}
4727
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004728void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004729 sp<IBinder> oldToken = commandEntry->oldToken;
4730 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004731 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004732 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004733 mLock.lock();
4734}
4735
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004736void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004737 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004738 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 mLock.unlock();
4740
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004741 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004742 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743
4744 mLock.lock();
4745
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004746 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004747 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4748 } else {
4749 // stop waking up for events in this connection, it is already not responding
4750 sp<Connection> connection = getConnectionLocked(token);
4751 if (connection == nullptr) {
4752 return;
4753 }
4754 cancelEventsForAnrLocked(connection);
4755 }
4756}
4757
4758void InputDispatcher::extendAnrTimeoutsLocked(const sp<InputApplicationHandle>& application,
4759 const sp<IBinder>& connectionToken,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004760 std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004761 sp<Connection> connection = getConnectionLocked(connectionToken);
4762 if (connection == nullptr) {
4763 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4764 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004765 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004766 mAwaitedFocusedApplication = application;
4767 } else {
4768 // It's also possible that the connection already disappeared. No action necessary.
4769 }
4770 return;
4771 }
4772
4773 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004774 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004775
4776 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004777 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004778 for (DispatchEntry* entry : connection->waitQueue) {
4779 if (newTimeout >= entry->timeoutTime) {
4780 // Already removed old entries when connection was marked unresponsive
4781 entry->timeoutTime = newTimeout;
4782 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4783 }
4784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785}
4786
4787void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4788 CommandEntry* commandEntry) {
4789 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004790 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791
4792 mLock.unlock();
4793
Michael Wright2b3c3302018-03-02 17:19:13 +00004794 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004795 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004796 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004797 : nullptr;
4798 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004799 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4800 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004801 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803
4804 mLock.lock();
4805
4806 if (delay < 0) {
4807 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4808 } else if (!delay) {
4809 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4810 } else {
4811 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4812 entry->interceptKeyWakeupTime = now() + delay;
4813 }
4814 entry->release();
4815}
4816
chaviwfd6d3512019-03-25 13:23:49 -07004817void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4818 mLock.unlock();
4819 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4820 mLock.lock();
4821}
4822
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004823/**
4824 * Connection is responsive if it has no events in the waitQueue that are older than the
4825 * current time.
4826 */
4827static bool isConnectionResponsive(const Connection& connection) {
4828 const nsecs_t currentTime = now();
4829 for (const DispatchEntry* entry : connection.waitQueue) {
4830 if (entry->timeoutTime < currentTime) {
4831 return false;
4832 }
4833 }
4834 return true;
4835}
4836
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004837void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004839 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004841 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842
4843 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004844 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004845 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004846 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004848 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004849 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004850 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004851 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4852 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004853 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004854 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004855
4856 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004857 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004858 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4859 restartEvent =
4860 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004861 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004862 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4863 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4864 handled);
4865 } else {
4866 restartEvent = false;
4867 }
4868
4869 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004870 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004871 // contents of the wait queue to have been drained, so we need to double-check
4872 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004873 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4874 if (dispatchEntryIt != connection->waitQueue.end()) {
4875 dispatchEntry = *dispatchEntryIt;
4876 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004877 mAnrTracker.erase(dispatchEntry->timeoutTime,
4878 connection->inputChannel->getConnectionToken());
4879 if (!connection->responsive) {
4880 connection->responsive = isConnectionResponsive(*connection);
4881 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004882 traceWaitQueueLength(connection);
4883 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004884 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004885 traceOutboundQueueLength(connection);
4886 } else {
4887 releaseDispatchEntry(dispatchEntry);
4888 }
4889 }
4890
4891 // Start the next dispatch cycle for this connection.
4892 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893}
4894
4895bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004896 DispatchEntry* dispatchEntry,
4897 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004898 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004899 if (!handled) {
4900 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004901 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004902 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004903 return false;
4904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004906 // Get the fallback key state.
4907 // Clear it out after dispatching the UP.
4908 int32_t originalKeyCode = keyEntry->keyCode;
4909 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4910 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4911 connection->inputState.removeFallbackKey(originalKeyCode);
4912 }
4913
4914 if (handled || !dispatchEntry->hasForegroundTarget()) {
4915 // If the application handles the original key for which we previously
4916 // generated a fallback or if the window is not a foreground window,
4917 // then cancel the associated fallback key, if any.
4918 if (fallbackKeyCode != -1) {
4919 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004921 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004922 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4923 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4924 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004926 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004927 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928
4929 mLock.unlock();
4930
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004931 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004932 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933
4934 mLock.lock();
4935
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004936 // Cancel the fallback key.
4937 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004939 "application handled the original non-fallback key "
4940 "or is no longer a foreground target, "
4941 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942 options.keyCode = fallbackKeyCode;
4943 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004945 connection->inputState.removeFallbackKey(originalKeyCode);
4946 }
4947 } else {
4948 // If the application did not handle a non-fallback key, first check
4949 // that we are in a good state to perform unhandled key event processing
4950 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004951 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004952 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004954 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004955 "since this is not an initial down. "
4956 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4957 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004959 return false;
4960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004961
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004962 // Dispatch the unhandled key to the policy.
4963#if DEBUG_OUTBOUND_EVENT_DETAILS
4964 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004965 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4966 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004967#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004968 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004969
4970 mLock.unlock();
4971
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004972 bool fallback =
4973 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4974 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004975
4976 mLock.lock();
4977
4978 if (connection->status != Connection::STATUS_NORMAL) {
4979 connection->inputState.removeFallbackKey(originalKeyCode);
4980 return false;
4981 }
4982
4983 // Latch the fallback keycode for this key on an initial down.
4984 // The fallback keycode cannot change at any other point in the lifecycle.
4985 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004987 fallbackKeyCode = event.getKeyCode();
4988 } else {
4989 fallbackKeyCode = AKEYCODE_UNKNOWN;
4990 }
4991 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4992 }
4993
4994 ALOG_ASSERT(fallbackKeyCode != -1);
4995
4996 // Cancel the fallback key if the policy decides not to send it anymore.
4997 // We will continue to dispatch the key to the policy but we will no
4998 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004999 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
5000 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005001#if DEBUG_OUTBOUND_EVENT_DETAILS
5002 if (fallback) {
5003 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005004 "as a fallback for %d, but on the DOWN it had requested "
5005 "to send %d instead. Fallback canceled.",
5006 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005007 } else {
5008 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005009 "but on the DOWN it had requested to send %d. "
5010 "Fallback canceled.",
5011 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005012 }
5013#endif
5014
5015 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5016 "canceling fallback, policy no longer desires it");
5017 options.keyCode = fallbackKeyCode;
5018 synthesizeCancelationEventsForConnectionLocked(connection, options);
5019
5020 fallback = false;
5021 fallbackKeyCode = AKEYCODE_UNKNOWN;
5022 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005023 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005024 }
5025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005026
5027#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005028 {
5029 std::string msg;
5030 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5031 connection->inputState.getFallbackKeys();
5032 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005033 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005034 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005035 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005036 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005037 }
5038#endif
5039
5040 if (fallback) {
5041 // Restart the dispatch cycle using the fallback key.
5042 keyEntry->eventTime = event.getEventTime();
5043 keyEntry->deviceId = event.getDeviceId();
5044 keyEntry->source = event.getSource();
5045 keyEntry->displayId = event.getDisplayId();
5046 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5047 keyEntry->keyCode = fallbackKeyCode;
5048 keyEntry->scanCode = event.getScanCode();
5049 keyEntry->metaState = event.getMetaState();
5050 keyEntry->repeatCount = event.getRepeatCount();
5051 keyEntry->downTime = event.getDownTime();
5052 keyEntry->syntheticRepeat = false;
5053
5054#if DEBUG_OUTBOUND_EVENT_DETAILS
5055 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005056 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5057 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005058#endif
5059 return true; // restart the event
5060 } else {
5061#if DEBUG_OUTBOUND_EVENT_DETAILS
5062 ALOGD("Unhandled key event: No fallback key.");
5063#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005064
5065 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005066 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005067 }
5068 }
5069 return false;
5070}
5071
5072bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005073 DispatchEntry* dispatchEntry,
5074 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075 return false;
5076}
5077
5078void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5079 mLock.unlock();
5080
5081 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5082
5083 mLock.lock();
5084}
5085
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005086KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5087 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005088 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005089 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5090 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005091 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092}
5093
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005094void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5095 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 // TODO Write some statistics about how long we spend waiting.
5097}
5098
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005099/**
5100 * Report the touch event latency to the statsd server.
5101 * Input events are reported for statistics if:
5102 * - This is a touchscreen event
5103 * - InputFilter is not enabled
5104 * - Event is not injected or synthesized
5105 *
5106 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5107 * from getting aggregated with the "old" data.
5108 */
5109void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5110 REQUIRES(mLock) {
5111 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5112 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5113 if (!reportForStatistics) {
5114 return;
5115 }
5116
5117 if (mTouchStatistics.shouldReport()) {
5118 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5119 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5120 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5121 mTouchStatistics.reset();
5122 }
5123 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5124 mTouchStatistics.addValue(latencyMicros);
5125}
5126
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127void InputDispatcher::traceInboundQueueLengthLocked() {
5128 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005129 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130 }
5131}
5132
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005133void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134 if (ATRACE_ENABLED()) {
5135 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005136 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005137 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138 }
5139}
5140
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005141void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142 if (ATRACE_ENABLED()) {
5143 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005144 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005145 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 }
5147}
5148
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005149void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005150 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005152 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 dumpDispatchStateLocked(dump);
5154
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005155 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005156 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005157 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158 }
5159}
5160
5161void InputDispatcher::monitor() {
5162 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005163 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005165 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166}
5167
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005168/**
5169 * Wake up the dispatcher and wait until it processes all events and commands.
5170 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5171 * this method can be safely called from any thread, as long as you've ensured that
5172 * the work you are interested in completing has already been queued.
5173 */
5174bool InputDispatcher::waitForIdle() {
5175 /**
5176 * Timeout should represent the longest possible time that a device might spend processing
5177 * events and commands.
5178 */
5179 constexpr std::chrono::duration TIMEOUT = 100ms;
5180 std::unique_lock lock(mLock);
5181 mLooper->wake();
5182 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5183 return result == std::cv_status::no_timeout;
5184}
5185
Garfield Tane84e6f92019-08-29 17:28:41 -07005186} // namespace android::inputdispatcher