blob: e3ab522d6d52fb7a94581d6a0a28d62e61ed4a28 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Garfield Tane84e6f92019-08-29 17:28:41 -070048#include "Connection.h"
49
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <errno.h>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080051#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <limits.h>
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -050053#include <statslog.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080055#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056#include <unistd.h>
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -070057#include <queue>
58#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070059
Michael Wright2b3c3302018-03-02 17:19:13 +000060#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070062#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080063#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <log/log.h>
Gang Wang342c9272020-01-13 13:15:04 -050065#include <openssl/hmac.h>
66#include <openssl/rand.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070067#include <powermanager/PowerManager.h>
68#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080069
70#define INDENT " "
71#define INDENT2 " "
72#define INDENT3 " "
73#define INDENT4 " "
74
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080075using android::base::StringPrintf;
76
Garfield Tane84e6f92019-08-29 17:28:41 -070077namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
79// Default input dispatching timeout if there is no focused application or paused window
80// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -070081constexpr std::chrono::nanoseconds DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5s;
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Amount of time to allow for all pending events to be processed when an app switch
84// key is on the way. This is used to preempt input dispatch and drop input events
85// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000086constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow for an event to be dispatched (measured since its eventTime)
89// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
Michael Wrightd02c5b62014-02-10 15:10:22 -080092// 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 +000093constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
94
95// Log a warning when an interception call takes longer than this to process.
96constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Siarhei Vishniakoue4623042020-03-25 16:16:40 -070098// Additional key latency in case a connection is still processing some motion events.
99// This will help with the case when a user touched a button that opens a new window,
100// and gives us the chance to dispatch the key to this new window.
101constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
102
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000104constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
105
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106static inline nsecs_t now() {
107 return systemTime(SYSTEM_TIME_MONOTONIC);
108}
109
110static inline const char* toString(bool value) {
111 return value ? "true" : "false";
112}
113
114static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700115 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
116 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117}
118
119static bool isValidKeyAction(int32_t action) {
120 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700121 case AKEY_EVENT_ACTION_DOWN:
122 case AKEY_EVENT_ACTION_UP:
123 return true;
124 default:
125 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126 }
127}
128
129static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700130 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131 ALOGE("Key event has invalid action code 0x%x", action);
132 return false;
133 }
134 return true;
135}
136
Michael Wright7b159c92015-05-14 14:48:03 +0100137static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700139 case AMOTION_EVENT_ACTION_DOWN:
140 case AMOTION_EVENT_ACTION_UP:
141 case AMOTION_EVENT_ACTION_CANCEL:
142 case AMOTION_EVENT_ACTION_MOVE:
143 case AMOTION_EVENT_ACTION_OUTSIDE:
144 case AMOTION_EVENT_ACTION_HOVER_ENTER:
145 case AMOTION_EVENT_ACTION_HOVER_MOVE:
146 case AMOTION_EVENT_ACTION_HOVER_EXIT:
147 case AMOTION_EVENT_ACTION_SCROLL:
148 return true;
149 case AMOTION_EVENT_ACTION_POINTER_DOWN:
150 case AMOTION_EVENT_ACTION_POINTER_UP: {
151 int32_t index = getMotionEventActionPointerIndex(action);
152 return index >= 0 && index < pointerCount;
153 }
154 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
155 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
156 return actionButton != 0;
157 default:
158 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800159 }
160}
161
Michael Wright7b159c92015-05-14 14:48:03 +0100162static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700163 const PointerProperties* pointerProperties) {
164 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 ALOGE("Motion event has invalid action code 0x%x", action);
166 return false;
167 }
168 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000169 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700170 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800171 return false;
172 }
173 BitSet32 pointerIdBits;
174 for (size_t i = 0; i < pointerCount; i++) {
175 int32_t id = pointerProperties[i].id;
176 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700177 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
178 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800179 return false;
180 }
181 if (pointerIdBits.hasBit(id)) {
182 ALOGE("Motion event has duplicate pointer id %d", id);
183 return false;
184 }
185 pointerIdBits.markBit(id);
186 }
187 return true;
188}
189
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800190static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800192 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 return;
194 }
195
196 bool first = true;
197 Region::const_iterator cur = region.begin();
198 Region::const_iterator const tail = region.end();
199 while (cur != tail) {
200 if (first) {
201 first = false;
202 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800203 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800205 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800206 cur++;
207 }
208}
209
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700210/**
211 * Find the entry in std::unordered_map by key, and return it.
212 * If the entry is not found, return a default constructed entry.
213 *
214 * Useful when the entries are vectors, since an empty vector will be returned
215 * if the entry is not found.
216 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
217 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700218template <typename K, typename V>
219static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700220 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700221 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800222}
223
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700224/**
225 * Find the entry in std::unordered_map by value, and remove it.
226 * If more than one entry has the same value, then all matching
227 * key-value pairs will be removed.
228 *
229 * Return true if at least one value has been removed.
230 */
231template <typename K, typename V>
232static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
233 bool removed = false;
234 for (auto it = map.begin(); it != map.end();) {
235 if (it->second == value) {
236 it = map.erase(it);
237 removed = true;
238 } else {
239 it++;
240 }
241 }
242 return removed;
243}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244
chaviwaf87b3e2019-10-01 16:59:28 -0700245static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
246 if (first == second) {
247 return true;
248 }
249
250 if (first == nullptr || second == nullptr) {
251 return false;
252 }
253
254 return first->getToken() == second->getToken();
255}
256
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800257static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
258 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
259}
260
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000261static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
262 EventEntry* eventEntry,
263 int32_t inputTargetFlags) {
264 if (inputTarget.useDefaultPointerInfo()) {
265 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
266 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
267 inputTargetFlags, pointerInfo.xOffset,
268 pointerInfo.yOffset, inputTarget.globalScaleFactor,
269 pointerInfo.windowXScale, pointerInfo.windowYScale);
270 }
271
272 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
273 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
274
275 PointerCoords pointerCoords[motionEntry.pointerCount];
276
277 // Use the first pointer information to normalize all other pointers. This could be any pointer
278 // as long as all other pointers are normalized to the same value and the final DispatchEntry
279 // uses the offset and scale for the normalized pointer.
280 const PointerInfo& firstPointerInfo =
281 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
282
283 // Iterate through all pointers in the event to normalize against the first.
284 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
285 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
286 uint32_t pointerId = uint32_t(pointerProperties.id);
287 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
288
289 // The scale factor is the ratio of the current pointers scale to the normalized scale.
290 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
291 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
292
293 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
294 // First apply the current pointers offset to set the window at 0,0
295 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
296 // Next scale the coordinates.
297 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
298 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
299 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
300 -firstPointerInfo.yOffset);
301 }
302
303 MotionEntry* combinedMotionEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800304 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000305 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
306 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
307 motionEntry.metaState, motionEntry.buttonState,
308 motionEntry.classification, motionEntry.edgeFlags,
309 motionEntry.xPrecision, motionEntry.yPrecision,
310 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
311 motionEntry.downTime, motionEntry.pointerCount,
312 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
313 0 /* yOffset */);
314
315 if (motionEntry.injectionState) {
316 combinedMotionEntry->injectionState = motionEntry.injectionState;
317 combinedMotionEntry->injectionState->refCount += 1;
318 }
319
320 std::unique_ptr<DispatchEntry> dispatchEntry =
321 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
322 inputTargetFlags, firstPointerInfo.xOffset,
323 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
324 firstPointerInfo.windowXScale,
325 firstPointerInfo.windowYScale);
326 combinedMotionEntry->release();
327 return dispatchEntry;
328}
329
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -0700330static void addGestureMonitors(const std::vector<Monitor>& monitors,
331 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
332 float yOffset = 0) {
333 if (monitors.empty()) {
334 return;
335 }
336 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
337 for (const Monitor& monitor : monitors) {
338 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
339 }
340}
341
Gang Wang342c9272020-01-13 13:15:04 -0500342static std::array<uint8_t, 128> getRandomKey() {
343 std::array<uint8_t, 128> key;
344 if (RAND_bytes(key.data(), key.size()) != 1) {
345 LOG_ALWAYS_FATAL("Can't generate HMAC key");
346 }
347 return key;
348}
349
350// --- HmacKeyManager ---
351
352HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
353
354std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
355 size_t size;
356 switch (event.type) {
357 case VerifiedInputEvent::Type::KEY: {
358 size = sizeof(VerifiedKeyEvent);
359 break;
360 }
361 case VerifiedInputEvent::Type::MOTION: {
362 size = sizeof(VerifiedMotionEvent);
363 break;
364 }
365 }
Gang Wang342c9272020-01-13 13:15:04 -0500366 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700367 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500368}
369
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700370std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500371 // SHA256 always generates 32-bytes result
372 std::array<uint8_t, 32> hash;
373 unsigned int hashLen = 0;
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700374 uint8_t* result =
375 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500376 if (result == nullptr) {
377 ALOGE("Could not sign the data using HMAC");
378 return INVALID_HMAC;
379 }
380
381 if (hashLen != hash.size()) {
382 ALOGE("HMAC-SHA256 has unexpected length");
383 return INVALID_HMAC;
384 }
385
386 return hash;
387}
388
Michael Wrightd02c5b62014-02-10 15:10:22 -0800389// --- InputDispatcher ---
390
Garfield Tan00f511d2019-06-12 16:55:40 -0700391InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
392 : mPolicy(policy),
393 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700394 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tan1c7bc862020-01-28 13:24:04 -0800395 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700396 mAppSwitchSawKeyDown(false),
397 mAppSwitchDueTime(LONG_LONG_MAX),
398 mNextUnblockedEvent(nullptr),
399 mDispatchEnabled(false),
400 mDispatchFrozen(false),
401 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800402 // mInTouchMode will be initialized by the WindowManager to the default device config.
403 // To avoid leaking stack in case that call never comes, and for tests,
404 // initialize it here anyways.
405 mInTouchMode(true),
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700406 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800407 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800408 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409
Yi Kong9b14ac62018-07-17 13:48:38 -0700410 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411
412 policy->getDispatcherConfiguration(&mConfig);
413}
414
415InputDispatcher::~InputDispatcher() {
416 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800417 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418
419 resetKeyRepeatLocked();
420 releasePendingEventLocked();
421 drainInboundQueueLocked();
422 }
423
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700424 while (!mConnectionsByFd.empty()) {
425 sp<Connection> connection = mConnectionsByFd.begin()->second;
426 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800427 }
428}
429
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700430status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700431 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700432 return ALREADY_EXISTS;
433 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700434 mThread = std::make_unique<InputThread>(
435 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
436 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700437}
438
439status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700440 if (mThread && mThread->isCallingThread()) {
441 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700442 return INVALID_OPERATION;
443 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700444 mThread.reset();
445 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700446}
447
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448void InputDispatcher::dispatchOnce() {
449 nsecs_t nextWakeupTime = LONG_LONG_MAX;
450 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800451 std::scoped_lock _l(mLock);
452 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453
454 // Run a dispatch loop if there are no pending commands.
455 // The dispatch loop might enqueue commands to run afterwards.
456 if (!haveCommandsLocked()) {
457 dispatchOnceInnerLocked(&nextWakeupTime);
458 }
459
460 // Run all pending commands if there are any.
461 // If any commands were run then force the next poll to wake up immediately.
462 if (runCommandsLockedInterruptible()) {
463 nextWakeupTime = LONG_LONG_MIN;
464 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800465
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700466 // If we are still waiting for ack on some events,
467 // we might have to wake up earlier to check if an app is anr'ing.
468 const nsecs_t nextAnrCheck = processAnrsLocked();
469 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
470
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800471 // We are about to enter an infinitely long sleep, because we have no commands or
472 // pending or queued events
473 if (nextWakeupTime == LONG_LONG_MAX) {
474 mDispatcherEnteredIdle.notify_all();
475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800476 } // release lock
477
478 // Wait for callback or timeout or wake. (make sure we round up, not down)
479 nsecs_t currentTime = now();
480 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
481 mLooper->pollOnce(timeoutMillis);
482}
483
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700484/**
485 * Check if any of the connections' wait queues have events that are too old.
486 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
487 * Return the time at which we should wake up next.
488 */
489nsecs_t InputDispatcher::processAnrsLocked() {
490 const nsecs_t currentTime = now();
491 nsecs_t nextAnrCheck = LONG_LONG_MAX;
492 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
493 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
494 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
495 onAnrLocked(mAwaitedFocusedApplication);
496 mAwaitedFocusedApplication.clear();
497 return LONG_LONG_MIN;
498 } else {
499 // Keep waiting
500 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
501 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
502 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
503 }
504 }
505
506 // Check if any connection ANRs are due
507 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
508 if (currentTime < nextAnrCheck) { // most likely scenario
509 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
510 }
511
512 // If we reached here, we have an unresponsive connection.
513 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
514 if (connection == nullptr) {
515 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
516 return nextAnrCheck;
517 }
518 connection->responsive = false;
519 // Stop waking up for this unresponsive connection
520 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
521 onAnrLocked(connection);
522 return LONG_LONG_MIN;
523}
524
525nsecs_t InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
526 sp<InputWindowHandle> window = getWindowHandleLocked(token);
527 if (window != nullptr) {
528 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT).count();
529 }
530 return DEFAULT_INPUT_DISPATCHING_TIMEOUT.count();
531}
532
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
534 nsecs_t currentTime = now();
535
Jeff Browndc5992e2014-04-11 01:27:26 -0700536 // Reset the key repeat timer whenever normal dispatch is suspended while the
537 // device is in a non-interactive state. This is to ensure that we abort a key
538 // repeat if the device is just coming out of sleep.
539 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 resetKeyRepeatLocked();
541 }
542
543 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
544 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100545 if (DEBUG_FOCUS) {
546 ALOGD("Dispatch frozen. Waiting some more.");
547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548 return;
549 }
550
551 // Optimize latency of app switches.
552 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
553 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
554 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
555 if (mAppSwitchDueTime < *nextWakeupTime) {
556 *nextWakeupTime = mAppSwitchDueTime;
557 }
558
559 // Ready to start a new event.
560 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700561 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700562 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 if (isAppSwitchDue) {
564 // The inbound queue is empty so the app switch key we were waiting
565 // for will never arrive. Stop waiting for it.
566 resetPendingAppSwitchLocked(false);
567 isAppSwitchDue = false;
568 }
569
570 // Synthesize a key repeat if appropriate.
571 if (mKeyRepeatState.lastKeyEntry) {
572 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
573 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
574 } else {
575 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
576 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
577 }
578 }
579 }
580
581 // Nothing to do if there is no pending event.
582 if (!mPendingEvent) {
583 return;
584 }
585 } else {
586 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700587 mPendingEvent = mInboundQueue.front();
588 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 traceInboundQueueLengthLocked();
590 }
591
592 // Poke user activity for this event.
593 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700594 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596 }
597
598 // Now we have an event to dispatch.
599 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700600 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700602 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700604 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700606 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607 }
608
609 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700610 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 }
612
613 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700614 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700615 ConfigurationChangedEntry* typedEntry =
616 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
617 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700618 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700619 break;
620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700622 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700623 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
624 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700625 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700626 break;
627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100629 case EventEntry::Type::FOCUS: {
630 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
631 dispatchFocusLocked(currentTime, typedEntry);
632 done = true;
633 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
634 break;
635 }
636
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700637 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700638 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
639 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700640 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700641 resetPendingAppSwitchLocked(true);
642 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700643 } else if (dropReason == DropReason::NOT_DROPPED) {
644 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700645 }
646 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700647 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700648 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700649 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700650 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
651 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700652 }
653 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
654 break;
655 }
656
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700657 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700658 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700659 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
660 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700662 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700663 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700664 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700665 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
666 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700667 }
668 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
669 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671 }
672
673 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700674 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700675 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 }
Michael Wright3a981722015-06-10 15:26:13 +0100677 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678
679 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 }
682}
683
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700684/**
685 * Return true if the events preceding this incoming motion event should be dropped
686 * Return false otherwise (the default behaviour)
687 */
688bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700689 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700690 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700691
692 // Optimize case where the current application is unresponsive and the user
693 // decides to touch a window in a different application.
694 // If the application takes too long to catch up then we drop all events preceding
695 // the touch into the other window.
696 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700697 int32_t displayId = motionEntry.displayId;
698 int32_t x = static_cast<int32_t>(
699 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
700 int32_t y = static_cast<int32_t>(
701 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700702 sp<InputWindowHandle> touchedWindowHandle =
703 findTouchedWindowAtLocked(displayId, x, y, nullptr);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700704 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700705 touchedWindowHandle->getApplicationToken() !=
706 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700707 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700708 ALOGI("Pruning input queue because user touched a different application while waiting "
709 "for %s",
710 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700711 return true;
712 }
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700713
714 // Alternatively, maybe there's a gesture monitor that could handle this event
715 std::vector<TouchedMonitor> gestureMonitors =
716 findTouchedGestureMonitorsLocked(displayId, {});
717 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
718 sp<Connection> connection =
719 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000720 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700721 // This monitor could take more input. Drop all events preceding this
722 // event, so that gesture monitor could get a chance to receive the stream
723 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
724 "responsive gesture monitor that may handle the event",
725 mAwaitedFocusedApplication->getName().c_str());
726 return true;
727 }
728 }
729 }
730
731 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
732 // yet been processed by some connections, the dispatcher will wait for these motion
733 // events to be processed before dispatching the key event. This is because these motion events
734 // may cause a new window to be launched, which the user might expect to receive focus.
735 // To prevent waiting forever for such events, just send the key to the currently focused window
736 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
737 ALOGD("Received a new pointer down event, stop waiting for events to process and "
738 "just send the pending key event to the focused window.");
739 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700740 }
741 return false;
742}
743
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700745 bool needWake = mInboundQueue.empty();
746 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 traceInboundQueueLengthLocked();
748
749 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700750 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700751 // Optimize app switch latency.
752 // If the application takes too long to catch up then we drop all events preceding
753 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700754 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700755 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700756 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700757 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700758 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700759 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700761 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700763 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700764 mAppSwitchSawKeyDown = false;
765 needWake = true;
766 }
767 }
768 }
769 break;
770 }
771
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700772 case EventEntry::Type::MOTION: {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700773 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
774 mNextUnblockedEvent = entry;
775 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100779 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700780 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
781 break;
782 }
783 case EventEntry::Type::CONFIGURATION_CHANGED:
784 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700785 // nothing to do
786 break;
787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 }
789
790 return needWake;
791}
792
793void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
794 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700795 mRecentQueue.push_back(entry);
796 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
797 mRecentQueue.front()->release();
798 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 }
800}
801
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700802sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700803 int32_t y, TouchState* touchState,
804 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805 bool addPortalWindows) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700806 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
807 LOG_ALWAYS_FATAL(
808 "Must provide a valid touch state if adding portal windows or outside targets");
809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800811 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
812 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 const InputWindowInfo* windowInfo = windowHandle->getInfo();
814 if (windowInfo->displayId == displayId) {
815 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816
817 if (windowInfo->visible) {
818 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700819 bool isTouchModal = (flags &
820 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
821 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800823 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 if (portalToDisplayId != ADISPLAY_ID_NONE &&
825 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800826 if (addPortalWindows) {
827 // For the monitoring channels of the display.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700828 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800829 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700830 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700831 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 // Found window.
834 return windowHandle;
835 }
836 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800837
838 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700839 touchState->addOrUpdateWindow(windowHandle,
840 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
841 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 }
845 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700846 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847}
848
Garfield Tane84e6f92019-08-29 17:28:41 -0700849std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -0700850 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000851 std::vector<TouchedMonitor> touchedMonitors;
852
853 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
854 addGestureMonitors(monitors, touchedMonitors);
855 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
856 const InputWindowInfo* windowInfo = portalWindow->getInfo();
857 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700858 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
859 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000860 }
861 return touchedMonitors;
862}
863
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700864void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 const char* reason;
866 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700867 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700869 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700871 reason = "inbound event was dropped because the policy consumed it";
872 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700873 case DropReason::DISABLED:
874 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 ALOGI("Dropped event because input dispatch is disabled.");
876 }
877 reason = "inbound event was dropped because input dispatch is disabled";
878 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700879 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700880 ALOGI("Dropped event because of pending overdue app switch.");
881 reason = "inbound event was dropped because of pending overdue app switch";
882 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 ALOGI("Dropped event because the current application is not responding and the user "
885 "has started interacting with a different application.");
886 reason = "inbound event was dropped because the current application is not responding "
887 "and the user has started interacting with a different application";
888 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700889 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700890 ALOGI("Dropped event because it is stale.");
891 reason = "inbound event was dropped because it is stale";
892 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700893 case DropReason::NOT_DROPPED: {
894 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700895 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
898
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700899 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700900 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
902 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700905 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700906 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
907 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700908 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
909 synthesizeCancelationEventsForAllConnectionsLocked(options);
910 } else {
911 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
912 synthesizeCancelationEventsForAllConnectionsLocked(options);
913 }
914 break;
915 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100916 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700917 case EventEntry::Type::CONFIGURATION_CHANGED:
918 case EventEntry::Type::DEVICE_RESET: {
919 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
920 break;
921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 }
923}
924
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800925static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700926 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
927 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928}
929
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700930bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
931 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
932 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
933 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934}
935
936bool InputDispatcher::isAppSwitchPendingLocked() {
937 return mAppSwitchDueTime != LONG_LONG_MAX;
938}
939
940void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
941 mAppSwitchDueTime = LONG_LONG_MAX;
942
943#if DEBUG_APP_SWITCH
944 if (handled) {
945 ALOGD("App switch has arrived.");
946 } else {
947 ALOGD("App switch was abandoned.");
948 }
949#endif
950}
951
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700953 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954}
955
956bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700957 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958 return false;
959 }
960
961 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700962 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700963 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700965 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966
967 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700968 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 return true;
970}
971
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700972void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
973 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974}
975
976void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700977 while (!mInboundQueue.empty()) {
978 EventEntry* entry = mInboundQueue.front();
979 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980 releaseInboundEventLocked(entry);
981 }
982 traceInboundQueueLengthLocked();
983}
984
985void InputDispatcher::releasePendingEventLocked() {
986 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700988 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 }
990}
991
992void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
993 InjectionState* injectionState = entry->injectionState;
994 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
995#if DEBUG_DISPATCH_CYCLE
996 ALOGD("Injected inbound event was dropped.");
997#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800998 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
1000 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001001 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 }
1003 addRecentEventLocked(entry);
1004 entry->release();
1005}
1006
1007void InputDispatcher::resetKeyRepeatLocked() {
1008 if (mKeyRepeatState.lastKeyEntry) {
1009 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001010 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 }
1012}
1013
Garfield Tane84e6f92019-08-29 17:28:41 -07001014KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1016
1017 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001018 uint32_t policyFlags = entry->policyFlags &
1019 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 if (entry->refCount == 1) {
1021 entry->recycle();
Garfield Tan1c7bc862020-01-28 13:24:04 -08001022 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 entry->eventTime = currentTime;
1024 entry->policyFlags = policyFlags;
1025 entry->repeatCount += 1;
1026 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 KeyEntry* newEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08001028 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001029 entry->displayId, policyFlags, entry->action, entry->flags,
1030 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032
1033 mKeyRepeatState.lastKeyEntry = newEntry;
1034 entry->release();
1035
1036 entry = newEntry;
1037 }
1038 entry->syntheticRepeat = true;
1039
1040 // Increment reference count since we keep a reference to the event in
1041 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1042 entry->refCount += 1;
1043
1044 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1045 return entry;
1046}
1047
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001048bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1049 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001051 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052#endif
1053
1054 // Reset key repeating in case a keyboard device was added or removed or something.
1055 resetKeyRepeatLocked();
1056
1057 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001058 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1059 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001061 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 return true;
1063}
1064
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001065bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001067 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069#endif
1070
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001071 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 options.deviceId = entry->deviceId;
1073 synthesizeCancelationEventsForAllConnectionsLocked(options);
1074 return true;
1075}
1076
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001077void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07001078 if (mPendingEvent != nullptr) {
1079 // Move the pending event to the front of the queue. This will give the chance
1080 // for the pending event to get dispatched to the newly focused window
1081 mInboundQueue.push_front(mPendingEvent);
1082 mPendingEvent = nullptr;
1083 }
1084
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001085 FocusEntry* focusEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08001086 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07001087
1088 // This event should go to the front of the queue, but behind all other focus events
1089 // Find the last focus event, and insert right after it
1090 std::deque<EventEntry*>::reverse_iterator it =
1091 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1092 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1093
1094 // Maintain the order of focus events. Insert the entry after all other focus events.
1095 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001096}
1097
1098void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1099 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1100 if (channel == nullptr) {
1101 return; // Window has gone away
1102 }
1103 InputTarget target;
1104 target.inputChannel = channel;
1105 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1106 entry->dispatchInProgress = true;
Selim Cinek3d989c22020-06-17 21:42:12 +00001107
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001108 dispatchEventLocked(currentTime, entry, {target});
1109}
1110
Michael Wrightd02c5b62014-02-10 15:10:22 -08001111bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001112 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 if (!entry->dispatchInProgress) {
1115 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1116 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1117 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1118 if (mKeyRepeatState.lastKeyEntry &&
1119 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 // We have seen two identical key downs in a row which indicates that the device
1121 // driver is automatically generating key repeats itself. We take note of the
1122 // repeat here, but we disable our own next key repeat timer since it is clear that
1123 // we will not need to synthesize key repeats ourselves.
1124 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1125 resetKeyRepeatLocked();
1126 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1127 } else {
1128 // Not a repeat. Save key down state in case we do see a repeat later.
1129 resetKeyRepeatLocked();
1130 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1131 }
1132 mKeyRepeatState.lastKeyEntry = entry;
1133 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001134 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135 resetKeyRepeatLocked();
1136 }
1137
1138 if (entry->repeatCount == 1) {
1139 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1140 } else {
1141 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1142 }
1143
1144 entry->dispatchInProgress = true;
1145
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001146 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
1148
1149 // Handle case where the policy asked us to try again later last time.
1150 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1151 if (currentTime < entry->interceptKeyWakeupTime) {
1152 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1153 *nextWakeupTime = entry->interceptKeyWakeupTime;
1154 }
1155 return false; // wait until next wakeup
1156 }
1157 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1158 entry->interceptKeyWakeupTime = 0;
1159 }
1160
1161 // Give the policy a chance to intercept the key.
1162 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1163 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001164 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001165 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001166 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001167 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001168 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001169 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 }
1171 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001172 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 entry->refCount += 1;
1174 return false; // wait for the command to run
1175 } else {
1176 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1177 }
1178 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001179 if (*dropReason == DropReason::NOT_DROPPED) {
1180 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 }
1182 }
1183
1184 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001185 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001186 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001187 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001188 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001189 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 return true;
1191 }
1192
1193 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001194 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001195 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001196 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1198 return false;
1199 }
1200
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001201 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1203 return true;
1204 }
1205
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001206 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001207 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208
1209 // Dispatch the key.
1210 dispatchEventLocked(currentTime, entry, inputTargets);
1211 return true;
1212}
1213
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001214void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001216 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001217 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1218 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001219 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1220 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1221 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222#endif
1223}
1224
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001225bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1226 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001227 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 entry->dispatchInProgress = true;
1231
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001232 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 }
1234
1235 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001236 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001238 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001239 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 return true;
1241 }
1242
1243 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1244
1245 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001246 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247
1248 bool conflictingPointerActions = false;
1249 int32_t injectionResult;
1250 if (isPointerEvent) {
1251 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001252 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001253 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001254 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 } else {
1256 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001257 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001258 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 }
1260 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1261 return false;
1262 }
1263
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001264 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001265 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1266 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1267 return true;
1268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001270 CancelationOptions::Mode mode(isPointerEvent
1271 ? CancelationOptions::CANCEL_POINTER_EVENTS
1272 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1273 CancelationOptions options(mode, "input event injection failed");
1274 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 return true;
1276 }
1277
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001278 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001279 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001281 if (isPointerEvent) {
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001282 std::unordered_map<int32_t, TouchState>::iterator it =
1283 mTouchStatesByDisplay.find(entry->displayId);
1284 if (it != mTouchStatesByDisplay.end()) {
1285 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001286 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001287 // The event has gone through these portal windows, so we add monitoring targets of
1288 // the corresponding displays as well.
1289 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001290 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001291 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001292 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001293 }
1294 }
1295 }
1296 }
1297
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 // Dispatch the motion.
1299 if (conflictingPointerActions) {
1300 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001301 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 synthesizeCancelationEventsForAllConnectionsLocked(options);
1303 }
1304 dispatchEventLocked(currentTime, entry, inputTargets);
1305 return true;
1306}
1307
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001308void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001310 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001311 ", policyFlags=0x%x, "
1312 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1313 "metaState=0x%x, buttonState=0x%x,"
1314 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001315 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1316 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1317 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001319 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001321 "x=%f, y=%f, pressure=%f, size=%f, "
1322 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1323 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001324 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1325 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1326 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1327 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1328 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1329 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1330 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1331 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1332 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1333 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 }
1335#endif
1336}
1337
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001338void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1339 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001340 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341#if DEBUG_DISPATCH_CYCLE
1342 ALOGD("dispatchEventToCurrentInputTargets");
1343#endif
1344
1345 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1346
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001347 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001349 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001350 sp<Connection> connection =
1351 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001352 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001353 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001355 if (DEBUG_FOCUS) {
1356 ALOGD("Dropping event delivery to target with channel '%s' because it "
1357 "is no longer registered with the input dispatcher.",
1358 inputTarget.inputChannel->getName().c_str());
1359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 }
1361 }
1362}
1363
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001364void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1365 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1366 // If the policy decides to close the app, we will get a channel removal event via
1367 // unregisterInputChannel, and will clean up the connection that way. We are already not
1368 // sending new pointers to the connection when it blocked, but focused events will continue to
1369 // pile up.
1370 ALOGW("Canceling events for %s because it is unresponsive",
1371 connection->inputChannel->getName().c_str());
1372 if (connection->status == Connection::STATUS_NORMAL) {
1373 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1374 "application not responding");
1375 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 }
1377}
1378
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001379void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001380 if (DEBUG_FOCUS) {
1381 ALOGD("Resetting ANR timeouts.");
1382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383
1384 // Reset input target wait timeout.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001385 mNoFocusedWindowTimeoutTime = std::nullopt;
1386 mAwaitedFocusedApplication.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387}
1388
Tiger Huang721e26f2018-07-24 22:26:19 +08001389/**
1390 * Get the display id that the given event should go to. If this event specifies a valid display id,
1391 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1392 * Focused display is the display that the user most recently interacted with.
1393 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001394int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001395 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001396 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001397 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1399 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001400 break;
1401 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001402 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001403 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1404 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001405 break;
1406 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001407 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001408 case EventEntry::Type::CONFIGURATION_CHANGED:
1409 case EventEntry::Type::DEVICE_RESET: {
1410 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001411 return ADISPLAY_ID_NONE;
1412 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001413 }
1414 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1415}
1416
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001417bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1418 const char* focusedWindowName) {
1419 if (mAnrTracker.empty()) {
1420 // already processed all events that we waited for
1421 mKeyIsWaitingForEventsTimeout = std::nullopt;
1422 return false;
1423 }
1424
1425 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1426 // Start the timer
1427 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1428 "focus to change",
1429 focusedWindowName);
1430 mKeyIsWaitingForEventsTimeout = currentTime + KEY_WAITING_FOR_EVENTS_TIMEOUT.count();
1431 return true;
1432 }
1433
1434 // We still have pending events, and already started the timer
1435 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1436 return true; // Still waiting
1437 }
1438
1439 // Waited too long, and some connection still hasn't processed all motions
1440 // Just send the key to the focused window
1441 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1442 focusedWindowName);
1443 mKeyIsWaitingForEventsTimeout = std::nullopt;
1444 return false;
1445}
1446
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001448 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001449 std::vector<InputTarget>& inputTargets,
1450 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001451 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452
Tiger Huang721e26f2018-07-24 22:26:19 +08001453 int32_t displayId = getTargetDisplayId(entry);
1454 sp<InputWindowHandle> focusedWindowHandle =
1455 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1456 sp<InputApplicationHandle> focusedApplicationHandle =
1457 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1458
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 // If there is no currently focused window and no focused application
1460 // then drop the event.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001461 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1462 ALOGI("Dropping %s event because there is no focused window or focused application in "
1463 "display %" PRId32 ".",
1464 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001465 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 }
1467
Vishnu Nair0f13fe52022-01-26 22:55:57 +00001468 // Drop key events if requested by input feature
1469 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1470 return INPUT_EVENT_INJECTION_FAILED;
1471 }
1472
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001473 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1474 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1475 // start interacting with another application via touch (app switch). This code can be removed
1476 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1477 // an app is expected to have a focused window.
1478 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1479 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1480 // We just discovered that there's no focused window. Start the ANR timer
1481 const nsecs_t timeout = focusedApplicationHandle->getDispatchingTimeout(
1482 DEFAULT_INPUT_DISPATCHING_TIMEOUT.count());
1483 mNoFocusedWindowTimeoutTime = currentTime + timeout;
1484 mAwaitedFocusedApplication = focusedApplicationHandle;
1485 ALOGW("Waiting because no window has focus but %s may eventually add a "
1486 "window when it finishes starting up. Will wait for %" PRId64 "ms",
1487 mAwaitedFocusedApplication->getName().c_str(), ns2ms(timeout));
1488 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1489 return INPUT_EVENT_INJECTION_PENDING;
1490 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1491 // Already raised ANR. Drop the event
1492 ALOGE("Dropping %s event because there is no focused window",
1493 EventEntry::typeToString(entry.type));
1494 return INPUT_EVENT_INJECTION_FAILED;
1495 } else {
1496 // Still waiting for the focused window
1497 return INPUT_EVENT_INJECTION_PENDING;
1498 }
1499 }
1500
1501 // we have a valid, non-null focused window
1502 resetNoFocusedWindowTimeoutLocked();
1503
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001505 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001506 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 }
1508
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001509 if (focusedWindowHandle->getInfo()->paused) {
1510 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1511 return INPUT_EVENT_INJECTION_PENDING;
1512 }
1513
1514 // If the event is a key event, then we must wait for all previous events to
1515 // complete before delivering it because previous events may have the
1516 // side-effect of transferring focus to a different window and we want to
1517 // ensure that the following keys are sent to the new window.
1518 //
1519 // Suppose the user touches a button in a window then immediately presses "A".
1520 // If the button causes a pop-up window to appear then we want to ensure that
1521 // the "A" key is delivered to the new pop-up window. This is because users
1522 // often anticipate pending UI changes when typing on a keyboard.
1523 // To obtain this behavior, we must serialize key events with respect to all
1524 // prior input events.
1525 if (entry.type == EventEntry::Type::KEY) {
1526 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1527 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1528 return INPUT_EVENT_INJECTION_PENDING;
1529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 }
1531
1532 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001533 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001534 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1535 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536
1537 // Done.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001538 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539}
1540
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001541/**
1542 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1543 * that are currently unresponsive.
1544 */
1545std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1546 const std::vector<TouchedMonitor>& monitors) const {
1547 std::vector<TouchedMonitor> responsiveMonitors;
1548 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1549 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1550 sp<Connection> connection = getConnectionLocked(
1551 monitor.monitor.inputChannel->getConnectionToken());
1552 if (connection == nullptr) {
1553 ALOGE("Could not find connection for monitor %s",
1554 monitor.monitor.inputChannel->getName().c_str());
1555 return false;
1556 }
1557 if (!connection->responsive) {
1558 ALOGW("Unresponsive monitor %s will not get the new gesture",
1559 connection->inputChannel->getName().c_str());
1560 return false;
1561 }
1562 return true;
1563 });
1564 return responsiveMonitors;
1565}
1566
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001568 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001569 std::vector<InputTarget>& inputTargets,
1570 nsecs_t* nextWakeupTime,
1571 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001572 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 enum InjectionPermission {
1574 INJECTION_PERMISSION_UNKNOWN,
1575 INJECTION_PERMISSION_GRANTED,
1576 INJECTION_PERMISSION_DENIED
1577 };
1578
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 // For security reasons, we defer updating the touch state until we are sure that
1580 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001581 int32_t displayId = entry.displayId;
1582 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1584
1585 // Update the touch state as needed based on the properties of the touch event.
1586 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1587 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1588 sp<InputWindowHandle> newHoverWindowHandle;
1589
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001590 // Copy current touch state into tempTouchState.
1591 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1592 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001593 const TouchState* oldState = nullptr;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001594 TouchState tempTouchState;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001595 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1596 mTouchStatesByDisplay.find(displayId);
1597 if (oldStateIt != mTouchStatesByDisplay.end()) {
1598 oldState = &(oldStateIt->second);
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001599 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001600 }
1601
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001602 bool isSplit = tempTouchState.split;
1603 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1604 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1605 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001606 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1607 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1608 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1609 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1610 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001611 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 bool wrongDevice = false;
1613 if (newGesture) {
1614 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001615 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001616 ALOGI("Dropping event because a pointer for a different device is already down "
1617 "in display %" PRId32,
1618 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001619 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1621 switchedDevice = false;
1622 wrongDevice = true;
1623 goto Failed;
1624 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001625 tempTouchState.reset();
1626 tempTouchState.down = down;
1627 tempTouchState.deviceId = entry.deviceId;
1628 tempTouchState.source = entry.source;
1629 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001631 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001632 ALOGI("Dropping move event because a pointer for a different device is already active "
1633 "in display %" PRId32,
1634 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001635 // TODO: test multiple simultaneous input streams.
1636 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1637 switchedDevice = false;
1638 wrongDevice = true;
1639 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 }
1641
1642 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1643 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1644
Garfield Tan00f511d2019-06-12 16:55:40 -07001645 int32_t x;
1646 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001648 // Always dispatch mouse events to cursor position.
1649 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001650 x = int32_t(entry.xCursorPosition);
1651 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001652 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001653 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1654 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001655 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001656 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001657 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001658 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1659 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001660
1661 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001662 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001663 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001666 if (newTouchedWindowHandle != nullptr &&
1667 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001668 // New window supports splitting, but we should never split mouse events.
1669 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 } else if (isSplit) {
1671 // New window does not support splitting but we have already split events.
1672 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001673 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 }
1675
1676 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001677 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001679 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001680 }
1681
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001682 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1683 ALOGI("Not sending touch event to %s because it is paused",
1684 newTouchedWindowHandle->getName().c_str());
1685 newTouchedWindowHandle = nullptr;
1686 }
1687
1688 if (newTouchedWindowHandle != nullptr) {
1689 sp<Connection> connection = getConnectionLocked(newTouchedWindowHandle->getToken());
1690 if (connection == nullptr) {
1691 ALOGI("Could not find connection for %s",
1692 newTouchedWindowHandle->getName().c_str());
1693 newTouchedWindowHandle = nullptr;
1694 } else if (!connection->responsive) {
1695 // don't send the new touch to an unresponsive window
1696 ALOGW("Unresponsive window %s will not get the new gesture at %" PRIu64,
1697 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1698 newTouchedWindowHandle = nullptr;
1699 }
1700 }
1701
Vishnu Nair0f13fe52022-01-26 22:55:57 +00001702 // Drop touch events if requested by input feature
1703 if (newTouchedWindowHandle != nullptr && shouldDropInput(entry, newTouchedWindowHandle)) {
1704 newTouchedWindowHandle = nullptr;
1705 }
1706
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001707 // Also don't send the new touch event to unresponsive gesture monitors
1708 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1709
Michael Wright3dd60e22019-03-27 22:06:44 +00001710 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1711 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001712 "(%d, %d) in display %" PRId32 ".",
1713 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001714 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1715 goto Failed;
1716 }
1717
1718 if (newTouchedWindowHandle != nullptr) {
1719 // Set target flags.
1720 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1721 if (isSplit) {
1722 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001724 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1725 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1726 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1727 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1728 }
1729
1730 // Update hover state.
1731 if (isHoverAction) {
1732 newHoverWindowHandle = newTouchedWindowHandle;
1733 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1734 newHoverWindowHandle = mLastHoverWindowHandle;
1735 }
1736
1737 // Update the temporary touch state.
1738 BitSet32 pointerIds;
1739 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001740 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001741 pointerIds.markBit(pointerId);
1742 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001743 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 }
1745
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001746 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 } else {
1748 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1749
1750 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001751 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001752 if (DEBUG_FOCUS) {
1753 ALOGD("Dropping event because the pointer is not down or we previously "
1754 "dropped the pointer down event in display %" PRId32,
1755 displayId);
1756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1758 goto Failed;
1759 }
1760
1761 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001762 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001763 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001764 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1765 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766
1767 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001768 tempTouchState.getFirstForegroundWindowHandle();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001770 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Vishnu Nair0f13fe52022-01-26 22:55:57 +00001771
1772 // Drop touch events if requested by input feature
1773 if (newTouchedWindowHandle != nullptr &&
1774 shouldDropInput(entry, newTouchedWindowHandle)) {
1775 newTouchedWindowHandle = nullptr;
1776 }
1777
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001778 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1779 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001780 if (DEBUG_FOCUS) {
1781 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1782 oldTouchedWindowHandle->getName().c_str(),
1783 newTouchedWindowHandle->getName().c_str(), displayId);
1784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 // Make a slippery exit from the old window.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001786 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1787 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1788 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789
1790 // Make a slippery entrance into the new window.
1791 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1792 isSplit = true;
1793 }
1794
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001795 int32_t targetFlags =
1796 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 if (isSplit) {
1798 targetFlags |= InputTarget::FLAG_SPLIT;
1799 }
1800 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1801 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakoud8c6ef22020-12-09 08:07:46 -10001802 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1803 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804 }
1805
1806 BitSet32 pointerIds;
1807 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001808 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001810 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 }
1812 }
1813 }
1814
1815 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1816 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001817 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818#if DEBUG_HOVER
1819 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001820 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821#endif
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001822 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1823 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 }
1825
1826 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001827 if (newHoverWindowHandle != nullptr) {
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 Vishniakou1ea3cf12020-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 Vishniakou1ea3cf12020-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 Vishniakou1ea3cf12020-03-24 19:50:03 -07001852 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001853 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakoue0fb6bd2020-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 Vishniakou1ea3cf12020-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 Vishniakou1ea3cf12020-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 Vishniakou1ea3cf12020-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 Vishniakou1ea3cf12020-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 &&
1900 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
Siarhei Vishniakou1ea3cf12020-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 Vishniakou1ea3cf12020-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 Vishniakou1ea3cf12020-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 Vishniakou1ea3cf12020-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 Vishniakou7f0a4392020-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 Vishniakou7f0a4392020-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 Vishniakou7f0a4392020-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 Vishniakou1ea3cf12020-03-24 19:50:03 -07001962 tempTouchState.reset();
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001963 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1964 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001965 tempTouchState.deviceId = entry.deviceId;
1966 tempTouchState.source = entry.source;
1967 tempTouchState.displayId = displayId;
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001968 }
1969 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1970 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1971 // All pointers up or canceled.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001972 tempTouchState.reset();
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001973 } 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 Vishniakou1ea3cf12020-03-24 19:50:03 -07001987 for (size_t i = 0; i < tempTouchState.windows.size();) {
1988 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001989 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1990 touchedWindow.pointerIds.clearBit(pointerId);
1991 if (touchedWindow.pointerIds.isEmpty()) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001992 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001993 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995 }
Siarhei Vishniakou7f0a4392020-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 Vishniakou7f0a4392020-03-24 20:49:09 -07001999 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002000
Siarhei Vishniakou7f0a4392020-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) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07002004 if (tempTouchState.displayId >= 0) {
2005 mTouchStatesByDisplay[displayId] = tempTouchState;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07002006 } else {
2007 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010
Siarhei Vishniakou7f0a4392020-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 Carr9cada032020-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 Carr9cada032020-04-13 17:21:08 -07002113 return false;
Chris Ye39bc6112020-05-10 15:16:04 -07002114 } else if (otherInfo->trustedOverlay) {
Robert Carr9cada032020-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 Carr9cada032020-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 Carr9cada032020-04-13 17:21:08 -07002131 if (canBeObscuredBy(windowHandle, otherHandle) &&
2132 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 Carr9cada032020-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 }
2147
2148 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002149 if (canBeObscuredBy(windowHandle, otherHandle) &&
2150 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002151 return true;
2152 }
2153 }
2154 return false;
2155}
2156
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002157std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 const sp<InputApplicationHandle>& applicationHandle,
2159 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002160 if (applicationHandle != nullptr) {
2161 if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002162 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 } else {
2164 return applicationHandle->getName();
2165 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002166 } else if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002167 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002169 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 }
2171}
2172
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002173void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002174 if (eventEntry.type == EventEntry::Type::FOCUS) {
2175 // Focus events are passed to apps, but do not represent user activity.
2176 return;
2177 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002178 int32_t displayId = getTargetDisplayId(eventEntry);
2179 sp<InputWindowHandle> focusedWindowHandle =
2180 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2181 if (focusedWindowHandle != nullptr) {
2182 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2184#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002185 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186#endif
2187 return;
2188 }
2189 }
2190
2191 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002192 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002193 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002194 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2195 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002196 return;
2197 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002199 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002200 eventType = USER_ACTIVITY_EVENT_TOUCH;
2201 }
2202 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002204 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002205 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2206 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002207 return;
2208 }
2209 eventType = USER_ACTIVITY_EVENT_BUTTON;
2210 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002212 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002213 case EventEntry::Type::CONFIGURATION_CHANGED:
2214 case EventEntry::Type::DEVICE_RESET: {
2215 LOG_ALWAYS_FATAL("%s events are not user activity",
2216 EventEntry::typeToString(eventEntry.type));
2217 break;
2218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 }
2220
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002221 std::unique_ptr<CommandEntry> commandEntry =
2222 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002223 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002225 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226}
2227
2228void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002229 const sp<Connection>& connection,
2230 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002231 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002232 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002233 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002234 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002235 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002236 ATRACE_NAME(message.c_str());
2237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238#if DEBUG_DISPATCH_CYCLE
2239 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002240 "globalScaleFactor=%f, pointerIds=0x%x %s",
2241 connection->getInputChannelName().c_str(), inputTarget.flags,
2242 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2243 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244#endif
2245
2246 // Skip this event if the connection status is not normal.
2247 // We don't want to enqueue additional outbound events if the connection is broken.
2248 if (connection->status != Connection::STATUS_NORMAL) {
2249#if DEBUG_DISPATCH_CYCLE
2250 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002251 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252#endif
2253 return;
2254 }
2255
2256 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002257 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2258 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2259 "Entry type %s should not have FLAG_SPLIT",
2260 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002262 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002263 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002264 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002265 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 if (!splitMotionEntry) {
2267 return; // split event was dropped
2268 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002269 if (DEBUG_FOCUS) {
2270 ALOGD("channel '%s' ~ Split motion event.",
2271 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002272 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002273 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002274 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 splitMotionEntry->release();
2276 return;
2277 }
2278 }
2279
2280 // Not splitting. Enqueue dispatch entries for the event as is.
2281 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2282}
2283
2284void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002285 const sp<Connection>& connection,
2286 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002287 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002288 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002290 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002291 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002292 ATRACE_NAME(message.c_str());
2293 }
2294
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002295 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296
2297 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002298 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002299 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002300 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002301 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002302 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002303 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002304 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002305 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002306 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002307 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002308 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002309 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310
2311 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002312 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 startDispatchCycleLocked(currentTime, connection);
2314 }
2315}
2316
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002317void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2318 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002319 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002320 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002321 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002322 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2323 connection->getInputChannelName().c_str(),
2324 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002325 ATRACE_NAME(message.c_str());
2326 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002327 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 if (!(inputTargetFlags & dispatchMode)) {
2329 return;
2330 }
2331 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2332
2333 // This is a new event.
2334 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002335 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002336 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002338 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2339 // different EventEntry than what was passed in.
2340 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002342 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002343 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002344 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002345 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002346 dispatchEntry->resolvedAction = keyEntry.action;
2347 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002349 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2350 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002352 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2353 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002355 return; // skip the inconsistent event
2356 }
2357 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002360 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002361 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002362 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2363 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2364 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2365 static_cast<int32_t>(IdGenerator::Source::OTHER);
2366 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002367 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2368 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2369 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2370 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2371 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2372 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2373 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2374 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2375 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2376 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2377 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002378 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002379 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002380 }
2381 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002382 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2383 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002385 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2386 "event",
2387 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002389 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002392 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002393 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2394 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2395 }
2396 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2397 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002400 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2401 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002403 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2404 "event",
2405 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002407 return; // skip the inconsistent event
2408 }
2409
Garfield Tan1c7bc862020-01-28 13:24:04 -08002410 dispatchEntry->resolvedEventId =
2411 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2412 ? mIdGenerator.nextId()
2413 : motionEntry.id;
2414 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2415 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2416 ") to MotionEvent(id=0x%" PRIx32 ").",
2417 motionEntry.id, dispatchEntry->resolvedEventId);
2418 ATRACE_NAME(message.c_str());
2419 }
2420
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002421 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002422 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002423
2424 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002426 case EventEntry::Type::FOCUS: {
2427 break;
2428 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002429 case EventEntry::Type::CONFIGURATION_CHANGED:
2430 case EventEntry::Type::DEVICE_RESET: {
2431 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002432 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002433 break;
2434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435 }
2436
2437 // Remember that we are waiting for this dispatch to complete.
2438 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002439 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 }
2441
2442 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002443 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002444 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002445}
2446
chaviwfd6d3512019-03-25 13:23:49 -07002447void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002448 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002449 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002450 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2451 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002452 return;
2453 }
2454
2455 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2456 if (inputWindowHandle == nullptr) {
2457 return;
2458 }
2459
chaviw8c9cf542019-03-25 13:02:48 -07002460 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002461 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002462
2463 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2464
2465 if (!hasFocusChanged) {
2466 return;
2467 }
2468
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002469 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2470 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002471 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002472 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473}
2474
2475void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002476 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002477 if (ATRACE_ENABLED()) {
2478 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002479 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002480 ATRACE_NAME(message.c_str());
2481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002483 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484#endif
2485
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002486 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2487 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07002489 const nsecs_t timeout =
2490 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
2491 dispatchEntry->timeoutTime = currentTime + timeout;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492
2493 // Publish the event.
2494 status_t status;
2495 EventEntry* eventEntry = dispatchEntry->eventEntry;
2496 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002497 case EventEntry::Type::KEY: {
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002498 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2499 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002501 // Publish the key event.
Garfield Tan1c7bc862020-01-28 13:24:04 -08002502 status =
2503 connection->inputPublisher
2504 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2505 keyEntry->deviceId, keyEntry->source,
2506 keyEntry->displayId, std::move(hmac),
2507 dispatchEntry->resolvedAction,
2508 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2509 keyEntry->scanCode, keyEntry->metaState,
2510 keyEntry->repeatCount, keyEntry->downTime,
2511 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002512 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513 }
2514
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002515 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002516 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002518 PointerCoords scaledCoords[MAX_POINTERS];
2519 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2520
chaviw82357092020-01-28 13:13:06 -08002521 // Set the X and Y offset and X and Y scale depending on the input source.
2522 float xOffset = 0.0f, yOffset = 0.0f;
2523 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002524 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2525 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2526 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002527 xScale = dispatchEntry->windowXScale;
2528 yScale = dispatchEntry->windowYScale;
2529 xOffset = dispatchEntry->xOffset * xScale;
2530 yOffset = dispatchEntry->yOffset * yScale;
2531 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002532 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2533 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002534 // Don't apply window scale here since we don't want scale to affect raw
2535 // coordinates. The scale will be sent back to the client and applied
2536 // later when requesting relative coordinates.
2537 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2538 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002539 }
2540 usingCoords = scaledCoords;
2541 }
2542 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002543 // We don't want the dispatch target to know.
2544 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2545 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2546 scaledCoords[i].clear();
2547 }
2548 usingCoords = scaledCoords;
2549 }
2550 }
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002551
2552 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002553
2554 // Publish the motion event.
2555 status = connection->inputPublisher
Garfield Tan1c7bc862020-01-28 13:24:04 -08002556 .publishMotionEvent(dispatchEntry->seq,
2557 dispatchEntry->resolvedEventId,
2558 motionEntry->deviceId, motionEntry->source,
2559 motionEntry->displayId, std::move(hmac),
2560 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 motionEntry->actionButton,
2562 dispatchEntry->resolvedFlags,
2563 motionEntry->edgeFlags, motionEntry->metaState,
2564 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002565 motionEntry->classification, xScale, yScale,
2566 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002567 motionEntry->yPrecision,
2568 motionEntry->xCursorPosition,
2569 motionEntry->yCursorPosition,
2570 motionEntry->downTime, motionEntry->eventTime,
2571 motionEntry->pointerCount,
2572 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002573 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002574 break;
2575 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002576 case EventEntry::Type::FOCUS: {
2577 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2578 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tan1c7bc862020-01-28 13:24:04 -08002579 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002580 focusEntry->hasFocus,
2581 mInTouchMode);
2582 break;
2583 }
2584
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002585 case EventEntry::Type::CONFIGURATION_CHANGED:
2586 case EventEntry::Type::DEVICE_RESET: {
2587 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2588 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002589 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591 }
2592
2593 // Check the result.
2594 if (status) {
2595 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002596 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002598 "This is unexpected because the wait queue is empty, so the pipe "
2599 "should be empty and we shouldn't have any problems writing an "
2600 "event to it, status=%d",
2601 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2603 } else {
2604 // Pipe is full and we are waiting for the app to finish process some events
2605 // before sending more events to it.
2606#if DEBUG_DISPATCH_CYCLE
2607 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002608 "waiting for the application to catch up",
2609 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002611 }
2612 } else {
2613 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002614 "status=%d",
2615 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2617 }
2618 return;
2619 }
2620
2621 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002622 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2623 connection->outboundQueue.end(),
2624 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002625 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002626 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07002627 if (connection->responsive) {
2628 mAnrTracker.insert(dispatchEntry->timeoutTime,
2629 connection->inputChannel->getConnectionToken());
2630 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002631 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632 }
2633}
2634
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002635const std::array<uint8_t, 32> InputDispatcher::getSignature(
2636 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2637 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2638 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2639 // Only sign events up and down events as the purely move events
2640 // are tied to their up/down counterparts so signing would be redundant.
2641 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2642 verifiedEvent.actionMasked = actionMasked;
2643 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2644 return mHmacKeyManager.sign(verifiedEvent);
2645 }
2646 return INVALID_HMAC;
2647}
2648
2649const std::array<uint8_t, 32> InputDispatcher::getSignature(
2650 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2651 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2652 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2653 verifiedEvent.action = dispatchEntry.resolvedAction;
2654 return mHmacKeyManager.sign(verifiedEvent);
2655}
2656
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002658 const sp<Connection>& connection, uint32_t seq,
2659 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660#if DEBUG_DISPATCH_CYCLE
2661 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002662 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663#endif
2664
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002665 if (connection->status == Connection::STATUS_BROKEN ||
2666 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667 return;
2668 }
2669
2670 // Notify other system components and prepare to start the next dispatch cycle.
2671 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2672}
2673
2674void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002675 const sp<Connection>& connection,
2676 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677#if DEBUG_DISPATCH_CYCLE
2678 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002679 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680#endif
2681
2682 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002683 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002684 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002685 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002686 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687
2688 // The connection appears to be unrecoverably broken.
2689 // Ignore already broken or zombie connections.
2690 if (connection->status == Connection::STATUS_NORMAL) {
2691 connection->status = Connection::STATUS_BROKEN;
2692
2693 if (notify) {
2694 // Notify other system components.
2695 onDispatchCycleBrokenLocked(currentTime, connection);
2696 }
2697 }
2698}
2699
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002700void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2701 while (!queue.empty()) {
2702 DispatchEntry* dispatchEntry = queue.front();
2703 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002704 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705 }
2706}
2707
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002708void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002710 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 }
2712 delete dispatchEntry;
2713}
2714
2715int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2716 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2717
2718 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002719 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002721 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002723 "fd=%d, events=0x%x",
2724 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725 return 0; // remove the callback
2726 }
2727
2728 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002729 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2731 if (!(events & ALOOPER_EVENT_INPUT)) {
2732 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002733 "events=0x%x",
2734 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735 return 1;
2736 }
2737
2738 nsecs_t currentTime = now();
2739 bool gotOne = false;
2740 status_t status;
2741 for (;;) {
2742 uint32_t seq;
2743 bool handled;
2744 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2745 if (status) {
2746 break;
2747 }
2748 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2749 gotOne = true;
2750 }
2751 if (gotOne) {
2752 d->runCommandsLockedInterruptible();
2753 if (status == WOULD_BLOCK) {
2754 return 1;
2755 }
2756 }
2757
2758 notify = status != DEAD_OBJECT || !connection->monitor;
2759 if (notify) {
2760 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002761 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 }
2763 } else {
2764 // Monitor channels are never explicitly unregistered.
2765 // We do it automatically when the remote endpoint is closed so don't warn
2766 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002767 const bool stillHaveWindowHandle =
2768 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2769 nullptr;
2770 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771 if (notify) {
2772 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 "events=0x%x",
2774 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775 }
2776 }
2777
2778 // Unregister the channel.
2779 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2780 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002781 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782}
2783
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002784void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002786 for (const auto& pair : mConnectionsByFd) {
2787 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 }
2789}
2790
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002791void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002792 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002793 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2794 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2795}
2796
2797void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2798 const CancelationOptions& options,
2799 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2800 for (const auto& it : monitorsByDisplay) {
2801 const std::vector<Monitor>& monitors = it.second;
2802 for (const Monitor& monitor : monitors) {
2803 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002804 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002805 }
2806}
2807
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2809 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002810 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002811 if (connection == nullptr) {
2812 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002814
2815 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816}
2817
2818void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2819 const sp<Connection>& connection, const CancelationOptions& options) {
2820 if (connection->status == Connection::STATUS_BROKEN) {
2821 return;
2822 }
2823
2824 nsecs_t currentTime = now();
2825
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002826 std::vector<EventEntry*> cancelationEvents =
2827 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002829 if (cancelationEvents.empty()) {
2830 return;
2831 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002833 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2834 "with reality: %s, mode=%d.",
2835 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2836 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002838
2839 InputTarget target;
2840 sp<InputWindowHandle> windowHandle =
2841 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2842 if (windowHandle != nullptr) {
2843 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2844 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2845 windowInfo->windowXScale, windowInfo->windowYScale);
2846 target.globalScaleFactor = windowInfo->globalScaleFactor;
2847 }
2848 target.inputChannel = connection->inputChannel;
2849 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2850
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002851 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2852 EventEntry* cancelationEventEntry = cancelationEvents[i];
2853 switch (cancelationEventEntry->type) {
2854 case EventEntry::Type::KEY: {
2855 logOutboundKeyDetails("cancel - ",
2856 static_cast<const KeyEntry&>(*cancelationEventEntry));
2857 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002859 case EventEntry::Type::MOTION: {
2860 logOutboundMotionDetails("cancel - ",
2861 static_cast<const MotionEntry&>(*cancelationEventEntry));
2862 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002864 case EventEntry::Type::FOCUS: {
2865 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2866 break;
2867 }
2868 case EventEntry::Type::CONFIGURATION_CHANGED:
2869 case EventEntry::Type::DEVICE_RESET: {
2870 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2871 EventEntry::typeToString(cancelationEventEntry->type));
2872 break;
2873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874 }
2875
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002876 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2877 target, InputTarget::FLAG_DISPATCH_AS_IS);
2878
2879 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002881
2882 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883}
2884
Svet Ganov5d3bc372020-01-26 23:11:07 -08002885void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2886 const sp<Connection>& connection) {
2887 if (connection->status == Connection::STATUS_BROKEN) {
2888 return;
2889 }
2890
2891 nsecs_t currentTime = now();
2892
2893 std::vector<EventEntry*> downEvents =
2894 connection->inputState.synthesizePointerDownEvents(currentTime);
2895
2896 if (downEvents.empty()) {
2897 return;
2898 }
2899
2900#if DEBUG_OUTBOUND_EVENT_DETAILS
2901 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2902 connection->getInputChannelName().c_str(), downEvents.size());
2903#endif
2904
2905 InputTarget target;
2906 sp<InputWindowHandle> windowHandle =
2907 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2908 if (windowHandle != nullptr) {
2909 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2910 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2911 windowInfo->windowXScale, windowInfo->windowYScale);
2912 target.globalScaleFactor = windowInfo->globalScaleFactor;
2913 }
2914 target.inputChannel = connection->inputChannel;
2915 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2916
2917 for (EventEntry* downEventEntry : downEvents) {
2918 switch (downEventEntry->type) {
2919 case EventEntry::Type::MOTION: {
2920 logOutboundMotionDetails("down - ",
2921 static_cast<const MotionEntry&>(*downEventEntry));
2922 break;
2923 }
2924
2925 case EventEntry::Type::KEY:
2926 case EventEntry::Type::FOCUS:
2927 case EventEntry::Type::CONFIGURATION_CHANGED:
2928 case EventEntry::Type::DEVICE_RESET: {
2929 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2930 EventEntry::typeToString(downEventEntry->type));
2931 break;
2932 }
2933 }
2934
2935 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2936 target, InputTarget::FLAG_DISPATCH_AS_IS);
2937
2938 downEventEntry->release();
2939 }
2940
2941 startDispatchCycleLocked(currentTime, connection);
2942}
2943
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002944MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002945 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946 ALOG_ASSERT(pointerIds.value != 0);
2947
2948 uint32_t splitPointerIndexMap[MAX_POINTERS];
2949 PointerProperties splitPointerProperties[MAX_POINTERS];
2950 PointerCoords splitPointerCoords[MAX_POINTERS];
2951
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002952 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002953 uint32_t splitPointerCount = 0;
2954
2955 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002956 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002958 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002959 uint32_t pointerId = uint32_t(pointerProperties.id);
2960 if (pointerIds.hasBit(pointerId)) {
2961 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2962 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2963 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002964 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965 splitPointerCount += 1;
2966 }
2967 }
2968
2969 if (splitPointerCount != pointerIds.count()) {
2970 // This is bad. We are missing some of the pointers that we expected to deliver.
2971 // Most likely this indicates that we received an ACTION_MOVE events that has
2972 // different pointer ids than we expected based on the previous ACTION_DOWN
2973 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2974 // in this way.
2975 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002976 "we expected there to be %d pointers. This probably means we received "
2977 "a broken sequence of pointer ids from the input device.",
2978 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002979 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980 }
2981
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002982 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002983 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002984 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2985 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2987 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002988 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002989 uint32_t pointerId = uint32_t(pointerProperties.id);
2990 if (pointerIds.hasBit(pointerId)) {
2991 if (pointerIds.count() == 1) {
2992 // The first/last pointer went down/up.
2993 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002994 ? AMOTION_EVENT_ACTION_DOWN
2995 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002996 } else {
2997 // A secondary pointer went down/up.
2998 uint32_t splitPointerIndex = 0;
2999 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3000 splitPointerIndex += 1;
3001 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003002 action = maskedAction |
3003 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004 }
3005 } else {
3006 // An unrelated pointer changed.
3007 action = AMOTION_EVENT_ACTION_MOVE;
3008 }
3009 }
3010
Garfield Tan1c7bc862020-01-28 13:24:04 -08003011 int32_t newId = mIdGenerator.nextId();
3012 if (ATRACE_ENABLED()) {
3013 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3014 ") to MotionEvent(id=0x%" PRIx32 ").",
3015 originalMotionEntry.id, newId);
3016 ATRACE_NAME(message.c_str());
3017 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003018 MotionEntry* splitMotionEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08003019 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3020 originalMotionEntry.source, originalMotionEntry.displayId,
3021 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003022 originalMotionEntry.actionButton, originalMotionEntry.flags,
3023 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3024 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3025 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3026 originalMotionEntry.xCursorPosition,
3027 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003028 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003030 if (originalMotionEntry.injectionState) {
3031 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003032 splitMotionEntry->injectionState->refCount += 1;
3033 }
3034
3035 return splitMotionEntry;
3036}
3037
3038void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3039#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003040 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041#endif
3042
3043 bool needWake;
3044 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003045 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046
Prabir Pradhan42611e02018-11-27 14:04:02 -08003047 ConfigurationChangedEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003048 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049 needWake = enqueueInboundEventLocked(newEntry);
3050 } // release lock
3051
3052 if (needWake) {
3053 mLooper->wake();
3054 }
3055}
3056
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003057/**
3058 * If one of the meta shortcuts is detected, process them here:
3059 * Meta + Backspace -> generate BACK
3060 * Meta + Enter -> generate HOME
3061 * This will potentially overwrite keyCode and metaState.
3062 */
3063void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003064 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003065 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3066 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3067 if (keyCode == AKEYCODE_DEL) {
3068 newKeyCode = AKEYCODE_BACK;
3069 } else if (keyCode == AKEYCODE_ENTER) {
3070 newKeyCode = AKEYCODE_HOME;
3071 }
3072 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003073 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003074 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003075 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003076 keyCode = newKeyCode;
3077 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3078 }
3079 } else if (action == AKEY_EVENT_ACTION_UP) {
3080 // In order to maintain a consistent stream of up and down events, check to see if the key
3081 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3082 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003083 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003084 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003085 auto replacementIt = mReplacedKeys.find(replacement);
3086 if (replacementIt != mReplacedKeys.end()) {
3087 keyCode = replacementIt->second;
3088 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003089 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3090 }
3091 }
3092}
3093
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3095#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003096 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3097 "policyFlags=0x%x, action=0x%x, "
3098 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3099 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3100 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3101 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102#endif
3103 if (!validateKeyEvent(args->action)) {
3104 return;
3105 }
3106
3107 uint32_t policyFlags = args->policyFlags;
3108 int32_t flags = args->flags;
3109 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003110 // InputDispatcher tracks and generates key repeats on behalf of
3111 // whatever notifies it, so repeatCount should always be set to 0
3112 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3114 policyFlags |= POLICY_FLAG_VIRTUAL;
3115 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 if (policyFlags & POLICY_FLAG_FUNCTION) {
3118 metaState |= AMETA_FUNCTION_ON;
3119 }
3120
3121 policyFlags |= POLICY_FLAG_TRUSTED;
3122
Michael Wright78f24442014-08-06 15:55:28 -07003123 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003124 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003125
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003127 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08003128 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3129 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130
Michael Wright2b3c3302018-03-02 17:19:13 +00003131 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003133 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3134 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003137
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 bool needWake;
3139 { // acquire lock
3140 mLock.lock();
3141
3142 if (shouldSendKeyToInputFilterLocked(args)) {
3143 mLock.unlock();
3144
3145 policyFlags |= POLICY_FLAG_FILTERED;
3146 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3147 return; // event was consumed by the filter
3148 }
3149
3150 mLock.lock();
3151 }
3152
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003153 KeyEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003154 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003155 args->displayId, policyFlags, args->action, flags, keyCode,
3156 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157
3158 needWake = enqueueInboundEventLocked(newEntry);
3159 mLock.unlock();
3160 } // release lock
3161
3162 if (needWake) {
3163 mLooper->wake();
3164 }
3165}
3166
3167bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3168 return mInputFilterEnabled;
3169}
3170
3171void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3172#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003173 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3174 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003175 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3176 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003177 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003178 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3179 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3180 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3181 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 for (uint32_t i = 0; i < args->pointerCount; i++) {
3183 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 "x=%f, y=%f, pressure=%f, size=%f, "
3185 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3186 "orientation=%f",
3187 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3188 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3189 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3190 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3191 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3192 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3193 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3194 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3195 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3196 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 }
3198#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003199 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3200 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 return;
3202 }
3203
3204 uint32_t policyFlags = args->policyFlags;
3205 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003206
3207 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003208 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003209 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3210 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003211 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003212 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213
3214 bool needWake;
3215 { // acquire lock
3216 mLock.lock();
3217
3218 if (shouldSendMotionToInputFilterLocked(args)) {
3219 mLock.unlock();
3220
3221 MotionEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003222 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3223 args->action, args->actionButton, args->flags, args->edgeFlags,
3224 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3225 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3226 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3227 args->downTime, args->eventTime, args->pointerCount,
3228 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229
3230 policyFlags |= POLICY_FLAG_FILTERED;
3231 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3232 return; // event was consumed by the filter
3233 }
3234
3235 mLock.lock();
3236 }
3237
3238 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003239 MotionEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003240 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003241 args->displayId, policyFlags, args->action, args->actionButton,
3242 args->flags, args->metaState, args->buttonState,
3243 args->classification, args->edgeFlags, args->xPrecision,
3244 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3245 args->downTime, args->pointerCount, args->pointerProperties,
3246 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247
3248 needWake = enqueueInboundEventLocked(newEntry);
3249 mLock.unlock();
3250 } // release lock
3251
3252 if (needWake) {
3253 mLooper->wake();
3254 }
3255}
3256
3257bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003258 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259}
3260
3261void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3262#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003263 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003264 "switchMask=0x%08x",
3265 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266#endif
3267
3268 uint32_t policyFlags = args->policyFlags;
3269 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003270 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271}
3272
3273void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3274#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003275 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3276 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277#endif
3278
3279 bool needWake;
3280 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003281 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282
Prabir Pradhan42611e02018-11-27 14:04:02 -08003283 DeviceResetEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003284 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285 needWake = enqueueInboundEventLocked(newEntry);
3286 } // release lock
3287
3288 if (needWake) {
3289 mLooper->wake();
3290 }
3291}
3292
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003293int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3294 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003295 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296#if DEBUG_INBOUND_EVENT_DETAILS
3297 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003298 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3299 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300#endif
3301
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003302 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303
3304 policyFlags |= POLICY_FLAG_INJECTED;
3305 if (hasInjectionPermission(injectorPid, injectorUid)) {
3306 policyFlags |= POLICY_FLAG_TRUSTED;
3307 }
3308
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003309 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003311 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003312 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3313 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003314 if (!validateKeyEvent(action)) {
3315 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003318 int32_t flags = incomingKey.getFlags();
3319 int32_t keyCode = incomingKey.getKeyCode();
3320 int32_t metaState = incomingKey.getMetaState();
3321 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003323 KeyEvent keyEvent;
Garfield Tanfbe732e2020-01-24 11:26:14 -08003324 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003325 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3326 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3327 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3330 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003331 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003332
3333 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3334 android::base::Timer t;
3335 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3336 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3337 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3338 std::to_string(t.duration().count()).c_str());
3339 }
3340 }
3341
3342 mLock.lock();
3343 KeyEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003344 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3345 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003346 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3347 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tanfbe732e2020-01-24 11:26:14 -08003348 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003349 injectedEntries.push(injectedEntry);
3350 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351 }
3352
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003353 case AINPUT_EVENT_TYPE_MOTION: {
3354 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3355 int32_t action = motionEvent->getAction();
3356 size_t pointerCount = motionEvent->getPointerCount();
3357 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3358 int32_t actionButton = motionEvent->getActionButton();
3359 int32_t displayId = motionEvent->getDisplayId();
3360 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3361 return INPUT_EVENT_INJECTION_FAILED;
3362 }
3363
3364 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3365 nsecs_t eventTime = motionEvent->getEventTime();
3366 android::base::Timer t;
3367 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3368 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3369 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3370 std::to_string(t.duration().count()).c_str());
3371 }
3372 }
3373
3374 mLock.lock();
3375 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3376 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3377 MotionEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003378 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3379 motionEvent->getSource(), motionEvent->getDisplayId(),
3380 policyFlags, action, actionButton, motionEvent->getFlags(),
3381 motionEvent->getMetaState(), motionEvent->getButtonState(),
3382 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3383 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003384 motionEvent->getRawXCursorPosition(),
3385 motionEvent->getRawYCursorPosition(),
3386 motionEvent->getDownTime(), uint32_t(pointerCount),
3387 pointerProperties, samplePointerCoords,
3388 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003389 injectedEntries.push(injectedEntry);
3390 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3391 sampleEventTimes += 1;
3392 samplePointerCoords += pointerCount;
3393 MotionEntry* nextInjectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003394 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003395 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003396 motionEvent->getDisplayId(), policyFlags, action,
3397 actionButton, motionEvent->getFlags(),
3398 motionEvent->getMetaState(), motionEvent->getButtonState(),
3399 motionEvent->getClassification(),
3400 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3401 motionEvent->getYPrecision(),
3402 motionEvent->getRawXCursorPosition(),
3403 motionEvent->getRawYCursorPosition(),
3404 motionEvent->getDownTime(), uint32_t(pointerCount),
3405 pointerProperties, samplePointerCoords,
3406 motionEvent->getXOffset(), motionEvent->getYOffset());
3407 injectedEntries.push(nextInjectedEntry);
3408 }
3409 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003412 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003413 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003414 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 }
3416
3417 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3418 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3419 injectionState->injectionIsAsync = true;
3420 }
3421
3422 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003423 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424
3425 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003426 while (!injectedEntries.empty()) {
3427 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3428 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429 }
3430
3431 mLock.unlock();
3432
3433 if (needWake) {
3434 mLooper->wake();
3435 }
3436
3437 int32_t injectionResult;
3438 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003439 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440
3441 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3442 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3443 } else {
3444 for (;;) {
3445 injectionResult = injectionState->injectionResult;
3446 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3447 break;
3448 }
3449
3450 nsecs_t remainingTimeout = endTime - now();
3451 if (remainingTimeout <= 0) {
3452#if DEBUG_INJECTION
3453 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003454 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455#endif
3456 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3457 break;
3458 }
3459
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003460 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461 }
3462
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003463 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3464 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465 while (injectionState->pendingForegroundDispatches != 0) {
3466#if DEBUG_INJECTION
3467 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003468 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469#endif
3470 nsecs_t remainingTimeout = endTime - now();
3471 if (remainingTimeout <= 0) {
3472#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003473 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3474 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475#endif
3476 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3477 break;
3478 }
3479
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003480 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481 }
3482 }
3483 }
3484
3485 injectionState->release();
3486 } // release lock
3487
3488#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003489 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003490 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491#endif
3492
3493 return injectionResult;
3494}
3495
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003496std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003497 std::array<uint8_t, 32> calculatedHmac;
3498 std::unique_ptr<VerifiedInputEvent> result;
3499 switch (event.getType()) {
3500 case AINPUT_EVENT_TYPE_KEY: {
3501 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3502 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3503 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3504 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3505 break;
3506 }
3507 case AINPUT_EVENT_TYPE_MOTION: {
3508 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3509 VerifiedMotionEvent verifiedMotionEvent =
3510 verifiedMotionEventFromMotionEvent(motionEvent);
3511 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3512 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3513 break;
3514 }
3515 default: {
3516 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3517 return nullptr;
3518 }
3519 }
3520 if (calculatedHmac == INVALID_HMAC) {
3521 return nullptr;
3522 }
3523 if (calculatedHmac != event.getHmac()) {
3524 return nullptr;
3525 }
3526 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003527}
3528
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003530 return injectorUid == 0 ||
3531 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532}
3533
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003534void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 InjectionState* injectionState = entry->injectionState;
3536 if (injectionState) {
3537#if DEBUG_INJECTION
3538 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003539 "injectorPid=%d, injectorUid=%d",
3540 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003541#endif
3542
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003543 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544 // Log the outcome since the injector did not wait for the injection result.
3545 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003546 case INPUT_EVENT_INJECTION_SUCCEEDED:
3547 ALOGV("Asynchronous input event injection succeeded.");
3548 break;
3549 case INPUT_EVENT_INJECTION_FAILED:
3550 ALOGW("Asynchronous input event injection failed.");
3551 break;
3552 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3553 ALOGW("Asynchronous input event injection permission denied.");
3554 break;
3555 case INPUT_EVENT_INJECTION_TIMED_OUT:
3556 ALOGW("Asynchronous input event injection timed out.");
3557 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 }
3559 }
3560
3561 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003562 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563 }
3564}
3565
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003566void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 InjectionState* injectionState = entry->injectionState;
3568 if (injectionState) {
3569 injectionState->pendingForegroundDispatches += 1;
3570 }
3571}
3572
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003573void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574 InjectionState* injectionState = entry->injectionState;
3575 if (injectionState) {
3576 injectionState->pendingForegroundDispatches -= 1;
3577
3578 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003579 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 }
3581 }
3582}
3583
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003584std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3585 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003586 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003587}
3588
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003590 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003591 if (windowHandleToken == nullptr) {
3592 return nullptr;
3593 }
3594
Arthur Hungb92218b2018-08-14 12:00:21 +08003595 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003596 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3597 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003598 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003599 return windowHandle;
3600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601 }
3602 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003603 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604}
3605
Mady Mellor017bcd12020-06-23 19:12:00 +00003606bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3607 for (auto& it : mWindowHandlesByDisplay) {
3608 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3609 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003610 if (handle->getId() == windowHandle->getId() &&
3611 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003612 if (windowHandle->getInfo()->displayId != it.first) {
3613 ALOGE("Found window %s in display %" PRId32
3614 ", but it should belong to display %" PRId32,
3615 windowHandle->getName().c_str(), it.first,
3616 windowHandle->getInfo()->displayId);
3617 }
3618 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 }
3621 }
3622 return false;
3623}
3624
Robert Carr5c8a0262018-10-03 16:30:44 -07003625sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3626 size_t count = mInputChannelsByToken.count(token);
3627 if (count == 0) {
3628 return nullptr;
3629 }
3630 return mInputChannelsByToken.at(token);
3631}
3632
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003633void InputDispatcher::updateWindowHandlesForDisplayLocked(
3634 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3635 if (inputWindowHandles.empty()) {
3636 // Remove all handles on a display if there are no windows left.
3637 mWindowHandlesByDisplay.erase(displayId);
3638 return;
3639 }
3640
3641 // Since we compare the pointer of input window handles across window updates, we need
3642 // to make sure the handle object for the same window stays unchanged across updates.
3643 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003644 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003645 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003646 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003647 }
3648
3649 std::vector<sp<InputWindowHandle>> newHandles;
3650 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3651 if (!handle->updateInfo()) {
3652 // handle no longer valid
3653 continue;
3654 }
3655
3656 const InputWindowInfo* info = handle->getInfo();
3657 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3658 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3659 const bool noInputChannel =
3660 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3661 const bool canReceiveInput =
3662 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3663 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3664 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003665 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003666 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003667 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003668 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003669 }
3670
3671 if (info->displayId != displayId) {
3672 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3673 handle->getName().c_str(), displayId, info->displayId);
3674 continue;
3675 }
3676
Robert Carredd13602020-04-13 17:24:34 -07003677 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3678 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003679 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003680 oldHandle->updateFrom(handle);
3681 newHandles.push_back(oldHandle);
3682 } else {
3683 newHandles.push_back(handle);
3684 }
3685 }
3686
3687 // Insert or replace
3688 mWindowHandlesByDisplay[displayId] = newHandles;
3689}
3690
Arthur Hung72d8dc32020-03-28 00:48:39 +00003691void InputDispatcher::setInputWindows(
3692 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3693 { // acquire lock
3694 std::scoped_lock _l(mLock);
3695 for (auto const& i : handlesPerDisplay) {
3696 setInputWindowsLocked(i.second, i.first);
3697 }
3698 }
3699 // Wake up poll loop since it may need to make new input dispatching choices.
3700 mLooper->wake();
3701}
3702
Arthur Hungb92218b2018-08-14 12:00:21 +08003703/**
3704 * Called from InputManagerService, update window handle list by displayId that can receive input.
3705 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3706 * If set an empty list, remove all handles from the specific display.
3707 * For focused handle, check if need to change and send a cancel event to previous one.
3708 * For removed handle, check if need to send a cancel event if already in touch.
3709 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003710void InputDispatcher::setInputWindowsLocked(
3711 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003712 if (DEBUG_FOCUS) {
3713 std::string windowList;
3714 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3715 windowList += iwh->getName() + " ";
3716 }
3717 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719
Arthur Hung72d8dc32020-03-28 00:48:39 +00003720 // Copy old handles for release if they are no longer present.
3721 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722
Arthur Hung72d8dc32020-03-28 00:48:39 +00003723 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003724
Arthur Hung72d8dc32020-03-28 00:48:39 +00003725 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3726 bool foundHoveredWindow = false;
3727 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3728 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3729 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3730 windowHandle->getInfo()->visible) {
3731 newFocusedWindowHandle = windowHandle;
3732 }
3733 if (windowHandle == mLastHoverWindowHandle) {
3734 foundHoveredWindow = true;
3735 }
3736 }
3737
3738 if (!foundHoveredWindow) {
3739 mLastHoverWindowHandle = nullptr;
3740 }
3741
3742 sp<InputWindowHandle> oldFocusedWindowHandle =
3743 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3744
3745 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3746 if (oldFocusedWindowHandle != nullptr) {
3747 if (DEBUG_FOCUS) {
3748 ALOGD("Focus left window: %s in display %" PRId32,
3749 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003750 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003751 sp<InputChannel> focusedInputChannel =
3752 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3753 if (focusedInputChannel != nullptr) {
3754 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3755 "focus left window");
3756 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3757 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003758 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003759 mFocusedWindowHandlesByDisplay.erase(displayId);
3760 }
3761 if (newFocusedWindowHandle != nullptr) {
3762 if (DEBUG_FOCUS) {
3763 ALOGD("Focus entered window: %s in display %" PRId32,
3764 newFocusedWindowHandle->getName().c_str(), displayId);
3765 }
3766 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3767 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768 }
3769
Arthur Hung72d8dc32020-03-28 00:48:39 +00003770 if (mFocusedDisplayId == displayId) {
3771 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003775 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3776 mTouchStatesByDisplay.find(displayId);
3777 if (stateIt != mTouchStatesByDisplay.end()) {
3778 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003779 for (size_t i = 0; i < state.windows.size();) {
3780 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003781 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003782 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003783 ALOGD("Touched window was removed: %s in display %" PRId32,
3784 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003785 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003786 sp<InputChannel> touchedInputChannel =
3787 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3788 if (touchedInputChannel != nullptr) {
3789 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3790 "touched window was removed");
3791 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003793 state.windows.erase(state.windows.begin() + i);
3794 } else {
3795 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 }
3797 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003798 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003799
Arthur Hung72d8dc32020-03-28 00:48:39 +00003800 // Release information for windows that are no longer present.
3801 // This ensures that unused input channels are released promptly.
3802 // Otherwise, they might stick around until the window handle is destroyed
3803 // which might not happen until the next GC.
3804 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003805 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003806 if (DEBUG_FOCUS) {
3807 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003808 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003809 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003810 }
chaviw291d88a2019-02-14 10:33:58 -08003811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812}
3813
3814void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003815 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003816 if (DEBUG_FOCUS) {
3817 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3818 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003821 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822
Tiger Huang721e26f2018-07-24 22:26:19 +08003823 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3824 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07003825
3826 if (oldFocusedApplicationHandle == mAwaitedFocusedApplication &&
3827 inputApplicationHandle != oldFocusedApplicationHandle) {
3828 resetNoFocusedWindowTimeoutLocked();
3829 }
3830
Yi Kong9b14ac62018-07-17 13:48:38 -07003831 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003832 if (oldFocusedApplicationHandle != inputApplicationHandle) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003833 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003835 } else if (oldFocusedApplicationHandle != nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003836 oldFocusedApplicationHandle.clear();
3837 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 } // release lock
3840
3841 // Wake up poll loop since it may need to make new input dispatching choices.
3842 mLooper->wake();
3843}
3844
Tiger Huang721e26f2018-07-24 22:26:19 +08003845/**
3846 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3847 * the display not specified.
3848 *
3849 * We track any unreleased events for each window. If a window loses the ability to receive the
3850 * released event, we will send a cancel event to it. So when the focused display is changed, we
3851 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3852 * display. The display-specified events won't be affected.
3853 */
3854void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003855 if (DEBUG_FOCUS) {
3856 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3857 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003858 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003859 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003860
3861 if (mFocusedDisplayId != displayId) {
3862 sp<InputWindowHandle> oldFocusedWindowHandle =
3863 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3864 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003865 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003866 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003867 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003868 CancelationOptions
3869 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3870 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003871 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003872 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3873 }
3874 }
3875 mFocusedDisplayId = displayId;
3876
3877 // Sanity check
3878 sp<InputWindowHandle> newFocusedWindowHandle =
3879 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003880 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003881
Tiger Huang721e26f2018-07-24 22:26:19 +08003882 if (newFocusedWindowHandle == nullptr) {
3883 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3884 if (!mFocusedWindowHandlesByDisplay.empty()) {
3885 ALOGE("But another display has a focused window:");
3886 for (auto& it : mFocusedWindowHandlesByDisplay) {
3887 const int32_t displayId = it.first;
3888 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003889 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3890 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003891 }
3892 }
3893 }
3894 }
3895
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003896 if (DEBUG_FOCUS) {
3897 logDispatchStateLocked();
3898 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003899 } // release lock
3900
3901 // Wake up poll loop since it may need to make new input dispatching choices.
3902 mLooper->wake();
3903}
3904
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003906 if (DEBUG_FOCUS) {
3907 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909
3910 bool changed;
3911 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003912 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913
3914 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3915 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07003916 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 }
3918
3919 if (mDispatchEnabled && !enabled) {
3920 resetAndDropEverythingLocked("dispatcher is being disabled");
3921 }
3922
3923 mDispatchEnabled = enabled;
3924 mDispatchFrozen = frozen;
3925 changed = true;
3926 } else {
3927 changed = false;
3928 }
3929
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003930 if (DEBUG_FOCUS) {
3931 logDispatchStateLocked();
3932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933 } // release lock
3934
3935 if (changed) {
3936 // Wake up poll loop since it may need to make new input dispatching choices.
3937 mLooper->wake();
3938 }
3939}
3940
3941void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003942 if (DEBUG_FOCUS) {
3943 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3944 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945
3946 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003947 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948
3949 if (mInputFilterEnabled == enabled) {
3950 return;
3951 }
3952
3953 mInputFilterEnabled = enabled;
3954 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3955 } // release lock
3956
3957 // Wake up poll loop since there might be work to do to drop everything.
3958 mLooper->wake();
3959}
3960
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003961void InputDispatcher::setInTouchMode(bool inTouchMode) {
3962 std::scoped_lock lock(mLock);
3963 mInTouchMode = inTouchMode;
3964}
3965
chaviwfbe5d9c2018-12-26 12:23:37 -08003966bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3967 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003968 if (DEBUG_FOCUS) {
3969 ALOGD("Trivial transfer to same window.");
3970 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003971 return true;
3972 }
3973
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003975 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976
chaviwfbe5d9c2018-12-26 12:23:37 -08003977 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3978 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003979 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003980 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 return false;
3982 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003983 if (DEBUG_FOCUS) {
3984 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3985 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3986 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003988 if (DEBUG_FOCUS) {
3989 ALOGD("Cannot transfer focus because windows are on different displays.");
3990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 return false;
3992 }
3993
3994 bool found = false;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003995 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
3996 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003997 for (size_t i = 0; i < state.windows.size(); i++) {
3998 const TouchedWindow& touchedWindow = state.windows[i];
3999 if (touchedWindow.windowHandle == fromWindowHandle) {
4000 int32_t oldTargetFlags = touchedWindow.targetFlags;
4001 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004003 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004005 int32_t newTargetFlags = oldTargetFlags &
4006 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4007 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004008 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009
Jeff Brownf086ddb2014-02-11 14:28:48 -08004010 found = true;
4011 goto Found;
4012 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013 }
4014 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004015 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004017 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004018 if (DEBUG_FOCUS) {
4019 ALOGD("Focus transfer failed because from window did not have focus.");
4020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 return false;
4022 }
4023
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004024 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4025 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004026 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004027 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004028 CancelationOptions
4029 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4030 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004032 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033 }
4034
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004035 if (DEBUG_FOCUS) {
4036 logDispatchStateLocked();
4037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038 } // release lock
4039
4040 // Wake up poll loop since it may need to make new input dispatching choices.
4041 mLooper->wake();
4042 return true;
4043}
4044
4045void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004046 if (DEBUG_FOCUS) {
4047 ALOGD("Resetting and dropping all events (%s).", reason);
4048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049
4050 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4051 synthesizeCancelationEventsForAllConnectionsLocked(options);
4052
4053 resetKeyRepeatLocked();
4054 releasePendingEventLocked();
4055 drainInboundQueueLocked();
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004056 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004058 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004059 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004061 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062}
4063
4064void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004065 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066 dumpDispatchStateLocked(dump);
4067
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004068 std::istringstream stream(dump);
4069 std::string line;
4070
4071 while (std::getline(stream, line, '\n')) {
4072 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073 }
4074}
4075
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004076void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004077 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4078 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4079 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004080 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081
Tiger Huang721e26f2018-07-24 22:26:19 +08004082 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4083 dump += StringPrintf(INDENT "FocusedApplications:\n");
4084 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4085 const int32_t displayId = it.first;
4086 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004087 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004088 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004089 displayId, applicationHandle->getName().c_str(),
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004090 ns2ms(applicationHandle
4091 ->getDispatchingTimeout(
4092 DEFAULT_INPUT_DISPATCHING_TIMEOUT)
4093 .count()));
Tiger Huang721e26f2018-07-24 22:26:19 +08004094 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004096 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004098
4099 if (!mFocusedWindowHandlesByDisplay.empty()) {
4100 dump += StringPrintf(INDENT "FocusedWindows:\n");
4101 for (auto& it : mFocusedWindowHandlesByDisplay) {
4102 const int32_t displayId = it.first;
4103 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004104 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4105 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004106 }
4107 } else {
4108 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004111 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004112 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004113 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4114 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004115 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004116 state.displayId, toString(state.down), toString(state.split),
4117 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004118 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004119 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004120 for (size_t i = 0; i < state.windows.size(); i++) {
4121 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004122 dump += StringPrintf(INDENT4
4123 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4124 i, touchedWindow.windowHandle->getName().c_str(),
4125 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004126 }
4127 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004128 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004129 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004130 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004131 dump += INDENT3 "Portal windows:\n";
4132 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004133 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004134 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4135 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004136 }
4137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 }
4139 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004140 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 }
4142
Arthur Hungb92218b2018-08-14 12:00:21 +08004143 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004144 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004145 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004146 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004147 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004148 dump += INDENT2 "Windows:\n";
4149 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004150 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004151 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152
Arthur Hungb92218b2018-08-14 12:00:21 +08004153 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004154 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004155 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4156 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004157 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004158 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004159 i, windowInfo->name.c_str(), windowInfo->displayId,
4160 windowInfo->portalToDisplayId,
4161 toString(windowInfo->paused),
4162 toString(windowInfo->hasFocus),
4163 toString(windowInfo->hasWallpaper),
4164 toString(windowInfo->visible),
4165 toString(windowInfo->canReceiveKeys),
4166 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004167 windowInfo->layoutParamsType, windowInfo->frameLeft,
4168 windowInfo->frameTop, windowInfo->frameRight,
4169 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4170 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004171 dumpRegion(dump, windowInfo->touchableRegion);
4172 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004173 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4174 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004175 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004176 ns2ms(windowInfo->dispatchingTimeout));
Arthur Hungb92218b2018-08-14 12:00:21 +08004177 }
4178 } else {
4179 dump += INDENT2 "Windows: <none>\n";
4180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 }
4182 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004183 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 }
4185
Michael Wright3dd60e22019-03-27 22:06:44 +00004186 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004187 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004188 const std::vector<Monitor>& monitors = it.second;
4189 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4190 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004191 }
4192 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004193 const std::vector<Monitor>& monitors = it.second;
4194 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4195 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004198 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 }
4200
4201 nsecs_t currentTime = now();
4202
4203 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004204 if (!mRecentQueue.empty()) {
4205 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4206 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004207 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004209 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 }
4211 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004212 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 }
4214
4215 // Dump event currently being dispatched.
4216 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004217 dump += INDENT "PendingEvent:\n";
4218 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004220 dump += StringPrintf(", age=%" PRId64 "ms\n",
4221 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004223 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224 }
4225
4226 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004227 if (!mInboundQueue.empty()) {
4228 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4229 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004230 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004232 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 }
4234 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004235 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 }
4237
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004238 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004239 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004240 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4241 const KeyReplacement& replacement = pair.first;
4242 int32_t newKeyCode = pair.second;
4243 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004244 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004245 }
4246 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004247 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004248 }
4249
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004250 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004251 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004252 for (const auto& pair : mConnectionsByFd) {
4253 const sp<Connection>& connection = pair.second;
4254 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004255 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004256 pair.first, connection->getInputChannelName().c_str(),
4257 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004258 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004260 if (!connection->outboundQueue.empty()) {
4261 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4262 connection->outboundQueue.size());
4263 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 dump.append(INDENT4);
4265 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004266 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4267 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004269 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 }
4271 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004272 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 }
4274
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004275 if (!connection->waitQueue.empty()) {
4276 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4277 connection->waitQueue.size());
4278 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004279 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004281 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004282 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004283 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004284 ns2ms(currentTime - entry->eventEntry->eventTime),
4285 ns2ms(currentTime - entry->deliveryTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 }
4287 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004288 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 }
4290 }
4291 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004292 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293 }
4294
4295 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004296 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4297 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004299 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 }
4301
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004302 dump += INDENT "Configuration:\n";
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004303 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4304 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4305 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306}
4307
Michael Wright3dd60e22019-03-27 22:06:44 +00004308void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4309 const size_t numMonitors = monitors.size();
4310 for (size_t i = 0; i < numMonitors; i++) {
4311 const Monitor& monitor = monitors[i];
4312 const sp<InputChannel>& channel = monitor.inputChannel;
4313 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4314 dump += "\n";
4315 }
4316}
4317
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004318status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004320 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321#endif
4322
4323 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004324 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004325 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004326 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004328 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 return BAD_VALUE;
4330 }
4331
Garfield Tan1c7bc862020-01-28 13:24:04 -08004332 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333
4334 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004335 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004336 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4339 } // release lock
4340
4341 // Wake the looper because some connections have changed.
4342 mLooper->wake();
4343 return OK;
4344}
4345
Michael Wright3dd60e22019-03-27 22:06:44 +00004346status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004347 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004348 { // acquire lock
4349 std::scoped_lock _l(mLock);
4350
4351 if (displayId < 0) {
4352 ALOGW("Attempted to register input monitor without a specified display.");
4353 return BAD_VALUE;
4354 }
4355
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004356 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004357 ALOGW("Attempted to register input monitor without an identifying token.");
4358 return BAD_VALUE;
4359 }
4360
Garfield Tan1c7bc862020-01-28 13:24:04 -08004361 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004362
4363 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004364 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004365 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004366
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004367 auto& monitorsByDisplay =
4368 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004369 monitorsByDisplay[displayId].emplace_back(inputChannel);
4370
4371 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004372 }
4373 // Wake the looper because some connections have changed.
4374 mLooper->wake();
4375 return OK;
4376}
4377
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4379#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004380 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381#endif
4382
4383 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004384 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385
4386 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4387 if (status) {
4388 return status;
4389 }
4390 } // release lock
4391
4392 // Wake the poll loop because removing the connection may have changed the current
4393 // synchronization state.
4394 mLooper->wake();
4395 return OK;
4396}
4397
4398status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004399 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004400 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004401 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004403 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 return BAD_VALUE;
4405 }
4406
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004407 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004408 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004409
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 if (connection->monitor) {
4411 removeMonitorChannelLocked(inputChannel);
4412 }
4413
4414 mLooper->removeFd(inputChannel->getFd());
4415
4416 nsecs_t currentTime = now();
4417 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4418
4419 connection->status = Connection::STATUS_ZOMBIE;
4420 return OK;
4421}
4422
4423void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004424 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4425 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4426}
4427
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004428void InputDispatcher::removeMonitorChannelLocked(
4429 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004430 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004431 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004432 std::vector<Monitor>& monitors = it->second;
4433 const size_t numMonitors = monitors.size();
4434 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004435 if (monitors[i].inputChannel == inputChannel) {
4436 monitors.erase(monitors.begin() + i);
4437 break;
4438 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004439 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004440 if (monitors.empty()) {
4441 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004442 } else {
4443 ++it;
4444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 }
4446}
4447
Michael Wright3dd60e22019-03-27 22:06:44 +00004448status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4449 { // acquire lock
4450 std::scoped_lock _l(mLock);
4451 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4452
4453 if (!foundDisplayId) {
4454 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4455 return BAD_VALUE;
4456 }
4457 int32_t displayId = foundDisplayId.value();
4458
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004459 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4460 mTouchStatesByDisplay.find(displayId);
4461 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004462 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4463 return BAD_VALUE;
4464 }
4465
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004466 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004467 std::optional<int32_t> foundDeviceId;
4468 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004469 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004470 foundDeviceId = state.deviceId;
4471 }
4472 }
4473 if (!foundDeviceId || !state.down) {
4474 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004475 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004476 return BAD_VALUE;
4477 }
4478 int32_t deviceId = foundDeviceId.value();
4479
4480 // Send cancel events to all the input channels we're stealing from.
4481 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004482 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004483 options.deviceId = deviceId;
4484 options.displayId = displayId;
4485 for (const TouchedWindow& window : state.windows) {
4486 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004487 if (channel != nullptr) {
4488 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4489 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004490 }
4491 // Then clear the current touch state so we stop dispatching to them as well.
4492 state.filterNonMonitors();
4493 }
4494 return OK;
4495}
4496
Michael Wright3dd60e22019-03-27 22:06:44 +00004497std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4498 const sp<IBinder>& token) {
4499 for (const auto& it : mGestureMonitorsByDisplay) {
4500 const std::vector<Monitor>& monitors = it.second;
4501 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004502 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004503 return it.first;
4504 }
4505 }
4506 }
4507 return std::nullopt;
4508}
4509
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004510sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004511 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004512 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004513 }
4514
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004515 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004516 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004517 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004518 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 }
4520 }
Robert Carr4e670e52018-08-15 13:26:12 -07004521
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004522 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523}
4524
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004525void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004526 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004527 removeByValue(mConnectionsByFd, connection);
4528}
4529
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004530void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4531 const sp<Connection>& connection, uint32_t seq,
4532 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004533 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4534 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535 commandEntry->connection = connection;
4536 commandEntry->eventTime = currentTime;
4537 commandEntry->seq = seq;
4538 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004539 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540}
4541
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004542void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4543 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004545 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004547 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4548 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004550 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551}
4552
chaviw0c06c6e2019-01-09 13:27:07 -08004553void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004554 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004555 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4556 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004557 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4558 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004559 commandEntry->oldToken = oldToken;
4560 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004561 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004562}
4563
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004564void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4565 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4566 // is already healthy again. Don't raise ANR in this situation
4567 if (connection->waitQueue.empty()) {
4568 ALOGI("Not raising ANR because the connection %s has recovered",
4569 connection->inputChannel->getName().c_str());
4570 return;
4571 }
4572 /**
4573 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4574 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4575 * has changed. This could cause newer entries to time out before the already dispatched
4576 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4577 * processes the events linearly. So providing information about the oldest entry seems to be
4578 * most useful.
4579 */
4580 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4581 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4582 std::string reason =
4583 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4584 connection->inputChannel->getName().c_str(),
4585 ns2ms(currentWait),
4586 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004588 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4589 reason);
4590
4591 std::unique_ptr<CommandEntry> commandEntry =
4592 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4593 commandEntry->inputApplicationHandle = nullptr;
4594 commandEntry->inputChannel = connection->inputChannel;
4595 commandEntry->reason = std::move(reason);
4596 postCommandLocked(std::move(commandEntry));
4597}
4598
4599void InputDispatcher::onAnrLocked(const sp<InputApplicationHandle>& application) {
4600 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4601 application->getName().c_str());
4602
4603 updateLastAnrStateLocked(application, reason);
4604
4605 std::unique_ptr<CommandEntry> commandEntry =
4606 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4607 commandEntry->inputApplicationHandle = application;
4608 commandEntry->inputChannel = nullptr;
4609 commandEntry->reason = std::move(reason);
4610 postCommandLocked(std::move(commandEntry));
4611}
4612
4613void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4614 const std::string& reason) {
4615 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4616 updateLastAnrStateLocked(windowLabel, reason);
4617}
4618
4619void InputDispatcher::updateLastAnrStateLocked(const sp<InputApplicationHandle>& application,
4620 const std::string& reason) {
4621 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4622 updateLastAnrStateLocked(windowLabel, reason);
4623}
4624
4625void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4626 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004628 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629 struct tm tm;
4630 localtime_r(&t, &tm);
4631 char timestr[64];
4632 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004633 mLastAnrState.clear();
4634 mLastAnrState += INDENT "ANR:\n";
4635 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004636 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4637 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004638 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639}
4640
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004641void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004642 mLock.unlock();
4643
4644 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4645
4646 mLock.lock();
4647}
4648
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004649void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 sp<Connection> connection = commandEntry->connection;
4651
4652 if (connection->status != Connection::STATUS_ZOMBIE) {
4653 mLock.unlock();
4654
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004655 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656
4657 mLock.lock();
4658 }
4659}
4660
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004661void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004662 sp<IBinder> oldToken = commandEntry->oldToken;
4663 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004664 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004665 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004666 mLock.lock();
4667}
4668
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004669void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004670 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004671 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004672 mLock.unlock();
4673
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004674 const nsecs_t timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004675 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004676
4677 mLock.lock();
4678
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004679 if (timeoutExtension > 0) {
4680 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4681 } else {
4682 // stop waking up for events in this connection, it is already not responding
4683 sp<Connection> connection = getConnectionLocked(token);
4684 if (connection == nullptr) {
4685 return;
4686 }
4687 cancelEventsForAnrLocked(connection);
4688 }
4689}
4690
4691void InputDispatcher::extendAnrTimeoutsLocked(const sp<InputApplicationHandle>& application,
4692 const sp<IBinder>& connectionToken,
4693 nsecs_t timeoutExtension) {
4694 sp<Connection> connection = getConnectionLocked(connectionToken);
4695 if (connection == nullptr) {
4696 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4697 // Maybe ANR happened because there's no focused window?
4698 mNoFocusedWindowTimeoutTime = now() + timeoutExtension;
4699 mAwaitedFocusedApplication = application;
4700 } else {
4701 // It's also possible that the connection already disappeared. No action necessary.
4702 }
4703 return;
4704 }
4705
4706 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
4707 connection->inputChannel->getName().c_str(), ns2ms(timeoutExtension));
4708
4709 connection->responsive = true;
4710 const nsecs_t newTimeout = now() + timeoutExtension;
4711 for (DispatchEntry* entry : connection->waitQueue) {
4712 if (newTimeout >= entry->timeoutTime) {
4713 // Already removed old entries when connection was marked unresponsive
4714 entry->timeoutTime = newTimeout;
4715 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4716 }
4717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718}
4719
4720void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4721 CommandEntry* commandEntry) {
4722 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004723 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724
4725 mLock.unlock();
4726
Michael Wright2b3c3302018-03-02 17:19:13 +00004727 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004728 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004729 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004730 : nullptr;
4731 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004732 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4733 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004734 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004735 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736
4737 mLock.lock();
4738
4739 if (delay < 0) {
4740 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4741 } else if (!delay) {
4742 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4743 } else {
4744 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4745 entry->interceptKeyWakeupTime = now() + delay;
4746 }
4747 entry->release();
4748}
4749
chaviwfd6d3512019-03-25 13:23:49 -07004750void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4751 mLock.unlock();
4752 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4753 mLock.lock();
4754}
4755
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004756/**
4757 * Connection is responsive if it has no events in the waitQueue that are older than the
4758 * current time.
4759 */
4760static bool isConnectionResponsive(const Connection& connection) {
4761 const nsecs_t currentTime = now();
4762 for (const DispatchEntry* entry : connection.waitQueue) {
4763 if (entry->timeoutTime < currentTime) {
4764 return false;
4765 }
4766 }
4767 return true;
4768}
4769
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004770void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004772 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004774 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775
4776 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004777 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004778 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004779 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004781 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004782 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004783 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004784 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4785 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004786 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004787 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004788
4789 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004790 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004791 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4792 restartEvent =
4793 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004794 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004795 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4796 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4797 handled);
4798 } else {
4799 restartEvent = false;
4800 }
4801
4802 // Dequeue the event and start the next cycle.
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004803 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004804 // contents of the wait queue to have been drained, so we need to double-check
4805 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004806 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4807 if (dispatchEntryIt != connection->waitQueue.end()) {
4808 dispatchEntry = *dispatchEntryIt;
4809 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004810 mAnrTracker.erase(dispatchEntry->timeoutTime,
4811 connection->inputChannel->getConnectionToken());
4812 if (!connection->responsive) {
4813 connection->responsive = isConnectionResponsive(*connection);
4814 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004815 traceWaitQueueLength(connection);
4816 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004817 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004818 traceOutboundQueueLength(connection);
4819 } else {
4820 releaseDispatchEntry(dispatchEntry);
4821 }
4822 }
4823
4824 // Start the next dispatch cycle for this connection.
4825 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826}
4827
4828bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004829 DispatchEntry* dispatchEntry,
4830 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004831 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004832 if (!handled) {
4833 // Report the key as unhandled, since the fallback was not handled.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004834 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004835 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004836 return false;
4837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004839 // Get the fallback key state.
4840 // Clear it out after dispatching the UP.
4841 int32_t originalKeyCode = keyEntry->keyCode;
4842 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4843 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4844 connection->inputState.removeFallbackKey(originalKeyCode);
4845 }
4846
4847 if (handled || !dispatchEntry->hasForegroundTarget()) {
4848 // If the application handles the original key for which we previously
4849 // generated a fallback or if the window is not a foreground window,
4850 // then cancel the associated fallback key, if any.
4851 if (fallbackKeyCode != -1) {
4852 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004854 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004855 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4856 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4857 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004859 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004860 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861
4862 mLock.unlock();
4863
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004864 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004865 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866
4867 mLock.lock();
4868
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004869 // Cancel the fallback key.
4870 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004872 "application handled the original non-fallback key "
4873 "or is no longer a foreground target, "
4874 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 options.keyCode = fallbackKeyCode;
4876 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004878 connection->inputState.removeFallbackKey(originalKeyCode);
4879 }
4880 } else {
4881 // If the application did not handle a non-fallback key, first check
4882 // that we are in a good state to perform unhandled key event processing
4883 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004884 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004885 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004887 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004888 "since this is not an initial down. "
4889 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4890 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004892 return false;
4893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004895 // Dispatch the unhandled key to the policy.
4896#if DEBUG_OUTBOUND_EVENT_DETAILS
4897 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004898 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4899 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004900#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004901 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004902
4903 mLock.unlock();
4904
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004905 bool fallback =
4906 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4907 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004908
4909 mLock.lock();
4910
4911 if (connection->status != Connection::STATUS_NORMAL) {
4912 connection->inputState.removeFallbackKey(originalKeyCode);
4913 return false;
4914 }
4915
4916 // Latch the fallback keycode for this key on an initial down.
4917 // The fallback keycode cannot change at any other point in the lifecycle.
4918 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004920 fallbackKeyCode = event.getKeyCode();
4921 } else {
4922 fallbackKeyCode = AKEYCODE_UNKNOWN;
4923 }
4924 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4925 }
4926
4927 ALOG_ASSERT(fallbackKeyCode != -1);
4928
4929 // Cancel the fallback key if the policy decides not to send it anymore.
4930 // We will continue to dispatch the key to the policy but we will no
4931 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004932 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4933 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004934#if DEBUG_OUTBOUND_EVENT_DETAILS
4935 if (fallback) {
4936 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004937 "as a fallback for %d, but on the DOWN it had requested "
4938 "to send %d instead. Fallback canceled.",
4939 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004940 } else {
4941 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004942 "but on the DOWN it had requested to send %d. "
4943 "Fallback canceled.",
4944 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004945 }
4946#endif
4947
4948 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4949 "canceling fallback, policy no longer desires it");
4950 options.keyCode = fallbackKeyCode;
4951 synthesizeCancelationEventsForConnectionLocked(connection, options);
4952
4953 fallback = false;
4954 fallbackKeyCode = AKEYCODE_UNKNOWN;
4955 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004956 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004957 }
4958 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959
4960#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004961 {
4962 std::string msg;
4963 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4964 connection->inputState.getFallbackKeys();
4965 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004966 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004968 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004969 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004970 }
4971#endif
4972
4973 if (fallback) {
4974 // Restart the dispatch cycle using the fallback key.
4975 keyEntry->eventTime = event.getEventTime();
4976 keyEntry->deviceId = event.getDeviceId();
4977 keyEntry->source = event.getSource();
4978 keyEntry->displayId = event.getDisplayId();
4979 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4980 keyEntry->keyCode = fallbackKeyCode;
4981 keyEntry->scanCode = event.getScanCode();
4982 keyEntry->metaState = event.getMetaState();
4983 keyEntry->repeatCount = event.getRepeatCount();
4984 keyEntry->downTime = event.getDownTime();
4985 keyEntry->syntheticRepeat = false;
4986
4987#if DEBUG_OUTBOUND_EVENT_DETAILS
4988 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004989 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4990 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004991#endif
4992 return true; // restart the event
4993 } else {
4994#if DEBUG_OUTBOUND_EVENT_DETAILS
4995 ALOGD("Unhandled key event: No fallback key.");
4996#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004997
4998 // Report the key as unhandled, since there is no fallback key.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004999 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005000 }
5001 }
5002 return false;
5003}
5004
5005bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005006 DispatchEntry* dispatchEntry,
5007 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008 return false;
5009}
5010
5011void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5012 mLock.unlock();
5013
5014 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5015
5016 mLock.lock();
5017}
5018
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005019KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5020 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08005021 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08005022 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5023 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005024 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005025}
5026
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07005027void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5028 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029 // TODO Write some statistics about how long we spend waiting.
5030}
5031
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005032/**
5033 * Report the touch event latency to the statsd server.
5034 * Input events are reported for statistics if:
5035 * - This is a touchscreen event
5036 * - InputFilter is not enabled
5037 * - Event is not injected or synthesized
5038 *
5039 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5040 * from getting aggregated with the "old" data.
5041 */
5042void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5043 REQUIRES(mLock) {
5044 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5045 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5046 if (!reportForStatistics) {
5047 return;
5048 }
5049
5050 if (mTouchStatistics.shouldReport()) {
5051 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5052 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5053 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5054 mTouchStatistics.reset();
5055 }
5056 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5057 mTouchStatistics.addValue(latencyMicros);
5058}
5059
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060void InputDispatcher::traceInboundQueueLengthLocked() {
5061 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005062 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005063 }
5064}
5065
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005066void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005067 if (ATRACE_ENABLED()) {
5068 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005069 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005070 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005071 }
5072}
5073
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005074void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075 if (ATRACE_ENABLED()) {
5076 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005077 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005078 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079 }
5080}
5081
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005082void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005083 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005084
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005085 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 dumpDispatchStateLocked(dump);
5087
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005088 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005089 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005090 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091 }
5092}
5093
5094void InputDispatcher::monitor() {
5095 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005096 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005097 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005098 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099}
5100
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005101/**
5102 * Wake up the dispatcher and wait until it processes all events and commands.
5103 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5104 * this method can be safely called from any thread, as long as you've ensured that
5105 * the work you are interested in completing has already been queued.
5106 */
5107bool InputDispatcher::waitForIdle() {
5108 /**
5109 * Timeout should represent the longest possible time that a device might spend processing
5110 * events and commands.
5111 */
5112 constexpr std::chrono::duration TIMEOUT = 100ms;
5113 std::unique_lock lock(mLock);
5114 mLooper->wake();
5115 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5116 return result == std::cv_status::no_timeout;
5117}
5118
Vishnu Nair0f13fe52022-01-26 22:55:57 +00005119bool InputDispatcher::shouldDropInput(const EventEntry& entry,
5120 const sp<InputWindowHandle>& windowHandle) const {
5121 if (windowHandle->getInfo()->inputFeatures & InputWindowInfo::INPUT_FEATURE_DROP_INPUT) {
5122 ALOGW("Dropping %s event targeting %s as requested by inputFeatures=0x%08x on display "
5123 "%" PRId32 ".",
5124 EventEntry::typeToString(entry.type), windowHandle->getName().c_str(),
5125 windowHandle->getInfo()->inputFeatures, windowHandle->getInfo()->displayId);
5126 return true;
5127 }
5128 return false;
5129}
5130
Garfield Tane84e6f92019-08-29 17:28:41 -07005131} // namespace android::inputdispatcher