blob: 25170606137a23b4c04b0c550dc70020a716a65c [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/**
Siarhei Vishniakou265ab012020-09-08 19:43:33 -0500485 * Raise ANR if there is no focused window.
486 * Before the ANR is raised, do a final state check:
487 * 1. The currently focused application must be the same one we are waiting for.
488 * 2. Ensure we still don't have a focused window.
489 */
490void InputDispatcher::processNoFocusedWindowAnrLocked() {
491 // Check if the application that we are waiting for is still focused.
492 sp<InputApplicationHandle> focusedApplication =
493 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
494 if (focusedApplication == nullptr ||
495 focusedApplication->getApplicationToken() !=
496 mAwaitedFocusedApplication->getApplicationToken()) {
497 // Unexpected because we should have reset the ANR timer when focused application changed
498 ALOGE("Waited for a focused window, but focused application has already changed to %s",
499 focusedApplication->getName().c_str());
500 return; // The focused application has changed.
501 }
502
503 const sp<InputWindowHandle>& focusedWindowHandle =
504 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
505 if (focusedWindowHandle != nullptr) {
506 return; // We now have a focused window. No need for ANR.
507 }
508 onAnrLocked(mAwaitedFocusedApplication);
509}
510
511/**
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700512 * Check if any of the connections' wait queues have events that are too old.
513 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
514 * Return the time at which we should wake up next.
515 */
516nsecs_t InputDispatcher::processAnrsLocked() {
517 const nsecs_t currentTime = now();
518 nsecs_t nextAnrCheck = LONG_LONG_MAX;
519 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
520 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
521 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakou265ab012020-09-08 19:43:33 -0500522 processNoFocusedWindowAnrLocked();
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700523 mAwaitedFocusedApplication.clear();
Siarhei Vishniakou265ab012020-09-08 19:43:33 -0500524 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700525 return LONG_LONG_MIN;
526 } else {
527 // Keep waiting
528 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
529 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
530 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
531 }
532 }
533
534 // Check if any connection ANRs are due
535 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
536 if (currentTime < nextAnrCheck) { // most likely scenario
537 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
538 }
539
540 // If we reached here, we have an unresponsive connection.
541 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
542 if (connection == nullptr) {
543 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
544 return nextAnrCheck;
545 }
546 connection->responsive = false;
547 // Stop waking up for this unresponsive connection
548 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4e219792020-09-22 21:43:09 -0500549 onAnrLocked(*connection);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700550 return LONG_LONG_MIN;
551}
552
553nsecs_t InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
554 sp<InputWindowHandle> window = getWindowHandleLocked(token);
555 if (window != nullptr) {
556 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT).count();
557 }
558 return DEFAULT_INPUT_DISPATCHING_TIMEOUT.count();
559}
560
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
562 nsecs_t currentTime = now();
563
Jeff Browndc5992e2014-04-11 01:27:26 -0700564 // Reset the key repeat timer whenever normal dispatch is suspended while the
565 // device is in a non-interactive state. This is to ensure that we abort a key
566 // repeat if the device is just coming out of sleep.
567 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800568 resetKeyRepeatLocked();
569 }
570
571 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
572 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100573 if (DEBUG_FOCUS) {
574 ALOGD("Dispatch frozen. Waiting some more.");
575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576 return;
577 }
578
579 // Optimize latency of app switches.
580 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
581 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
582 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
583 if (mAppSwitchDueTime < *nextWakeupTime) {
584 *nextWakeupTime = mAppSwitchDueTime;
585 }
586
587 // Ready to start a new event.
588 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700589 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700590 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800591 if (isAppSwitchDue) {
592 // The inbound queue is empty so the app switch key we were waiting
593 // for will never arrive. Stop waiting for it.
594 resetPendingAppSwitchLocked(false);
595 isAppSwitchDue = false;
596 }
597
598 // Synthesize a key repeat if appropriate.
599 if (mKeyRepeatState.lastKeyEntry) {
600 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
601 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
602 } else {
603 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
604 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
605 }
606 }
607 }
608
609 // Nothing to do if there is no pending event.
610 if (!mPendingEvent) {
611 return;
612 }
613 } else {
614 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700615 mPendingEvent = mInboundQueue.front();
616 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 traceInboundQueueLengthLocked();
618 }
619
620 // Poke user activity for this event.
621 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700622 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 }
625
626 // Now we have an event to dispatch.
627 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700628 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700630 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700632 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700634 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800635 }
636
637 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700638 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 }
640
641 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700642 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700643 ConfigurationChangedEntry* typedEntry =
644 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
645 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700646 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700647 break;
648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700650 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700651 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
652 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700653 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700654 break;
655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100657 case EventEntry::Type::FOCUS: {
658 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
659 dispatchFocusLocked(currentTime, typedEntry);
660 done = true;
661 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
662 break;
663 }
664
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700665 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700666 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
667 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700668 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700669 resetPendingAppSwitchLocked(true);
670 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700671 } else if (dropReason == DropReason::NOT_DROPPED) {
672 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700673 }
674 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700675 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700676 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700677 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700678 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
679 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 }
681 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
682 break;
683 }
684
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700685 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700686 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700687 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
688 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700690 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700691 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700692 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700693 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
694 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700695 }
696 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
697 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699 }
700
701 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700702 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700703 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 }
Michael Wright3a981722015-06-10 15:26:13 +0100705 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706
707 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700708 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800709 }
710}
711
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700712/**
713 * Return true if the events preceding this incoming motion event should be dropped
714 * Return false otherwise (the default behaviour)
715 */
716bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700717 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700718 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700719
720 // Optimize case where the current application is unresponsive and the user
721 // decides to touch a window in a different application.
722 // If the application takes too long to catch up then we drop all events preceding
723 // the touch into the other window.
724 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700725 int32_t displayId = motionEntry.displayId;
726 int32_t x = static_cast<int32_t>(
727 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
728 int32_t y = static_cast<int32_t>(
729 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700730 sp<InputWindowHandle> touchedWindowHandle =
731 findTouchedWindowAtLocked(displayId, x, y, nullptr);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700732 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700733 touchedWindowHandle->getApplicationToken() !=
734 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700735 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700736 ALOGI("Pruning input queue because user touched a different application while waiting "
737 "for %s",
738 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700739 return true;
740 }
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700741
742 // Alternatively, maybe there's a gesture monitor that could handle this event
743 std::vector<TouchedMonitor> gestureMonitors =
744 findTouchedGestureMonitorsLocked(displayId, {});
745 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
746 sp<Connection> connection =
747 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000748 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700749 // This monitor could take more input. Drop all events preceding this
750 // event, so that gesture monitor could get a chance to receive the stream
751 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
752 "responsive gesture monitor that may handle the event",
753 mAwaitedFocusedApplication->getName().c_str());
754 return true;
755 }
756 }
757 }
758
759 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
760 // yet been processed by some connections, the dispatcher will wait for these motion
761 // events to be processed before dispatching the key event. This is because these motion events
762 // may cause a new window to be launched, which the user might expect to receive focus.
763 // To prevent waiting forever for such events, just send the key to the currently focused window
764 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
765 ALOGD("Received a new pointer down event, stop waiting for events to process and "
766 "just send the pending key event to the focused window.");
767 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700768 }
769 return false;
770}
771
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700773 bool needWake = mInboundQueue.empty();
774 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775 traceInboundQueueLengthLocked();
776
777 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700778 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700779 // Optimize app switch latency.
780 // If the application takes too long to catch up then we drop all events preceding
781 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700782 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700783 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700784 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700785 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700786 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700787 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700789 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700791 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700792 mAppSwitchSawKeyDown = false;
793 needWake = true;
794 }
795 }
796 }
797 break;
798 }
799
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700800 case EventEntry::Type::MOTION: {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700801 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
802 mNextUnblockedEvent = entry;
803 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100807 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700808 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
809 break;
810 }
811 case EventEntry::Type::CONFIGURATION_CHANGED:
812 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700813 // nothing to do
814 break;
815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816 }
817
818 return needWake;
819}
820
821void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
822 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700823 mRecentQueue.push_back(entry);
824 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
825 mRecentQueue.front()->release();
826 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 }
828}
829
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700830sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700831 int32_t y, TouchState* touchState,
832 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700833 bool addPortalWindows) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700834 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
835 LOG_ALWAYS_FATAL(
836 "Must provide a valid touch state if adding portal windows or outside targets");
837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800839 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
840 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 const InputWindowInfo* windowInfo = windowHandle->getInfo();
842 if (windowInfo->displayId == displayId) {
843 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844
845 if (windowInfo->visible) {
846 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700847 bool isTouchModal = (flags &
848 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
849 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800851 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700852 if (portalToDisplayId != ADISPLAY_ID_NONE &&
853 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800854 if (addPortalWindows) {
855 // For the monitoring channels of the display.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700856 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800857 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700858 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700859 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800860 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 // Found window.
862 return windowHandle;
863 }
864 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800865
866 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700867 touchState->addOrUpdateWindow(windowHandle,
868 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
869 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872 }
873 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700874 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875}
876
Garfield Tane84e6f92019-08-29 17:28:41 -0700877std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -0700878 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000879 std::vector<TouchedMonitor> touchedMonitors;
880
881 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
882 addGestureMonitors(monitors, touchedMonitors);
883 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
884 const InputWindowInfo* windowInfo = portalWindow->getInfo();
885 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700886 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
887 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000888 }
889 return touchedMonitors;
890}
891
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700892void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 const char* reason;
894 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700895 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700897 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 reason = "inbound event was dropped because the policy consumed it";
900 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700901 case DropReason::DISABLED:
902 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 ALOGI("Dropped event because input dispatch is disabled.");
904 }
905 reason = "inbound event was dropped because input dispatch is disabled";
906 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700907 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700908 ALOGI("Dropped event because of pending overdue app switch.");
909 reason = "inbound event was dropped because of pending overdue app switch";
910 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700911 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700912 ALOGI("Dropped event because the current application is not responding and the user "
913 "has started interacting with a different application.");
914 reason = "inbound event was dropped because the current application is not responding "
915 "and the user has started interacting with a different application";
916 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700917 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700918 ALOGI("Dropped event because it is stale.");
919 reason = "inbound event was dropped because it is stale";
920 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700921 case DropReason::NOT_DROPPED: {
922 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700923 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 }
926
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700927 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700928 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
930 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700931 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700933 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700934 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
935 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700936 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
937 synthesizeCancelationEventsForAllConnectionsLocked(options);
938 } else {
939 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
940 synthesizeCancelationEventsForAllConnectionsLocked(options);
941 }
942 break;
943 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100944 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700945 case EventEntry::Type::CONFIGURATION_CHANGED:
946 case EventEntry::Type::DEVICE_RESET: {
947 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
948 break;
949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950 }
951}
952
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800953static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700954 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
955 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956}
957
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700958bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
959 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
960 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
961 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962}
963
964bool InputDispatcher::isAppSwitchPendingLocked() {
965 return mAppSwitchDueTime != LONG_LONG_MAX;
966}
967
968void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
969 mAppSwitchDueTime = LONG_LONG_MAX;
970
971#if DEBUG_APP_SWITCH
972 if (handled) {
973 ALOGD("App switch has arrived.");
974 } else {
975 ALOGD("App switch was abandoned.");
976 }
977#endif
978}
979
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700981 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982}
983
984bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700985 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 return false;
987 }
988
989 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700990 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700991 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700993 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994
995 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700996 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 return true;
998}
999
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001000void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
1001 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002}
1003
1004void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001005 while (!mInboundQueue.empty()) {
1006 EventEntry* entry = mInboundQueue.front();
1007 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 releaseInboundEventLocked(entry);
1009 }
1010 traceInboundQueueLengthLocked();
1011}
1012
1013void InputDispatcher::releasePendingEventLocked() {
1014 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001016 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 }
1018}
1019
1020void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
1021 InjectionState* injectionState = entry->injectionState;
1022 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1023#if DEBUG_DISPATCH_CYCLE
1024 ALOGD("Injected inbound event was dropped.");
1025#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001026 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 }
1028 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001029 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 }
1031 addRecentEventLocked(entry);
1032 entry->release();
1033}
1034
1035void InputDispatcher::resetKeyRepeatLocked() {
1036 if (mKeyRepeatState.lastKeyEntry) {
1037 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001038 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
1040}
1041
Garfield Tane84e6f92019-08-29 17:28:41 -07001042KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1044
1045 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001046 uint32_t policyFlags = entry->policyFlags &
1047 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 if (entry->refCount == 1) {
1049 entry->recycle();
Garfield Tan1c7bc862020-01-28 13:24:04 -08001050 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 entry->eventTime = currentTime;
1052 entry->policyFlags = policyFlags;
1053 entry->repeatCount += 1;
1054 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001055 KeyEntry* newEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08001056 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001057 entry->displayId, policyFlags, entry->action, entry->flags,
1058 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001059 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060
1061 mKeyRepeatState.lastKeyEntry = newEntry;
1062 entry->release();
1063
1064 entry = newEntry;
1065 }
1066 entry->syntheticRepeat = true;
1067
1068 // Increment reference count since we keep a reference to the event in
1069 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1070 entry->refCount += 1;
1071
1072 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1073 return entry;
1074}
1075
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001076bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1077 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001079 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080#endif
1081
1082 // Reset key repeating in case a keyboard device was added or removed or something.
1083 resetKeyRepeatLocked();
1084
1085 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001086 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1087 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001089 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 return true;
1091}
1092
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001095 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097#endif
1098
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100 options.deviceId = entry->deviceId;
1101 synthesizeCancelationEventsForAllConnectionsLocked(options);
1102 return true;
1103}
1104
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001105void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07001106 if (mPendingEvent != nullptr) {
1107 // Move the pending event to the front of the queue. This will give the chance
1108 // for the pending event to get dispatched to the newly focused window
1109 mInboundQueue.push_front(mPendingEvent);
1110 mPendingEvent = nullptr;
1111 }
1112
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001113 FocusEntry* focusEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08001114 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07001115
1116 // This event should go to the front of the queue, but behind all other focus events
1117 // Find the last focus event, and insert right after it
1118 std::deque<EventEntry*>::reverse_iterator it =
1119 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1120 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1121
1122 // Maintain the order of focus events. Insert the entry after all other focus events.
1123 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001124}
1125
1126void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1127 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1128 if (channel == nullptr) {
1129 return; // Window has gone away
1130 }
1131 InputTarget target;
1132 target.inputChannel = channel;
1133 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1134 entry->dispatchInProgress = true;
Selim Cinek3d989c22020-06-17 21:42:12 +00001135
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001136 dispatchEventLocked(currentTime, entry, {target});
1137}
1138
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001140 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001142 if (!entry->dispatchInProgress) {
1143 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1144 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1145 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1146 if (mKeyRepeatState.lastKeyEntry &&
1147 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 // We have seen two identical key downs in a row which indicates that the device
1149 // driver is automatically generating key repeats itself. We take note of the
1150 // repeat here, but we disable our own next key repeat timer since it is clear that
1151 // we will not need to synthesize key repeats ourselves.
1152 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1153 resetKeyRepeatLocked();
1154 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1155 } else {
1156 // Not a repeat. Save key down state in case we do see a repeat later.
1157 resetKeyRepeatLocked();
1158 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1159 }
1160 mKeyRepeatState.lastKeyEntry = entry;
1161 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001162 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 resetKeyRepeatLocked();
1164 }
1165
1166 if (entry->repeatCount == 1) {
1167 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1168 } else {
1169 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1170 }
1171
1172 entry->dispatchInProgress = true;
1173
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001174 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 }
1176
1177 // Handle case where the policy asked us to try again later last time.
1178 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1179 if (currentTime < entry->interceptKeyWakeupTime) {
1180 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1181 *nextWakeupTime = entry->interceptKeyWakeupTime;
1182 }
1183 return false; // wait until next wakeup
1184 }
1185 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1186 entry->interceptKeyWakeupTime = 0;
1187 }
1188
1189 // Give the policy a chance to intercept the key.
1190 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1191 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001192 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001193 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001194 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001195 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001196 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001197 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 }
1199 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001200 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 entry->refCount += 1;
1202 return false; // wait for the command to run
1203 } else {
1204 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1205 }
1206 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001207 if (*dropReason == DropReason::NOT_DROPPED) {
1208 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 }
1210 }
1211
1212 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001213 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001215 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001216 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001217 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 return true;
1219 }
1220
1221 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001222 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001223 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001224 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1226 return false;
1227 }
1228
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001229 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1231 return true;
1232 }
1233
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001234 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001235 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236
1237 // Dispatch the key.
1238 dispatchEventLocked(currentTime, entry, inputTargets);
1239 return true;
1240}
1241
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001242void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001244 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001245 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1246 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001247 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1248 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1249 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250#endif
1251}
1252
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001253bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1254 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001255 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001257 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 entry->dispatchInProgress = true;
1259
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001260 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 }
1262
1263 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001264 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001265 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001266 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001267 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 return true;
1269 }
1270
1271 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1272
1273 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001274 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275
1276 bool conflictingPointerActions = false;
1277 int32_t injectionResult;
1278 if (isPointerEvent) {
1279 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001280 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001281 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001282 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 } else {
1284 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001285 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001286 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287 }
1288 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1289 return false;
1290 }
1291
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001292 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001293 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1294 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1295 return true;
1296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001298 CancelationOptions::Mode mode(isPointerEvent
1299 ? CancelationOptions::CANCEL_POINTER_EVENTS
1300 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1301 CancelationOptions options(mode, "input event injection failed");
1302 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 return true;
1304 }
1305
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001306 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001307 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001309 if (isPointerEvent) {
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001310 std::unordered_map<int32_t, TouchState>::iterator it =
1311 mTouchStatesByDisplay.find(entry->displayId);
1312 if (it != mTouchStatesByDisplay.end()) {
1313 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001314 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001315 // The event has gone through these portal windows, so we add monitoring targets of
1316 // the corresponding displays as well.
1317 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001318 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001319 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001320 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001321 }
1322 }
1323 }
1324 }
1325
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 // Dispatch the motion.
1327 if (conflictingPointerActions) {
1328 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001329 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 synthesizeCancelationEventsForAllConnectionsLocked(options);
1331 }
1332 dispatchEventLocked(currentTime, entry, inputTargets);
1333 return true;
1334}
1335
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001336void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001338 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001339 ", policyFlags=0x%x, "
1340 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1341 "metaState=0x%x, buttonState=0x%x,"
1342 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001343 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1344 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1345 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001347 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001349 "x=%f, y=%f, pressure=%f, size=%f, "
1350 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1351 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001352 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1353 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1354 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1355 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1356 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1357 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1358 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1359 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1360 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1361 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 }
1363#endif
1364}
1365
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001366void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1367 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001368 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369#if DEBUG_DISPATCH_CYCLE
1370 ALOGD("dispatchEventToCurrentInputTargets");
1371#endif
1372
1373 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1374
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001375 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001377 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001378 sp<Connection> connection =
1379 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001380 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001381 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001383 if (DEBUG_FOCUS) {
1384 ALOGD("Dropping event delivery to target with channel '%s' because it "
1385 "is no longer registered with the input dispatcher.",
1386 inputTarget.inputChannel->getName().c_str());
1387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 }
1389 }
1390}
1391
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001392void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1393 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1394 // If the policy decides to close the app, we will get a channel removal event via
1395 // unregisterInputChannel, and will clean up the connection that way. We are already not
1396 // sending new pointers to the connection when it blocked, but focused events will continue to
1397 // pile up.
1398 ALOGW("Canceling events for %s because it is unresponsive",
1399 connection->inputChannel->getName().c_str());
1400 if (connection->status == Connection::STATUS_NORMAL) {
1401 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1402 "application not responding");
1403 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404 }
1405}
1406
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001407void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001408 if (DEBUG_FOCUS) {
1409 ALOGD("Resetting ANR timeouts.");
1410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411
1412 // Reset input target wait timeout.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001413 mNoFocusedWindowTimeoutTime = std::nullopt;
1414 mAwaitedFocusedApplication.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415}
1416
Tiger Huang721e26f2018-07-24 22:26:19 +08001417/**
1418 * Get the display id that the given event should go to. If this event specifies a valid display id,
1419 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1420 * Focused display is the display that the user most recently interacted with.
1421 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001422int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001423 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001424 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001425 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001426 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1427 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001428 break;
1429 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001430 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001431 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1432 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001433 break;
1434 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001435 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001436 case EventEntry::Type::CONFIGURATION_CHANGED:
1437 case EventEntry::Type::DEVICE_RESET: {
1438 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001439 return ADISPLAY_ID_NONE;
1440 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001441 }
1442 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1443}
1444
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001445bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1446 const char* focusedWindowName) {
1447 if (mAnrTracker.empty()) {
1448 // already processed all events that we waited for
1449 mKeyIsWaitingForEventsTimeout = std::nullopt;
1450 return false;
1451 }
1452
1453 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1454 // Start the timer
1455 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1456 "focus to change",
1457 focusedWindowName);
1458 mKeyIsWaitingForEventsTimeout = currentTime + KEY_WAITING_FOR_EVENTS_TIMEOUT.count();
1459 return true;
1460 }
1461
1462 // We still have pending events, and already started the timer
1463 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1464 return true; // Still waiting
1465 }
1466
1467 // Waited too long, and some connection still hasn't processed all motions
1468 // Just send the key to the focused window
1469 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1470 focusedWindowName);
1471 mKeyIsWaitingForEventsTimeout = std::nullopt;
1472 return false;
1473}
1474
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001476 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001477 std::vector<InputTarget>& inputTargets,
1478 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001479 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480
Tiger Huang721e26f2018-07-24 22:26:19 +08001481 int32_t displayId = getTargetDisplayId(entry);
1482 sp<InputWindowHandle> focusedWindowHandle =
1483 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1484 sp<InputApplicationHandle> focusedApplicationHandle =
1485 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1486
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 // If there is no currently focused window and no focused application
1488 // then drop the event.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001489 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1490 ALOGI("Dropping %s event because there is no focused window or focused application in "
1491 "display %" PRId32 ".",
1492 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001493 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 }
1495
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001496 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1497 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1498 // start interacting with another application via touch (app switch). This code can be removed
1499 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1500 // an app is expected to have a focused window.
1501 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1502 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1503 // We just discovered that there's no focused window. Start the ANR timer
1504 const nsecs_t timeout = focusedApplicationHandle->getDispatchingTimeout(
1505 DEFAULT_INPUT_DISPATCHING_TIMEOUT.count());
1506 mNoFocusedWindowTimeoutTime = currentTime + timeout;
1507 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakou265ab012020-09-08 19:43:33 -05001508 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001509 ALOGW("Waiting because no window has focus but %s may eventually add a "
1510 "window when it finishes starting up. Will wait for %" PRId64 "ms",
1511 mAwaitedFocusedApplication->getName().c_str(), ns2ms(timeout));
1512 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1513 return INPUT_EVENT_INJECTION_PENDING;
1514 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1515 // Already raised ANR. Drop the event
1516 ALOGE("Dropping %s event because there is no focused window",
1517 EventEntry::typeToString(entry.type));
1518 return INPUT_EVENT_INJECTION_FAILED;
1519 } else {
1520 // Still waiting for the focused window
1521 return INPUT_EVENT_INJECTION_PENDING;
1522 }
1523 }
1524
1525 // we have a valid, non-null focused window
1526 resetNoFocusedWindowTimeoutLocked();
1527
Michael Wrightd02c5b62014-02-10 15:10:22 -08001528 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001529 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001530 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 }
1532
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001533 if (focusedWindowHandle->getInfo()->paused) {
1534 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1535 return INPUT_EVENT_INJECTION_PENDING;
1536 }
1537
1538 // If the event is a key event, then we must wait for all previous events to
1539 // complete before delivering it because previous events may have the
1540 // side-effect of transferring focus to a different window and we want to
1541 // ensure that the following keys are sent to the new window.
1542 //
1543 // Suppose the user touches a button in a window then immediately presses "A".
1544 // If the button causes a pop-up window to appear then we want to ensure that
1545 // the "A" key is delivered to the new pop-up window. This is because users
1546 // often anticipate pending UI changes when typing on a keyboard.
1547 // To obtain this behavior, we must serialize key events with respect to all
1548 // prior input events.
1549 if (entry.type == EventEntry::Type::KEY) {
1550 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1551 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1552 return INPUT_EVENT_INJECTION_PENDING;
1553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 }
1555
1556 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001557 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001558 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1559 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560
1561 // Done.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001562 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563}
1564
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001565/**
1566 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1567 * that are currently unresponsive.
1568 */
1569std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1570 const std::vector<TouchedMonitor>& monitors) const {
1571 std::vector<TouchedMonitor> responsiveMonitors;
1572 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1573 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1574 sp<Connection> connection = getConnectionLocked(
1575 monitor.monitor.inputChannel->getConnectionToken());
1576 if (connection == nullptr) {
1577 ALOGE("Could not find connection for monitor %s",
1578 monitor.monitor.inputChannel->getName().c_str());
1579 return false;
1580 }
1581 if (!connection->responsive) {
1582 ALOGW("Unresponsive monitor %s will not get the new gesture",
1583 connection->inputChannel->getName().c_str());
1584 return false;
1585 }
1586 return true;
1587 });
1588 return responsiveMonitors;
1589}
1590
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001592 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001593 std::vector<InputTarget>& inputTargets,
1594 nsecs_t* nextWakeupTime,
1595 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001596 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 enum InjectionPermission {
1598 INJECTION_PERMISSION_UNKNOWN,
1599 INJECTION_PERMISSION_GRANTED,
1600 INJECTION_PERMISSION_DENIED
1601 };
1602
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 // For security reasons, we defer updating the touch state until we are sure that
1604 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001605 int32_t displayId = entry.displayId;
1606 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1608
1609 // Update the touch state as needed based on the properties of the touch event.
1610 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1611 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1612 sp<InputWindowHandle> newHoverWindowHandle;
1613
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001614 // Copy current touch state into tempTouchState.
1615 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1616 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001617 const TouchState* oldState = nullptr;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001618 TouchState tempTouchState;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001619 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1620 mTouchStatesByDisplay.find(displayId);
1621 if (oldStateIt != mTouchStatesByDisplay.end()) {
1622 oldState = &(oldStateIt->second);
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001623 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001624 }
1625
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001626 bool isSplit = tempTouchState.split;
1627 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1628 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1629 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001630 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1631 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1632 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1633 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1634 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001635 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 bool wrongDevice = false;
1637 if (newGesture) {
1638 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001639 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001640 ALOGI("Dropping event because a pointer for a different device is already down "
1641 "in display %" PRId32,
1642 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001643 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1645 switchedDevice = false;
1646 wrongDevice = true;
1647 goto Failed;
1648 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001649 tempTouchState.reset();
1650 tempTouchState.down = down;
1651 tempTouchState.deviceId = entry.deviceId;
1652 tempTouchState.source = entry.source;
1653 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001655 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001656 ALOGI("Dropping move event because a pointer for a different device is already active "
1657 "in display %" PRId32,
1658 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001659 // TODO: test multiple simultaneous input streams.
1660 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1661 switchedDevice = false;
1662 wrongDevice = true;
1663 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 }
1665
1666 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1667 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1668
Garfield Tan00f511d2019-06-12 16:55:40 -07001669 int32_t x;
1670 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001672 // Always dispatch mouse events to cursor position.
1673 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001674 x = int32_t(entry.xCursorPosition);
1675 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001676 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001677 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1678 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001679 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001680 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001681 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001682 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1683 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001684
1685 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001686 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001687 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001690 if (newTouchedWindowHandle != nullptr &&
1691 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001692 // New window supports splitting, but we should never split mouse events.
1693 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 } else if (isSplit) {
1695 // New window does not support splitting but we have already split events.
1696 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001697 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 }
1699
1700 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001701 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001703 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001704 }
1705
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001706 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1707 ALOGI("Not sending touch event to %s because it is paused",
1708 newTouchedWindowHandle->getName().c_str());
1709 newTouchedWindowHandle = nullptr;
1710 }
1711
1712 if (newTouchedWindowHandle != nullptr) {
1713 sp<Connection> connection = getConnectionLocked(newTouchedWindowHandle->getToken());
1714 if (connection == nullptr) {
1715 ALOGI("Could not find connection for %s",
1716 newTouchedWindowHandle->getName().c_str());
1717 newTouchedWindowHandle = nullptr;
1718 } else if (!connection->responsive) {
1719 // don't send the new touch to an unresponsive window
1720 ALOGW("Unresponsive window %s will not get the new gesture at %" PRIu64,
1721 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1722 newTouchedWindowHandle = nullptr;
1723 }
1724 }
1725
1726 // Also don't send the new touch event to unresponsive gesture monitors
1727 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1728
Michael Wright3dd60e22019-03-27 22:06:44 +00001729 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1730 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001731 "(%d, %d) in display %" PRId32 ".",
1732 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001733 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1734 goto Failed;
1735 }
1736
1737 if (newTouchedWindowHandle != nullptr) {
1738 // Set target flags.
1739 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1740 if (isSplit) {
1741 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001743 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1744 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1745 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1746 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1747 }
1748
1749 // Update hover state.
1750 if (isHoverAction) {
1751 newHoverWindowHandle = newTouchedWindowHandle;
1752 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1753 newHoverWindowHandle = mLastHoverWindowHandle;
1754 }
1755
1756 // Update the temporary touch state.
1757 BitSet32 pointerIds;
1758 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001759 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001760 pointerIds.markBit(pointerId);
1761 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001762 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 }
1764
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001765 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766 } else {
1767 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1768
1769 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001770 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001771 if (DEBUG_FOCUS) {
1772 ALOGD("Dropping event because the pointer is not down or we previously "
1773 "dropped the pointer down event in display %" PRId32,
1774 displayId);
1775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1777 goto Failed;
1778 }
1779
1780 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001781 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001782 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001783 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1784 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785
1786 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001787 tempTouchState.getFirstForegroundWindowHandle();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001789 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001790 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1791 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001792 if (DEBUG_FOCUS) {
1793 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1794 oldTouchedWindowHandle->getName().c_str(),
1795 newTouchedWindowHandle->getName().c_str(), displayId);
1796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 // Make a slippery exit from the old window.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001798 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1799 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1800 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801
1802 // Make a slippery entrance into the new window.
1803 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1804 isSplit = true;
1805 }
1806
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001807 int32_t targetFlags =
1808 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 if (isSplit) {
1810 targetFlags |= InputTarget::FLAG_SPLIT;
1811 }
1812 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1813 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1814 }
1815
1816 BitSet32 pointerIds;
1817 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001818 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001820 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 }
1822 }
1823 }
1824
1825 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1826 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001827 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828#if DEBUG_HOVER
1829 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001830 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831#endif
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001832 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1833 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 }
1835
1836 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001837 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838#if DEBUG_HOVER
1839 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001840 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841#endif
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001842 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1843 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1844 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 }
1846 }
1847
1848 // Check permission to inject into all touched foreground windows and ensure there
1849 // is at least one touched foreground window.
1850 {
1851 bool haveForegroundWindow = false;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001852 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1854 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001855 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1857 injectionPermission = INJECTION_PERMISSION_DENIED;
1858 goto Failed;
1859 }
1860 }
1861 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001862 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001863 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001864 ALOGI("Dropping event because there is no touched foreground window in display "
1865 "%" PRId32 " or gesture monitor to receive it.",
1866 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1868 goto Failed;
1869 }
1870
1871 // Permission granted to injection into all touched foreground windows.
1872 injectionPermission = INJECTION_PERMISSION_GRANTED;
1873 }
1874
1875 // Check whether windows listening for outside touches are owned by the same UID. If it is
1876 // set the policy flag that we will not reveal coordinate information to this window.
1877 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1878 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001879 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001880 if (foregroundWindowHandle) {
1881 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001882 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001883 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1884 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1885 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001886 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1887 InputTarget::FLAG_ZERO_COORDS,
1888 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 }
1891 }
1892 }
1893 }
1894
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 // If this is the first pointer going down and the touched window has a wallpaper
1896 // then also add the touched wallpaper windows so they are locked in for the duration
1897 // of the touch gesture.
1898 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1899 // engine only supports touch events. We would need to add a mechanism similar
1900 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1901 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1902 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001903 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001904 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001905 const std::vector<sp<InputWindowHandle>> windowHandles =
1906 getWindowHandlesLocked(displayId);
1907 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001909 if (info->displayId == displayId &&
1910 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001911 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001912 .addOrUpdateWindow(windowHandle,
1913 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1914 InputTarget::
1915 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1916 InputTarget::FLAG_DISPATCH_AS_IS,
1917 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 }
1919 }
1920 }
1921 }
1922
1923 // Success! Output targets.
1924 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1925
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001926 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001928 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 }
1930
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001931 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001932 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001933 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001934 }
1935
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 // Drop the outside or hover touch windows since we will not care about them
1937 // in the next iteration.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001938 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939
1940Failed:
1941 // Check injection permission once and for all.
1942 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001943 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 injectionPermission = INJECTION_PERMISSION_GRANTED;
1945 } else {
1946 injectionPermission = INJECTION_PERMISSION_DENIED;
1947 }
1948 }
1949
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001950 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1951 return injectionResult;
1952 }
1953
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001955 if (!wrongDevice) {
1956 if (switchedDevice) {
1957 if (DEBUG_FOCUS) {
1958 ALOGD("Conflicting pointer actions: Switched to a different device.");
1959 }
1960 *outConflictingPointerActions = true;
1961 }
1962
1963 if (isHoverAction) {
1964 // Started hovering, therefore no longer down.
1965 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001966 if (DEBUG_FOCUS) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001967 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1968 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 *outConflictingPointerActions = true;
1971 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001972 tempTouchState.reset();
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001973 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1974 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001975 tempTouchState.deviceId = entry.deviceId;
1976 tempTouchState.source = entry.source;
1977 tempTouchState.displayId = displayId;
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001978 }
1979 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1980 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1981 // All pointers up or canceled.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001982 tempTouchState.reset();
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001983 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1984 // First pointer went down.
1985 if (oldState && oldState->down) {
1986 if (DEBUG_FOCUS) {
1987 ALOGD("Conflicting pointer actions: Down received while already down.");
1988 }
1989 *outConflictingPointerActions = true;
1990 }
1991 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1992 // One pointer went up.
1993 if (isSplit) {
1994 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1995 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001997 for (size_t i = 0; i < tempTouchState.windows.size();) {
1998 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001999 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2000 touchedWindow.pointerIds.clearBit(pointerId);
2001 if (touchedWindow.pointerIds.isEmpty()) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07002002 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002003 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002006 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002008 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002009 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002010
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002011 // Save changes unless the action was scroll in which case the temporary touch
2012 // state was only valid for this one action.
2013 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07002014 if (tempTouchState.displayId >= 0) {
2015 mTouchStatesByDisplay[displayId] = tempTouchState;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07002016 } else {
2017 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07002021 // Update hover state.
2022 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023 }
2024
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 return injectionResult;
2026}
2027
2028void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002029 int32_t targetFlags, BitSet32 pointerIds,
2030 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002031 std::vector<InputTarget>::iterator it =
2032 std::find_if(inputTargets.begin(), inputTargets.end(),
2033 [&windowHandle](const InputTarget& inputTarget) {
2034 return inputTarget.inputChannel->getConnectionToken() ==
2035 windowHandle->getToken();
2036 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002037
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002038 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002039
2040 if (it == inputTargets.end()) {
2041 InputTarget inputTarget;
2042 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2043 if (inputChannel == nullptr) {
2044 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2045 return;
2046 }
2047 inputTarget.inputChannel = inputChannel;
2048 inputTarget.flags = targetFlags;
2049 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2050 inputTargets.push_back(inputTarget);
2051 it = inputTargets.end() - 1;
2052 }
2053
2054 ALOG_ASSERT(it->flags == targetFlags);
2055 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2056
2057 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
2058 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059}
2060
Michael Wright3dd60e22019-03-27 22:06:44 +00002061void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002062 int32_t displayId, float xOffset,
2063 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002064 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2065 mGlobalMonitorsByDisplay.find(displayId);
2066
2067 if (it != mGlobalMonitorsByDisplay.end()) {
2068 const std::vector<Monitor>& monitors = it->second;
2069 for (const Monitor& monitor : monitors) {
2070 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 }
2073}
2074
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002075void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2076 float yOffset,
2077 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002078 InputTarget target;
2079 target.inputChannel = monitor.inputChannel;
2080 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002081 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00002082 inputTargets.push_back(target);
2083}
2084
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002086 const InjectionState* injectionState) {
2087 if (injectionState &&
2088 (windowHandle == nullptr ||
2089 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2090 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002091 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002093 "owned by uid %d",
2094 injectionState->injectorPid, injectionState->injectorUid,
2095 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 } else {
2097 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002098 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099 }
2100 return false;
2101 }
2102 return true;
2103}
2104
Robert Carr9cada032020-04-13 17:21:08 -07002105/**
2106 * Indicate whether one window handle should be considered as obscuring
2107 * another window handle. We only check a few preconditions. Actually
2108 * checking the bounds is left to the caller.
2109 */
2110static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2111 const sp<InputWindowHandle>& otherHandle) {
2112 // Compare by token so cloned layers aren't counted
2113 if (haveSameToken(windowHandle, otherHandle)) {
2114 return false;
2115 }
2116 auto info = windowHandle->getInfo();
2117 auto otherInfo = otherHandle->getInfo();
2118 if (!otherInfo->visible) {
2119 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002120 } else if (info->ownerPid == otherInfo->ownerPid) {
2121 // If ownerPid is the same we don't generate occlusion events as there
2122 // is no in-process security boundary.
Robert Carr9cada032020-04-13 17:21:08 -07002123 return false;
2124 } else if (otherInfo->isTrustedOverlay()) {
2125 return false;
2126 } else if (otherInfo->displayId != info->displayId) {
2127 return false;
2128 }
2129 return true;
2130}
2131
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002132bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2133 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002135 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2136 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002137 if (windowHandle == otherHandle) {
2138 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002141 if (canBeObscuredBy(windowHandle, otherHandle) &&
2142 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 return true;
2144 }
2145 }
2146 return false;
2147}
2148
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002149bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2150 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002151 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002152 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002153 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002154 if (windowHandle == otherHandle) {
2155 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002156 }
2157
2158 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002159 if (canBeObscuredBy(windowHandle, otherHandle) &&
2160 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002161 return true;
2162 }
2163 }
2164 return false;
2165}
2166
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002167std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168 const sp<InputApplicationHandle>& applicationHandle,
2169 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002170 if (applicationHandle != nullptr) {
2171 if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002172 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 } else {
2174 return applicationHandle->getName();
2175 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002176 } else if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002177 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002179 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180 }
2181}
2182
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002183void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002184 if (eventEntry.type == EventEntry::Type::FOCUS) {
2185 // Focus events are passed to apps, but do not represent user activity.
2186 return;
2187 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002188 int32_t displayId = getTargetDisplayId(eventEntry);
2189 sp<InputWindowHandle> focusedWindowHandle =
2190 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2191 if (focusedWindowHandle != nullptr) {
2192 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2194#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002195 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196#endif
2197 return;
2198 }
2199 }
2200
2201 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002202 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002203 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002204 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2205 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002206 return;
2207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002209 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002210 eventType = USER_ACTIVITY_EVENT_TOUCH;
2211 }
2212 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002214 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002215 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2216 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002217 return;
2218 }
2219 eventType = USER_ACTIVITY_EVENT_BUTTON;
2220 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002222 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002223 case EventEntry::Type::CONFIGURATION_CHANGED:
2224 case EventEntry::Type::DEVICE_RESET: {
2225 LOG_ALWAYS_FATAL("%s events are not user activity",
2226 EventEntry::typeToString(eventEntry.type));
2227 break;
2228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 }
2230
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002231 std::unique_ptr<CommandEntry> commandEntry =
2232 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002233 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002235 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236}
2237
2238void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002239 const sp<Connection>& connection,
2240 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002241 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002242 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002243 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002244 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002245 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002246 ATRACE_NAME(message.c_str());
2247 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248#if DEBUG_DISPATCH_CYCLE
2249 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002250 "globalScaleFactor=%f, pointerIds=0x%x %s",
2251 connection->getInputChannelName().c_str(), inputTarget.flags,
2252 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2253 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254#endif
2255
2256 // Skip this event if the connection status is not normal.
2257 // We don't want to enqueue additional outbound events if the connection is broken.
2258 if (connection->status != Connection::STATUS_NORMAL) {
2259#if DEBUG_DISPATCH_CYCLE
2260 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002261 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262#endif
2263 return;
2264 }
2265
2266 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002267 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2268 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2269 "Entry type %s should not have FLAG_SPLIT",
2270 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002272 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002273 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002274 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002275 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 if (!splitMotionEntry) {
2277 return; // split event was dropped
2278 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002279 if (DEBUG_FOCUS) {
2280 ALOGD("channel '%s' ~ Split motion event.",
2281 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002282 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002283 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002284 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 splitMotionEntry->release();
2286 return;
2287 }
2288 }
2289
2290 // Not splitting. Enqueue dispatch entries for the event as is.
2291 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2292}
2293
2294void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 const sp<Connection>& connection,
2296 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002297 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002298 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002299 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002300 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002301 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002302 ATRACE_NAME(message.c_str());
2303 }
2304
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002305 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306
2307 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002308 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002309 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002310 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002311 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002312 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002313 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002314 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002315 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002316 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002317 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002318 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002319 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320
2321 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002322 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323 startDispatchCycleLocked(currentTime, connection);
2324 }
2325}
2326
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002327void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2328 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002329 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002330 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002331 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002332 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2333 connection->getInputChannelName().c_str(),
2334 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002335 ATRACE_NAME(message.c_str());
2336 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002337 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 if (!(inputTargetFlags & dispatchMode)) {
2339 return;
2340 }
2341 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2342
2343 // This is a new event.
2344 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002345 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002346 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002348 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2349 // different EventEntry than what was passed in.
2350 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002352 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002353 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002354 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002355 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002356 dispatchEntry->resolvedAction = keyEntry.action;
2357 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002359 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2360 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002362 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2363 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002365 return; // skip the inconsistent event
2366 }
2367 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002370 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002371 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002372 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2373 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2374 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2375 static_cast<int32_t>(IdGenerator::Source::OTHER);
2376 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002377 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2378 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2379 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2380 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2381 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2382 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2383 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2384 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2385 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2386 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2387 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002388 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002389 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002390 }
2391 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002392 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2393 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002395 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2396 "event",
2397 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002399 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002402 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002403 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2404 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2405 }
2406 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2407 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002410 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2411 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002413 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2414 "event",
2415 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002417 return; // skip the inconsistent event
2418 }
2419
Garfield Tan1c7bc862020-01-28 13:24:04 -08002420 dispatchEntry->resolvedEventId =
2421 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2422 ? mIdGenerator.nextId()
2423 : motionEntry.id;
2424 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2425 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2426 ") to MotionEvent(id=0x%" PRIx32 ").",
2427 motionEntry.id, dispatchEntry->resolvedEventId);
2428 ATRACE_NAME(message.c_str());
2429 }
2430
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002431 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002432 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002433
2434 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002436 case EventEntry::Type::FOCUS: {
2437 break;
2438 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002439 case EventEntry::Type::CONFIGURATION_CHANGED:
2440 case EventEntry::Type::DEVICE_RESET: {
2441 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002442 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002443 break;
2444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445 }
2446
2447 // Remember that we are waiting for this dispatch to complete.
2448 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002449 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 }
2451
2452 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002453 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002454 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002455}
2456
chaviwfd6d3512019-03-25 13:23:49 -07002457void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002458 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002459 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002460 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2461 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002462 return;
2463 }
2464
2465 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2466 if (inputWindowHandle == nullptr) {
2467 return;
2468 }
2469
chaviw8c9cf542019-03-25 13:02:48 -07002470 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002471 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002472
2473 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2474
2475 if (!hasFocusChanged) {
2476 return;
2477 }
2478
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002479 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2480 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002481 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002482 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483}
2484
2485void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002486 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002487 if (ATRACE_ENABLED()) {
2488 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002489 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002490 ATRACE_NAME(message.c_str());
2491 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002493 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494#endif
2495
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002496 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2497 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07002499 const nsecs_t timeout =
2500 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
2501 dispatchEntry->timeoutTime = currentTime + timeout;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502
2503 // Publish the event.
2504 status_t status;
2505 EventEntry* eventEntry = dispatchEntry->eventEntry;
2506 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002507 case EventEntry::Type::KEY: {
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002508 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2509 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002511 // Publish the key event.
Garfield Tan1c7bc862020-01-28 13:24:04 -08002512 status =
2513 connection->inputPublisher
2514 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2515 keyEntry->deviceId, keyEntry->source,
2516 keyEntry->displayId, std::move(hmac),
2517 dispatchEntry->resolvedAction,
2518 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2519 keyEntry->scanCode, keyEntry->metaState,
2520 keyEntry->repeatCount, keyEntry->downTime,
2521 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002522 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523 }
2524
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002525 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002526 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002528 PointerCoords scaledCoords[MAX_POINTERS];
2529 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2530
chaviw82357092020-01-28 13:13:06 -08002531 // Set the X and Y offset and X and Y scale depending on the input source.
2532 float xOffset = 0.0f, yOffset = 0.0f;
2533 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002534 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2535 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2536 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002537 xScale = dispatchEntry->windowXScale;
2538 yScale = dispatchEntry->windowYScale;
2539 xOffset = dispatchEntry->xOffset * xScale;
2540 yOffset = dispatchEntry->yOffset * yScale;
2541 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002542 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2543 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002544 // Don't apply window scale here since we don't want scale to affect raw
2545 // coordinates. The scale will be sent back to the client and applied
2546 // later when requesting relative coordinates.
2547 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2548 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002549 }
2550 usingCoords = scaledCoords;
2551 }
2552 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002553 // We don't want the dispatch target to know.
2554 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2555 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2556 scaledCoords[i].clear();
2557 }
2558 usingCoords = scaledCoords;
2559 }
2560 }
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002561
2562 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002563
2564 // Publish the motion event.
2565 status = connection->inputPublisher
Garfield Tan1c7bc862020-01-28 13:24:04 -08002566 .publishMotionEvent(dispatchEntry->seq,
2567 dispatchEntry->resolvedEventId,
2568 motionEntry->deviceId, motionEntry->source,
2569 motionEntry->displayId, std::move(hmac),
2570 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002571 motionEntry->actionButton,
2572 dispatchEntry->resolvedFlags,
2573 motionEntry->edgeFlags, motionEntry->metaState,
2574 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002575 motionEntry->classification, xScale, yScale,
2576 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002577 motionEntry->yPrecision,
2578 motionEntry->xCursorPosition,
2579 motionEntry->yCursorPosition,
2580 motionEntry->downTime, motionEntry->eventTime,
2581 motionEntry->pointerCount,
2582 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002583 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002584 break;
2585 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002586 case EventEntry::Type::FOCUS: {
2587 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2588 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tan1c7bc862020-01-28 13:24:04 -08002589 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002590 focusEntry->hasFocus,
2591 mInTouchMode);
2592 break;
2593 }
2594
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002595 case EventEntry::Type::CONFIGURATION_CHANGED:
2596 case EventEntry::Type::DEVICE_RESET: {
2597 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2598 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002599 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 }
2602
2603 // Check the result.
2604 if (status) {
2605 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002606 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002608 "This is unexpected because the wait queue is empty, so the pipe "
2609 "should be empty and we shouldn't have any problems writing an "
2610 "event to it, status=%d",
2611 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2613 } else {
2614 // Pipe is full and we are waiting for the app to finish process some events
2615 // before sending more events to it.
2616#if DEBUG_DISPATCH_CYCLE
2617 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002618 "waiting for the application to catch up",
2619 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621 }
2622 } else {
2623 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002624 "status=%d",
2625 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2627 }
2628 return;
2629 }
2630
2631 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002632 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2633 connection->outboundQueue.end(),
2634 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002635 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002636 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07002637 if (connection->responsive) {
2638 mAnrTracker.insert(dispatchEntry->timeoutTime,
2639 connection->inputChannel->getConnectionToken());
2640 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002641 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 }
2643}
2644
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002645const std::array<uint8_t, 32> InputDispatcher::getSignature(
2646 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2647 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2648 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2649 // Only sign events up and down events as the purely move events
2650 // are tied to their up/down counterparts so signing would be redundant.
2651 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2652 verifiedEvent.actionMasked = actionMasked;
2653 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2654 return mHmacKeyManager.sign(verifiedEvent);
2655 }
2656 return INVALID_HMAC;
2657}
2658
2659const std::array<uint8_t, 32> InputDispatcher::getSignature(
2660 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2661 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2662 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2663 verifiedEvent.action = dispatchEntry.resolvedAction;
2664 return mHmacKeyManager.sign(verifiedEvent);
2665}
2666
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002668 const sp<Connection>& connection, uint32_t seq,
2669 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670#if DEBUG_DISPATCH_CYCLE
2671 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002672 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673#endif
2674
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002675 if (connection->status == Connection::STATUS_BROKEN ||
2676 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677 return;
2678 }
2679
2680 // Notify other system components and prepare to start the next dispatch cycle.
2681 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2682}
2683
2684void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002685 const sp<Connection>& connection,
2686 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687#if DEBUG_DISPATCH_CYCLE
2688 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002689 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690#endif
2691
2692 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002693 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002694 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002695 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002696 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697
2698 // The connection appears to be unrecoverably broken.
2699 // Ignore already broken or zombie connections.
2700 if (connection->status == Connection::STATUS_NORMAL) {
2701 connection->status = Connection::STATUS_BROKEN;
2702
2703 if (notify) {
2704 // Notify other system components.
2705 onDispatchCycleBrokenLocked(currentTime, connection);
2706 }
2707 }
2708}
2709
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002710void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2711 while (!queue.empty()) {
2712 DispatchEntry* dispatchEntry = queue.front();
2713 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002714 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715 }
2716}
2717
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002718void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002720 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721 }
2722 delete dispatchEntry;
2723}
2724
2725int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2726 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2727
2728 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002729 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002731 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002733 "fd=%d, events=0x%x",
2734 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735 return 0; // remove the callback
2736 }
2737
2738 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002739 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2741 if (!(events & ALOOPER_EVENT_INPUT)) {
2742 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002743 "events=0x%x",
2744 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 return 1;
2746 }
2747
2748 nsecs_t currentTime = now();
2749 bool gotOne = false;
2750 status_t status;
2751 for (;;) {
2752 uint32_t seq;
2753 bool handled;
2754 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2755 if (status) {
2756 break;
2757 }
2758 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2759 gotOne = true;
2760 }
2761 if (gotOne) {
2762 d->runCommandsLockedInterruptible();
2763 if (status == WOULD_BLOCK) {
2764 return 1;
2765 }
2766 }
2767
2768 notify = status != DEAD_OBJECT || !connection->monitor;
2769 if (notify) {
2770 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002771 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772 }
2773 } else {
2774 // Monitor channels are never explicitly unregistered.
2775 // We do it automatically when the remote endpoint is closed so don't warn
2776 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002777 const bool stillHaveWindowHandle =
2778 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2779 nullptr;
2780 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781 if (notify) {
2782 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002783 "events=0x%x",
2784 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 }
2786 }
2787
2788 // Unregister the channel.
2789 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2790 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002791 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792}
2793
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002794void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002796 for (const auto& pair : mConnectionsByFd) {
2797 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002798 }
2799}
2800
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002801void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002802 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002803 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2804 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2805}
2806
2807void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2808 const CancelationOptions& options,
2809 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2810 for (const auto& it : monitorsByDisplay) {
2811 const std::vector<Monitor>& monitors = it.second;
2812 for (const Monitor& monitor : monitors) {
2813 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002814 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002815 }
2816}
2817
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2819 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002820 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002821 if (connection == nullptr) {
2822 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002824
2825 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826}
2827
2828void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2829 const sp<Connection>& connection, const CancelationOptions& options) {
2830 if (connection->status == Connection::STATUS_BROKEN) {
2831 return;
2832 }
2833
2834 nsecs_t currentTime = now();
2835
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002836 std::vector<EventEntry*> cancelationEvents =
2837 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002839 if (cancelationEvents.empty()) {
2840 return;
2841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002843 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2844 "with reality: %s, mode=%d.",
2845 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2846 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002848
2849 InputTarget target;
2850 sp<InputWindowHandle> windowHandle =
2851 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2852 if (windowHandle != nullptr) {
2853 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2854 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2855 windowInfo->windowXScale, windowInfo->windowYScale);
2856 target.globalScaleFactor = windowInfo->globalScaleFactor;
2857 }
2858 target.inputChannel = connection->inputChannel;
2859 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2860
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002861 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2862 EventEntry* cancelationEventEntry = cancelationEvents[i];
2863 switch (cancelationEventEntry->type) {
2864 case EventEntry::Type::KEY: {
2865 logOutboundKeyDetails("cancel - ",
2866 static_cast<const KeyEntry&>(*cancelationEventEntry));
2867 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002869 case EventEntry::Type::MOTION: {
2870 logOutboundMotionDetails("cancel - ",
2871 static_cast<const MotionEntry&>(*cancelationEventEntry));
2872 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002874 case EventEntry::Type::FOCUS: {
2875 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2876 break;
2877 }
2878 case EventEntry::Type::CONFIGURATION_CHANGED:
2879 case EventEntry::Type::DEVICE_RESET: {
2880 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2881 EventEntry::typeToString(cancelationEventEntry->type));
2882 break;
2883 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884 }
2885
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002886 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2887 target, InputTarget::FLAG_DISPATCH_AS_IS);
2888
2889 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002891
2892 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893}
2894
Svet Ganov5d3bc372020-01-26 23:11:07 -08002895void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2896 const sp<Connection>& connection) {
2897 if (connection->status == Connection::STATUS_BROKEN) {
2898 return;
2899 }
2900
2901 nsecs_t currentTime = now();
2902
2903 std::vector<EventEntry*> downEvents =
2904 connection->inputState.synthesizePointerDownEvents(currentTime);
2905
2906 if (downEvents.empty()) {
2907 return;
2908 }
2909
2910#if DEBUG_OUTBOUND_EVENT_DETAILS
2911 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2912 connection->getInputChannelName().c_str(), downEvents.size());
2913#endif
2914
2915 InputTarget target;
2916 sp<InputWindowHandle> windowHandle =
2917 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2918 if (windowHandle != nullptr) {
2919 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2920 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2921 windowInfo->windowXScale, windowInfo->windowYScale);
2922 target.globalScaleFactor = windowInfo->globalScaleFactor;
2923 }
2924 target.inputChannel = connection->inputChannel;
2925 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2926
2927 for (EventEntry* downEventEntry : downEvents) {
2928 switch (downEventEntry->type) {
2929 case EventEntry::Type::MOTION: {
2930 logOutboundMotionDetails("down - ",
2931 static_cast<const MotionEntry&>(*downEventEntry));
2932 break;
2933 }
2934
2935 case EventEntry::Type::KEY:
2936 case EventEntry::Type::FOCUS:
2937 case EventEntry::Type::CONFIGURATION_CHANGED:
2938 case EventEntry::Type::DEVICE_RESET: {
2939 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2940 EventEntry::typeToString(downEventEntry->type));
2941 break;
2942 }
2943 }
2944
2945 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2946 target, InputTarget::FLAG_DISPATCH_AS_IS);
2947
2948 downEventEntry->release();
2949 }
2950
2951 startDispatchCycleLocked(currentTime, connection);
2952}
2953
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002954MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002955 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956 ALOG_ASSERT(pointerIds.value != 0);
2957
2958 uint32_t splitPointerIndexMap[MAX_POINTERS];
2959 PointerProperties splitPointerProperties[MAX_POINTERS];
2960 PointerCoords splitPointerCoords[MAX_POINTERS];
2961
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002962 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002963 uint32_t splitPointerCount = 0;
2964
2965 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002966 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002968 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969 uint32_t pointerId = uint32_t(pointerProperties.id);
2970 if (pointerIds.hasBit(pointerId)) {
2971 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2972 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2973 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002974 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002975 splitPointerCount += 1;
2976 }
2977 }
2978
2979 if (splitPointerCount != pointerIds.count()) {
2980 // This is bad. We are missing some of the pointers that we expected to deliver.
2981 // Most likely this indicates that we received an ACTION_MOVE events that has
2982 // different pointer ids than we expected based on the previous ACTION_DOWN
2983 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2984 // in this way.
2985 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002986 "we expected there to be %d pointers. This probably means we received "
2987 "a broken sequence of pointer ids from the input device.",
2988 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002989 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002990 }
2991
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002992 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002994 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2995 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002996 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2997 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002998 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002999 uint32_t pointerId = uint32_t(pointerProperties.id);
3000 if (pointerIds.hasBit(pointerId)) {
3001 if (pointerIds.count() == 1) {
3002 // The first/last pointer went down/up.
3003 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003004 ? AMOTION_EVENT_ACTION_DOWN
3005 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006 } else {
3007 // A secondary pointer went down/up.
3008 uint32_t splitPointerIndex = 0;
3009 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3010 splitPointerIndex += 1;
3011 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003012 action = maskedAction |
3013 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014 }
3015 } else {
3016 // An unrelated pointer changed.
3017 action = AMOTION_EVENT_ACTION_MOVE;
3018 }
3019 }
3020
Garfield Tan1c7bc862020-01-28 13:24:04 -08003021 int32_t newId = mIdGenerator.nextId();
3022 if (ATRACE_ENABLED()) {
3023 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3024 ") to MotionEvent(id=0x%" PRIx32 ").",
3025 originalMotionEntry.id, newId);
3026 ATRACE_NAME(message.c_str());
3027 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003028 MotionEntry* splitMotionEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08003029 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3030 originalMotionEntry.source, originalMotionEntry.displayId,
3031 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003032 originalMotionEntry.actionButton, originalMotionEntry.flags,
3033 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3034 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3035 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3036 originalMotionEntry.xCursorPosition,
3037 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003038 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003040 if (originalMotionEntry.injectionState) {
3041 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 splitMotionEntry->injectionState->refCount += 1;
3043 }
3044
3045 return splitMotionEntry;
3046}
3047
3048void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3049#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003050 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051#endif
3052
3053 bool needWake;
3054 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003055 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056
Prabir Pradhan42611e02018-11-27 14:04:02 -08003057 ConfigurationChangedEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003058 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059 needWake = enqueueInboundEventLocked(newEntry);
3060 } // release lock
3061
3062 if (needWake) {
3063 mLooper->wake();
3064 }
3065}
3066
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003067/**
3068 * If one of the meta shortcuts is detected, process them here:
3069 * Meta + Backspace -> generate BACK
3070 * Meta + Enter -> generate HOME
3071 * This will potentially overwrite keyCode and metaState.
3072 */
3073void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003074 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003075 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3076 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3077 if (keyCode == AKEYCODE_DEL) {
3078 newKeyCode = AKEYCODE_BACK;
3079 } else if (keyCode == AKEYCODE_ENTER) {
3080 newKeyCode = AKEYCODE_HOME;
3081 }
3082 if (newKeyCode != AKEYCODE_UNKNOWN) {
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 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003086 keyCode = newKeyCode;
3087 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3088 }
3089 } else if (action == AKEY_EVENT_ACTION_UP) {
3090 // In order to maintain a consistent stream of up and down events, check to see if the key
3091 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3092 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003093 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003094 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003095 auto replacementIt = mReplacedKeys.find(replacement);
3096 if (replacementIt != mReplacedKeys.end()) {
3097 keyCode = replacementIt->second;
3098 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003099 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3100 }
3101 }
3102}
3103
Michael Wrightd02c5b62014-02-10 15:10:22 -08003104void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3105#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3107 "policyFlags=0x%x, action=0x%x, "
3108 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3109 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3110 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3111 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112#endif
3113 if (!validateKeyEvent(args->action)) {
3114 return;
3115 }
3116
3117 uint32_t policyFlags = args->policyFlags;
3118 int32_t flags = args->flags;
3119 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003120 // InputDispatcher tracks and generates key repeats on behalf of
3121 // whatever notifies it, so repeatCount should always be set to 0
3122 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003123 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3124 policyFlags |= POLICY_FLAG_VIRTUAL;
3125 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3126 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127 if (policyFlags & POLICY_FLAG_FUNCTION) {
3128 metaState |= AMETA_FUNCTION_ON;
3129 }
3130
3131 policyFlags |= POLICY_FLAG_TRUSTED;
3132
Michael Wright78f24442014-08-06 15:55:28 -07003133 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003134 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003135
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003137 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08003138 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3139 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140
Michael Wright2b3c3302018-03-02 17:19:13 +00003141 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003143 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3144 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003145 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 bool needWake;
3149 { // acquire lock
3150 mLock.lock();
3151
3152 if (shouldSendKeyToInputFilterLocked(args)) {
3153 mLock.unlock();
3154
3155 policyFlags |= POLICY_FLAG_FILTERED;
3156 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3157 return; // event was consumed by the filter
3158 }
3159
3160 mLock.lock();
3161 }
3162
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003163 KeyEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003164 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 args->displayId, policyFlags, args->action, flags, keyCode,
3166 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167
3168 needWake = enqueueInboundEventLocked(newEntry);
3169 mLock.unlock();
3170 } // release lock
3171
3172 if (needWake) {
3173 mLooper->wake();
3174 }
3175}
3176
3177bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3178 return mInputFilterEnabled;
3179}
3180
3181void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3182#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003183 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3184 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003185 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3186 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003187 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003188 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3189 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3190 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3191 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 for (uint32_t i = 0; i < args->pointerCount; i++) {
3193 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003194 "x=%f, y=%f, pressure=%f, size=%f, "
3195 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3196 "orientation=%f",
3197 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3198 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3199 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3200 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3201 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3202 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3203 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3204 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3205 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3206 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 }
3208#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3210 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211 return;
3212 }
3213
3214 uint32_t policyFlags = args->policyFlags;
3215 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003216
3217 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003218 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003219 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3220 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003221 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003222 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223
3224 bool needWake;
3225 { // acquire lock
3226 mLock.lock();
3227
3228 if (shouldSendMotionToInputFilterLocked(args)) {
3229 mLock.unlock();
3230
3231 MotionEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003232 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3233 args->action, args->actionButton, args->flags, args->edgeFlags,
3234 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3235 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3236 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3237 args->downTime, args->eventTime, args->pointerCount,
3238 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239
3240 policyFlags |= POLICY_FLAG_FILTERED;
3241 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3242 return; // event was consumed by the filter
3243 }
3244
3245 mLock.lock();
3246 }
3247
3248 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003249 MotionEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003250 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003251 args->displayId, policyFlags, args->action, args->actionButton,
3252 args->flags, args->metaState, args->buttonState,
3253 args->classification, args->edgeFlags, args->xPrecision,
3254 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3255 args->downTime, args->pointerCount, args->pointerProperties,
3256 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257
3258 needWake = enqueueInboundEventLocked(newEntry);
3259 mLock.unlock();
3260 } // release lock
3261
3262 if (needWake) {
3263 mLooper->wake();
3264 }
3265}
3266
3267bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003268 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269}
3270
3271void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3272#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003273 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003274 "switchMask=0x%08x",
3275 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276#endif
3277
3278 uint32_t policyFlags = args->policyFlags;
3279 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003280 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281}
3282
3283void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3284#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003285 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3286 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287#endif
3288
3289 bool needWake;
3290 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003291 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292
Prabir Pradhan42611e02018-11-27 14:04:02 -08003293 DeviceResetEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003294 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295 needWake = enqueueInboundEventLocked(newEntry);
3296 } // release lock
3297
3298 if (needWake) {
3299 mLooper->wake();
3300 }
3301}
3302
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003303int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3304 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003305 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306#if DEBUG_INBOUND_EVENT_DETAILS
3307 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003308 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3309 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310#endif
3311
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003312 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313
3314 policyFlags |= POLICY_FLAG_INJECTED;
3315 if (hasInjectionPermission(injectorPid, injectorUid)) {
3316 policyFlags |= POLICY_FLAG_TRUSTED;
3317 }
3318
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003319 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003321 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003322 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3323 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003324 if (!validateKeyEvent(action)) {
3325 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003326 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003328 int32_t flags = incomingKey.getFlags();
3329 int32_t keyCode = incomingKey.getKeyCode();
3330 int32_t metaState = incomingKey.getMetaState();
3331 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003332 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003333 KeyEvent keyEvent;
Garfield Tanfbe732e2020-01-24 11:26:14 -08003334 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003335 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3336 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3337 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3340 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003341 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003342
3343 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3344 android::base::Timer t;
3345 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3346 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3347 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3348 std::to_string(t.duration().count()).c_str());
3349 }
3350 }
3351
3352 mLock.lock();
3353 KeyEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003354 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3355 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003356 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3357 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tanfbe732e2020-01-24 11:26:14 -08003358 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003359 injectedEntries.push(injectedEntry);
3360 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361 }
3362
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003363 case AINPUT_EVENT_TYPE_MOTION: {
3364 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3365 int32_t action = motionEvent->getAction();
3366 size_t pointerCount = motionEvent->getPointerCount();
3367 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3368 int32_t actionButton = motionEvent->getActionButton();
3369 int32_t displayId = motionEvent->getDisplayId();
3370 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3371 return INPUT_EVENT_INJECTION_FAILED;
3372 }
3373
3374 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3375 nsecs_t eventTime = motionEvent->getEventTime();
3376 android::base::Timer t;
3377 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3378 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3379 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3380 std::to_string(t.duration().count()).c_str());
3381 }
3382 }
3383
3384 mLock.lock();
3385 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3386 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3387 MotionEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003388 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3389 motionEvent->getSource(), motionEvent->getDisplayId(),
3390 policyFlags, action, actionButton, motionEvent->getFlags(),
3391 motionEvent->getMetaState(), motionEvent->getButtonState(),
3392 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3393 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003394 motionEvent->getRawXCursorPosition(),
3395 motionEvent->getRawYCursorPosition(),
3396 motionEvent->getDownTime(), uint32_t(pointerCount),
3397 pointerProperties, samplePointerCoords,
3398 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003399 injectedEntries.push(injectedEntry);
3400 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3401 sampleEventTimes += 1;
3402 samplePointerCoords += pointerCount;
3403 MotionEntry* nextInjectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003404 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003405 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003406 motionEvent->getDisplayId(), policyFlags, action,
3407 actionButton, motionEvent->getFlags(),
3408 motionEvent->getMetaState(), motionEvent->getButtonState(),
3409 motionEvent->getClassification(),
3410 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3411 motionEvent->getYPrecision(),
3412 motionEvent->getRawXCursorPosition(),
3413 motionEvent->getRawYCursorPosition(),
3414 motionEvent->getDownTime(), uint32_t(pointerCount),
3415 pointerProperties, samplePointerCoords,
3416 motionEvent->getXOffset(), motionEvent->getYOffset());
3417 injectedEntries.push(nextInjectedEntry);
3418 }
3419 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003422 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003423 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003424 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 }
3426
3427 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3428 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3429 injectionState->injectionIsAsync = true;
3430 }
3431
3432 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003433 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434
3435 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003436 while (!injectedEntries.empty()) {
3437 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3438 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439 }
3440
3441 mLock.unlock();
3442
3443 if (needWake) {
3444 mLooper->wake();
3445 }
3446
3447 int32_t injectionResult;
3448 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003449 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450
3451 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3452 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3453 } else {
3454 for (;;) {
3455 injectionResult = injectionState->injectionResult;
3456 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3457 break;
3458 }
3459
3460 nsecs_t remainingTimeout = endTime - now();
3461 if (remainingTimeout <= 0) {
3462#if DEBUG_INJECTION
3463 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003464 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465#endif
3466 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3467 break;
3468 }
3469
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003470 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 }
3472
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003473 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3474 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 while (injectionState->pendingForegroundDispatches != 0) {
3476#if DEBUG_INJECTION
3477 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003478 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479#endif
3480 nsecs_t remainingTimeout = endTime - now();
3481 if (remainingTimeout <= 0) {
3482#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003483 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3484 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485#endif
3486 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3487 break;
3488 }
3489
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003490 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491 }
3492 }
3493 }
3494
3495 injectionState->release();
3496 } // release lock
3497
3498#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003499 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003500 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501#endif
3502
3503 return injectionResult;
3504}
3505
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003506std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003507 std::array<uint8_t, 32> calculatedHmac;
3508 std::unique_ptr<VerifiedInputEvent> result;
3509 switch (event.getType()) {
3510 case AINPUT_EVENT_TYPE_KEY: {
3511 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3512 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3513 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3514 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3515 break;
3516 }
3517 case AINPUT_EVENT_TYPE_MOTION: {
3518 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3519 VerifiedMotionEvent verifiedMotionEvent =
3520 verifiedMotionEventFromMotionEvent(motionEvent);
3521 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3522 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3523 break;
3524 }
3525 default: {
3526 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3527 return nullptr;
3528 }
3529 }
3530 if (calculatedHmac == INVALID_HMAC) {
3531 return nullptr;
3532 }
3533 if (calculatedHmac != event.getHmac()) {
3534 return nullptr;
3535 }
3536 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003537}
3538
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003540 return injectorUid == 0 ||
3541 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542}
3543
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003544void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 InjectionState* injectionState = entry->injectionState;
3546 if (injectionState) {
3547#if DEBUG_INJECTION
3548 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003549 "injectorPid=%d, injectorUid=%d",
3550 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551#endif
3552
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003553 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554 // Log the outcome since the injector did not wait for the injection result.
3555 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003556 case INPUT_EVENT_INJECTION_SUCCEEDED:
3557 ALOGV("Asynchronous input event injection succeeded.");
3558 break;
3559 case INPUT_EVENT_INJECTION_FAILED:
3560 ALOGW("Asynchronous input event injection failed.");
3561 break;
3562 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3563 ALOGW("Asynchronous input event injection permission denied.");
3564 break;
3565 case INPUT_EVENT_INJECTION_TIMED_OUT:
3566 ALOGW("Asynchronous input event injection timed out.");
3567 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003568 }
3569 }
3570
3571 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003572 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573 }
3574}
3575
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003576void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577 InjectionState* injectionState = entry->injectionState;
3578 if (injectionState) {
3579 injectionState->pendingForegroundDispatches += 1;
3580 }
3581}
3582
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003583void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584 InjectionState* injectionState = entry->injectionState;
3585 if (injectionState) {
3586 injectionState->pendingForegroundDispatches -= 1;
3587
3588 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003589 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590 }
3591 }
3592}
3593
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003594std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3595 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003596 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003597}
3598
Siarhei Vishniakou265ab012020-09-08 19:43:33 -05003599sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3600 return getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3601}
3602
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003604 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003605 if (windowHandleToken == nullptr) {
3606 return nullptr;
3607 }
3608
Arthur Hungb92218b2018-08-14 12:00:21 +08003609 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003610 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3611 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003612 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003613 return windowHandle;
3614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 }
3616 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003617 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618}
3619
Mady Mellor017bcd12020-06-23 19:12:00 +00003620bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3621 for (auto& it : mWindowHandlesByDisplay) {
3622 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3623 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003624 if (handle->getId() == windowHandle->getId() &&
3625 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003626 if (windowHandle->getInfo()->displayId != it.first) {
3627 ALOGE("Found window %s in display %" PRId32
3628 ", but it should belong to display %" PRId32,
3629 windowHandle->getName().c_str(), it.first,
3630 windowHandle->getInfo()->displayId);
3631 }
3632 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003633 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 }
3635 }
3636 return false;
3637}
3638
Robert Carr5c8a0262018-10-03 16:30:44 -07003639sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3640 size_t count = mInputChannelsByToken.count(token);
3641 if (count == 0) {
3642 return nullptr;
3643 }
3644 return mInputChannelsByToken.at(token);
3645}
3646
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003647void InputDispatcher::updateWindowHandlesForDisplayLocked(
3648 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3649 if (inputWindowHandles.empty()) {
3650 // Remove all handles on a display if there are no windows left.
3651 mWindowHandlesByDisplay.erase(displayId);
3652 return;
3653 }
3654
3655 // Since we compare the pointer of input window handles across window updates, we need
3656 // to make sure the handle object for the same window stays unchanged across updates.
3657 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003658 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003659 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003660 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003661 }
3662
3663 std::vector<sp<InputWindowHandle>> newHandles;
3664 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3665 if (!handle->updateInfo()) {
3666 // handle no longer valid
3667 continue;
3668 }
3669
3670 const InputWindowInfo* info = handle->getInfo();
3671 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3672 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3673 const bool noInputChannel =
3674 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3675 const bool canReceiveInput =
3676 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3677 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3678 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003679 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003680 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003681 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003682 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003683 }
3684
3685 if (info->displayId != displayId) {
3686 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3687 handle->getName().c_str(), displayId, info->displayId);
3688 continue;
3689 }
3690
Robert Carredd13602020-04-13 17:24:34 -07003691 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3692 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003693 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003694 oldHandle->updateFrom(handle);
3695 newHandles.push_back(oldHandle);
3696 } else {
3697 newHandles.push_back(handle);
3698 }
3699 }
3700
3701 // Insert or replace
3702 mWindowHandlesByDisplay[displayId] = newHandles;
3703}
3704
Arthur Hung72d8dc32020-03-28 00:48:39 +00003705void InputDispatcher::setInputWindows(
3706 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3707 { // acquire lock
3708 std::scoped_lock _l(mLock);
3709 for (auto const& i : handlesPerDisplay) {
3710 setInputWindowsLocked(i.second, i.first);
3711 }
3712 }
3713 // Wake up poll loop since it may need to make new input dispatching choices.
3714 mLooper->wake();
3715}
3716
Arthur Hungb92218b2018-08-14 12:00:21 +08003717/**
3718 * Called from InputManagerService, update window handle list by displayId that can receive input.
3719 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3720 * If set an empty list, remove all handles from the specific display.
3721 * For focused handle, check if need to change and send a cancel event to previous one.
3722 * For removed handle, check if need to send a cancel event if already in touch.
3723 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003724void InputDispatcher::setInputWindowsLocked(
3725 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003726 if (DEBUG_FOCUS) {
3727 std::string windowList;
3728 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3729 windowList += iwh->getName() + " ";
3730 }
3731 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733
Arthur Hung72d8dc32020-03-28 00:48:39 +00003734 // Copy old handles for release if they are no longer present.
3735 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736
Arthur Hung72d8dc32020-03-28 00:48:39 +00003737 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003738
Arthur Hung72d8dc32020-03-28 00:48:39 +00003739 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3740 bool foundHoveredWindow = false;
3741 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3742 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3743 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3744 windowHandle->getInfo()->visible) {
3745 newFocusedWindowHandle = windowHandle;
3746 }
3747 if (windowHandle == mLastHoverWindowHandle) {
3748 foundHoveredWindow = true;
3749 }
3750 }
3751
3752 if (!foundHoveredWindow) {
3753 mLastHoverWindowHandle = nullptr;
3754 }
3755
3756 sp<InputWindowHandle> oldFocusedWindowHandle =
3757 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3758
3759 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3760 if (oldFocusedWindowHandle != nullptr) {
3761 if (DEBUG_FOCUS) {
3762 ALOGD("Focus left window: %s in display %" PRId32,
3763 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003764 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003765 sp<InputChannel> focusedInputChannel =
3766 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3767 if (focusedInputChannel != nullptr) {
3768 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3769 "focus left window");
3770 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3771 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003772 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003773 mFocusedWindowHandlesByDisplay.erase(displayId);
3774 }
3775 if (newFocusedWindowHandle != nullptr) {
3776 if (DEBUG_FOCUS) {
3777 ALOGD("Focus entered window: %s in display %" PRId32,
3778 newFocusedWindowHandle->getName().c_str(), displayId);
3779 }
3780 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3781 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 }
3783
Arthur Hung72d8dc32020-03-28 00:48:39 +00003784 if (mFocusedDisplayId == displayId) {
3785 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003789 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3790 mTouchStatesByDisplay.find(displayId);
3791 if (stateIt != mTouchStatesByDisplay.end()) {
3792 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003793 for (size_t i = 0; i < state.windows.size();) {
3794 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003795 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003796 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003797 ALOGD("Touched window was removed: %s in display %" PRId32,
3798 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003799 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003800 sp<InputChannel> touchedInputChannel =
3801 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3802 if (touchedInputChannel != nullptr) {
3803 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3804 "touched window was removed");
3805 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003807 state.windows.erase(state.windows.begin() + i);
3808 } else {
3809 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 }
3811 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003812 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003813
Arthur Hung72d8dc32020-03-28 00:48:39 +00003814 // Release information for windows that are no longer present.
3815 // This ensures that unused input channels are released promptly.
3816 // Otherwise, they might stick around until the window handle is destroyed
3817 // which might not happen until the next GC.
3818 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003819 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003820 if (DEBUG_FOCUS) {
3821 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003822 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003823 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003824 }
chaviw291d88a2019-02-14 10:33:58 -08003825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826}
3827
3828void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003829 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003830 if (DEBUG_FOCUS) {
3831 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3832 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003835 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836
Tiger Huang721e26f2018-07-24 22:26:19 +08003837 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3838 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07003839
3840 if (oldFocusedApplicationHandle == mAwaitedFocusedApplication &&
3841 inputApplicationHandle != oldFocusedApplicationHandle) {
3842 resetNoFocusedWindowTimeoutLocked();
3843 }
3844
Yi Kong9b14ac62018-07-17 13:48:38 -07003845 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003846 if (oldFocusedApplicationHandle != inputApplicationHandle) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003847 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003849 } else if (oldFocusedApplicationHandle != nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003850 oldFocusedApplicationHandle.clear();
3851 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853 } // release lock
3854
3855 // Wake up poll loop since it may need to make new input dispatching choices.
3856 mLooper->wake();
3857}
3858
Tiger Huang721e26f2018-07-24 22:26:19 +08003859/**
3860 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3861 * the display not specified.
3862 *
3863 * We track any unreleased events for each window. If a window loses the ability to receive the
3864 * released event, we will send a cancel event to it. So when the focused display is changed, we
3865 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3866 * display. The display-specified events won't be affected.
3867 */
3868void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003869 if (DEBUG_FOCUS) {
3870 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3871 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003872 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003873 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003874
3875 if (mFocusedDisplayId != displayId) {
3876 sp<InputWindowHandle> oldFocusedWindowHandle =
3877 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3878 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003879 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003880 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003881 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003882 CancelationOptions
3883 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3884 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003885 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003886 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3887 }
3888 }
3889 mFocusedDisplayId = displayId;
3890
3891 // Sanity check
3892 sp<InputWindowHandle> newFocusedWindowHandle =
3893 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003894 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003895
Tiger Huang721e26f2018-07-24 22:26:19 +08003896 if (newFocusedWindowHandle == nullptr) {
3897 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3898 if (!mFocusedWindowHandlesByDisplay.empty()) {
3899 ALOGE("But another display has a focused window:");
3900 for (auto& it : mFocusedWindowHandlesByDisplay) {
3901 const int32_t displayId = it.first;
3902 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003903 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3904 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003905 }
3906 }
3907 }
3908 }
3909
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003910 if (DEBUG_FOCUS) {
3911 logDispatchStateLocked();
3912 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003913 } // release lock
3914
3915 // Wake up poll loop since it may need to make new input dispatching choices.
3916 mLooper->wake();
3917}
3918
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003920 if (DEBUG_FOCUS) {
3921 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923
3924 bool changed;
3925 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003926 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927
3928 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3929 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07003930 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 }
3932
3933 if (mDispatchEnabled && !enabled) {
3934 resetAndDropEverythingLocked("dispatcher is being disabled");
3935 }
3936
3937 mDispatchEnabled = enabled;
3938 mDispatchFrozen = frozen;
3939 changed = true;
3940 } else {
3941 changed = false;
3942 }
3943
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003944 if (DEBUG_FOCUS) {
3945 logDispatchStateLocked();
3946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 } // release lock
3948
3949 if (changed) {
3950 // Wake up poll loop since it may need to make new input dispatching choices.
3951 mLooper->wake();
3952 }
3953}
3954
3955void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003956 if (DEBUG_FOCUS) {
3957 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3958 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959
3960 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003961 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962
3963 if (mInputFilterEnabled == enabled) {
3964 return;
3965 }
3966
3967 mInputFilterEnabled = enabled;
3968 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3969 } // release lock
3970
3971 // Wake up poll loop since there might be work to do to drop everything.
3972 mLooper->wake();
3973}
3974
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003975void InputDispatcher::setInTouchMode(bool inTouchMode) {
3976 std::scoped_lock lock(mLock);
3977 mInTouchMode = inTouchMode;
3978}
3979
chaviwfbe5d9c2018-12-26 12:23:37 -08003980bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3981 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003982 if (DEBUG_FOCUS) {
3983 ALOGD("Trivial transfer to same window.");
3984 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003985 return true;
3986 }
3987
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003989 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990
chaviwfbe5d9c2018-12-26 12:23:37 -08003991 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3992 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003993 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003994 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 return false;
3996 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003997 if (DEBUG_FOCUS) {
3998 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3999 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004002 if (DEBUG_FOCUS) {
4003 ALOGD("Cannot transfer focus because windows are on different displays.");
4004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 return false;
4006 }
4007
4008 bool found = false;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004009 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4010 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004011 for (size_t i = 0; i < state.windows.size(); i++) {
4012 const TouchedWindow& touchedWindow = state.windows[i];
4013 if (touchedWindow.windowHandle == fromWindowHandle) {
4014 int32_t oldTargetFlags = touchedWindow.targetFlags;
4015 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004017 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004019 int32_t newTargetFlags = oldTargetFlags &
4020 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4021 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004022 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023
Jeff Brownf086ddb2014-02-11 14:28:48 -08004024 found = true;
4025 goto Found;
4026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027 }
4028 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004029 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004031 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004032 if (DEBUG_FOCUS) {
4033 ALOGD("Focus transfer failed because from window did not have focus.");
4034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035 return false;
4036 }
4037
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004038 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4039 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004040 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004041 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004042 CancelationOptions
4043 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4044 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004046 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047 }
4048
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004049 if (DEBUG_FOCUS) {
4050 logDispatchStateLocked();
4051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052 } // release lock
4053
4054 // Wake up poll loop since it may need to make new input dispatching choices.
4055 mLooper->wake();
4056 return true;
4057}
4058
4059void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004060 if (DEBUG_FOCUS) {
4061 ALOGD("Resetting and dropping all events (%s).", reason);
4062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063
4064 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4065 synthesizeCancelationEventsForAllConnectionsLocked(options);
4066
4067 resetKeyRepeatLocked();
4068 releasePendingEventLocked();
4069 drainInboundQueueLocked();
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004070 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004072 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004073 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004075 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076}
4077
4078void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004079 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080 dumpDispatchStateLocked(dump);
4081
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004082 std::istringstream stream(dump);
4083 std::string line;
4084
4085 while (std::getline(stream, line, '\n')) {
4086 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 }
4088}
4089
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004090void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004091 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4092 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4093 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004094 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095
Tiger Huang721e26f2018-07-24 22:26:19 +08004096 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4097 dump += StringPrintf(INDENT "FocusedApplications:\n");
4098 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4099 const int32_t displayId = it.first;
4100 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004101 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004102 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004103 displayId, applicationHandle->getName().c_str(),
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004104 ns2ms(applicationHandle
4105 ->getDispatchingTimeout(
4106 DEFAULT_INPUT_DISPATCHING_TIMEOUT)
4107 .count()));
Tiger Huang721e26f2018-07-24 22:26:19 +08004108 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004110 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004112
4113 if (!mFocusedWindowHandlesByDisplay.empty()) {
4114 dump += StringPrintf(INDENT "FocusedWindows:\n");
4115 for (auto& it : mFocusedWindowHandlesByDisplay) {
4116 const int32_t displayId = it.first;
4117 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004118 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4119 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004120 }
4121 } else {
4122 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004125 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004126 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004127 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4128 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004129 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004130 state.displayId, toString(state.down), toString(state.split),
4131 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004132 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004133 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004134 for (size_t i = 0; i < state.windows.size(); i++) {
4135 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004136 dump += StringPrintf(INDENT4
4137 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4138 i, touchedWindow.windowHandle->getName().c_str(),
4139 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004140 }
4141 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004142 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004143 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004144 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004145 dump += INDENT3 "Portal windows:\n";
4146 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004147 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004148 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4149 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004150 }
4151 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152 }
4153 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004154 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 }
4156
Arthur Hungb92218b2018-08-14 12:00:21 +08004157 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004158 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004159 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004160 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004161 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004162 dump += INDENT2 "Windows:\n";
4163 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004164 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004165 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166
Arthur Hungb92218b2018-08-14 12:00:21 +08004167 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004168 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004169 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4170 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004171 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004172 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004173 i, windowInfo->name.c_str(), windowInfo->displayId,
4174 windowInfo->portalToDisplayId,
4175 toString(windowInfo->paused),
4176 toString(windowInfo->hasFocus),
4177 toString(windowInfo->hasWallpaper),
4178 toString(windowInfo->visible),
4179 toString(windowInfo->canReceiveKeys),
4180 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004181 windowInfo->layoutParamsType, windowInfo->frameLeft,
4182 windowInfo->frameTop, windowInfo->frameRight,
4183 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4184 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004185 dumpRegion(dump, windowInfo->touchableRegion);
4186 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004187 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4188 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004189 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004190 ns2ms(windowInfo->dispatchingTimeout));
Arthur Hungb92218b2018-08-14 12:00:21 +08004191 }
4192 } else {
4193 dump += INDENT2 "Windows: <none>\n";
4194 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 }
4196 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004197 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 }
4199
Michael Wright3dd60e22019-03-27 22:06:44 +00004200 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004202 const std::vector<Monitor>& monitors = it.second;
4203 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4204 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004205 }
4206 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004207 const std::vector<Monitor>& monitors = it.second;
4208 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4209 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004212 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 }
4214
4215 nsecs_t currentTime = now();
4216
4217 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004218 if (!mRecentQueue.empty()) {
4219 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4220 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004221 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004223 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224 }
4225 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004226 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 }
4228
4229 // Dump event currently being dispatched.
4230 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004231 dump += INDENT "PendingEvent:\n";
4232 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004234 dump += StringPrintf(", age=%" PRId64 "ms\n",
4235 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004237 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 }
4239
4240 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004241 if (!mInboundQueue.empty()) {
4242 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4243 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004244 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004246 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 }
4248 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004249 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 }
4251
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004252 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004253 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004254 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4255 const KeyReplacement& replacement = pair.first;
4256 int32_t newKeyCode = pair.second;
4257 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004258 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004259 }
4260 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004261 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004262 }
4263
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004264 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004265 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004266 for (const auto& pair : mConnectionsByFd) {
4267 const sp<Connection>& connection = pair.second;
4268 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004269 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004270 pair.first, connection->getInputChannelName().c_str(),
4271 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004272 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004274 if (!connection->outboundQueue.empty()) {
4275 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4276 connection->outboundQueue.size());
4277 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 dump.append(INDENT4);
4279 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004280 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4281 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004282 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004283 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 }
4285 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004286 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 }
4288
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004289 if (!connection->waitQueue.empty()) {
4290 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4291 connection->waitQueue.size());
4292 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004293 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004295 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004296 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004297 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004298 ns2ms(currentTime - entry->eventEntry->eventTime),
4299 ns2ms(currentTime - entry->deliveryTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 }
4301 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004302 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303 }
4304 }
4305 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004306 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 }
4308
4309 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004310 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4311 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004313 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 }
4315
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004316 dump += INDENT "Configuration:\n";
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004317 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4318 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4319 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320}
4321
Michael Wright3dd60e22019-03-27 22:06:44 +00004322void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4323 const size_t numMonitors = monitors.size();
4324 for (size_t i = 0; i < numMonitors; i++) {
4325 const Monitor& monitor = monitors[i];
4326 const sp<InputChannel>& channel = monitor.inputChannel;
4327 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4328 dump += "\n";
4329 }
4330}
4331
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004332status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004334 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335#endif
4336
4337 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004338 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004339 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004340 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004342 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 return BAD_VALUE;
4344 }
4345
Garfield Tan1c7bc862020-01-28 13:24:04 -08004346 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347
4348 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004349 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004350 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4353 } // release lock
4354
4355 // Wake the looper because some connections have changed.
4356 mLooper->wake();
4357 return OK;
4358}
4359
Michael Wright3dd60e22019-03-27 22:06:44 +00004360status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004361 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004362 { // acquire lock
4363 std::scoped_lock _l(mLock);
4364
4365 if (displayId < 0) {
4366 ALOGW("Attempted to register input monitor without a specified display.");
4367 return BAD_VALUE;
4368 }
4369
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004370 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004371 ALOGW("Attempted to register input monitor without an identifying token.");
4372 return BAD_VALUE;
4373 }
4374
Garfield Tan1c7bc862020-01-28 13:24:04 -08004375 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004376
4377 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004378 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004379 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004380
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004381 auto& monitorsByDisplay =
4382 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004383 monitorsByDisplay[displayId].emplace_back(inputChannel);
4384
4385 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004386 }
4387 // Wake the looper because some connections have changed.
4388 mLooper->wake();
4389 return OK;
4390}
4391
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4393#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004394 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395#endif
4396
4397 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004398 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399
4400 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4401 if (status) {
4402 return status;
4403 }
4404 } // release lock
4405
4406 // Wake the poll loop because removing the connection may have changed the current
4407 // synchronization state.
4408 mLooper->wake();
4409 return OK;
4410}
4411
4412status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004413 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004414 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004415 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004417 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418 return BAD_VALUE;
4419 }
4420
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004421 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004422 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004423
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424 if (connection->monitor) {
4425 removeMonitorChannelLocked(inputChannel);
4426 }
4427
4428 mLooper->removeFd(inputChannel->getFd());
4429
4430 nsecs_t currentTime = now();
4431 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4432
4433 connection->status = Connection::STATUS_ZOMBIE;
4434 return OK;
4435}
4436
4437void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004438 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4439 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4440}
4441
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004442void InputDispatcher::removeMonitorChannelLocked(
4443 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004444 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004445 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004446 std::vector<Monitor>& monitors = it->second;
4447 const size_t numMonitors = monitors.size();
4448 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004449 if (monitors[i].inputChannel == inputChannel) {
4450 monitors.erase(monitors.begin() + i);
4451 break;
4452 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004453 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004454 if (monitors.empty()) {
4455 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004456 } else {
4457 ++it;
4458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 }
4460}
4461
Michael Wright3dd60e22019-03-27 22:06:44 +00004462status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4463 { // acquire lock
4464 std::scoped_lock _l(mLock);
4465 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4466
4467 if (!foundDisplayId) {
4468 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4469 return BAD_VALUE;
4470 }
4471 int32_t displayId = foundDisplayId.value();
4472
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004473 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4474 mTouchStatesByDisplay.find(displayId);
4475 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004476 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4477 return BAD_VALUE;
4478 }
4479
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004480 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004481 std::optional<int32_t> foundDeviceId;
4482 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004483 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004484 foundDeviceId = state.deviceId;
4485 }
4486 }
4487 if (!foundDeviceId || !state.down) {
4488 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004489 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004490 return BAD_VALUE;
4491 }
4492 int32_t deviceId = foundDeviceId.value();
4493
4494 // Send cancel events to all the input channels we're stealing from.
4495 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004496 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004497 options.deviceId = deviceId;
4498 options.displayId = displayId;
4499 for (const TouchedWindow& window : state.windows) {
4500 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004501 if (channel != nullptr) {
4502 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4503 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004504 }
4505 // Then clear the current touch state so we stop dispatching to them as well.
4506 state.filterNonMonitors();
4507 }
4508 return OK;
4509}
4510
Michael Wright3dd60e22019-03-27 22:06:44 +00004511std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4512 const sp<IBinder>& token) {
4513 for (const auto& it : mGestureMonitorsByDisplay) {
4514 const std::vector<Monitor>& monitors = it.second;
4515 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004516 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004517 return it.first;
4518 }
4519 }
4520 }
4521 return std::nullopt;
4522}
4523
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004524sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004525 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004526 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004527 }
4528
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004529 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004530 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004531 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004532 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533 }
4534 }
Robert Carr4e670e52018-08-15 13:26:12 -07004535
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004536 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537}
4538
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004539void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004540 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004541 removeByValue(mConnectionsByFd, connection);
4542}
4543
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004544void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4545 const sp<Connection>& connection, uint32_t seq,
4546 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004547 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4548 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 commandEntry->connection = connection;
4550 commandEntry->eventTime = currentTime;
4551 commandEntry->seq = seq;
4552 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004553 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554}
4555
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004556void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4557 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004559 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004561 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4562 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004564 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565}
4566
chaviw0c06c6e2019-01-09 13:27:07 -08004567void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004568 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004569 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4570 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004571 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4572 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004573 commandEntry->oldToken = oldToken;
4574 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004575 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004576}
4577
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004578void InputDispatcher::onAnrLocked(const Connection& connection) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004579 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4580 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004581 if (connection.waitQueue.empty()) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004582 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004583 connection.inputChannel->getName().c_str());
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004584 return;
4585 }
4586 /**
4587 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4588 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4589 * has changed. This could cause newer entries to time out before the already dispatched
4590 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4591 * processes the events linearly. So providing information about the oldest entry seems to be
4592 * most useful.
4593 */
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004594 DispatchEntry* oldestEntry = *connection.waitQueue.begin();
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004595 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4596 std::string reason =
4597 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004598 connection.inputChannel->getName().c_str(),
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004599 ns2ms(currentWait),
4600 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004602 updateLastAnrStateLocked(getWindowHandleLocked(connection.inputChannel->getConnectionToken()),
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004603 reason);
4604
4605 std::unique_ptr<CommandEntry> commandEntry =
4606 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4607 commandEntry->inputApplicationHandle = nullptr;
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004608 commandEntry->inputChannel = connection.inputChannel;
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004609 commandEntry->reason = std::move(reason);
4610 postCommandLocked(std::move(commandEntry));
4611}
4612
4613void InputDispatcher::onAnrLocked(const sp<InputApplicationHandle>& application) {
4614 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4615 application->getName().c_str());
4616
4617 updateLastAnrStateLocked(application, reason);
4618
4619 std::unique_ptr<CommandEntry> commandEntry =
4620 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4621 commandEntry->inputApplicationHandle = application;
4622 commandEntry->inputChannel = nullptr;
4623 commandEntry->reason = std::move(reason);
4624 postCommandLocked(std::move(commandEntry));
4625}
4626
4627void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4628 const std::string& reason) {
4629 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4630 updateLastAnrStateLocked(windowLabel, reason);
4631}
4632
4633void InputDispatcher::updateLastAnrStateLocked(const sp<InputApplicationHandle>& application,
4634 const std::string& reason) {
4635 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4636 updateLastAnrStateLocked(windowLabel, reason);
4637}
4638
4639void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4640 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004642 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643 struct tm tm;
4644 localtime_r(&t, &tm);
4645 char timestr[64];
4646 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004647 mLastAnrState.clear();
4648 mLastAnrState += INDENT "ANR:\n";
4649 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004650 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4651 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004652 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653}
4654
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004655void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656 mLock.unlock();
4657
4658 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4659
4660 mLock.lock();
4661}
4662
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004663void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004664 sp<Connection> connection = commandEntry->connection;
4665
4666 if (connection->status != Connection::STATUS_ZOMBIE) {
4667 mLock.unlock();
4668
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004669 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004670
4671 mLock.lock();
4672 }
4673}
4674
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004675void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004676 sp<IBinder> oldToken = commandEntry->oldToken;
4677 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004678 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004679 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004680 mLock.lock();
4681}
4682
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004683void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004684 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004685 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686 mLock.unlock();
4687
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004688 const nsecs_t timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004689 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690
4691 mLock.lock();
4692
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004693 if (timeoutExtension > 0) {
4694 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4695 } else {
4696 // stop waking up for events in this connection, it is already not responding
4697 sp<Connection> connection = getConnectionLocked(token);
4698 if (connection == nullptr) {
4699 return;
4700 }
4701 cancelEventsForAnrLocked(connection);
4702 }
4703}
4704
4705void InputDispatcher::extendAnrTimeoutsLocked(const sp<InputApplicationHandle>& application,
4706 const sp<IBinder>& connectionToken,
4707 nsecs_t timeoutExtension) {
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004708 if (connectionToken == nullptr && application != nullptr) {
4709 // The ANR happened because there's no focused window
4710 mNoFocusedWindowTimeoutTime = now() + timeoutExtension;
4711 mAwaitedFocusedApplication = application;
4712 }
4713
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004714 sp<Connection> connection = getConnectionLocked(connectionToken);
4715 if (connection == nullptr) {
Siarhei Vishniakou4e219792020-09-22 21:43:09 -05004716 // It's possible that the connection already disappeared. No action necessary.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004717 return;
4718 }
4719
4720 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
4721 connection->inputChannel->getName().c_str(), ns2ms(timeoutExtension));
4722
4723 connection->responsive = true;
4724 const nsecs_t newTimeout = now() + timeoutExtension;
4725 for (DispatchEntry* entry : connection->waitQueue) {
4726 if (newTimeout >= entry->timeoutTime) {
4727 // Already removed old entries when connection was marked unresponsive
4728 entry->timeoutTime = newTimeout;
4729 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4730 }
4731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732}
4733
4734void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4735 CommandEntry* commandEntry) {
4736 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004737 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738
4739 mLock.unlock();
4740
Michael Wright2b3c3302018-03-02 17:19:13 +00004741 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004742 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004743 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004744 : nullptr;
4745 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004746 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4747 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004748 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750
4751 mLock.lock();
4752
4753 if (delay < 0) {
4754 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4755 } else if (!delay) {
4756 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4757 } else {
4758 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4759 entry->interceptKeyWakeupTime = now() + delay;
4760 }
4761 entry->release();
4762}
4763
chaviwfd6d3512019-03-25 13:23:49 -07004764void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4765 mLock.unlock();
4766 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4767 mLock.lock();
4768}
4769
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004770/**
4771 * Connection is responsive if it has no events in the waitQueue that are older than the
4772 * current time.
4773 */
4774static bool isConnectionResponsive(const Connection& connection) {
4775 const nsecs_t currentTime = now();
4776 for (const DispatchEntry* entry : connection.waitQueue) {
4777 if (entry->timeoutTime < currentTime) {
4778 return false;
4779 }
4780 }
4781 return true;
4782}
4783
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004784void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004786 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004788 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789
4790 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004791 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004792 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004793 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004795 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004796 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004797 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004798 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4799 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004800 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004801 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004802
4803 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004804 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004805 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4806 restartEvent =
4807 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004808 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004809 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4810 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4811 handled);
4812 } else {
4813 restartEvent = false;
4814 }
4815
4816 // Dequeue the event and start the next cycle.
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004817 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004818 // contents of the wait queue to have been drained, so we need to double-check
4819 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004820 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4821 if (dispatchEntryIt != connection->waitQueue.end()) {
4822 dispatchEntry = *dispatchEntryIt;
4823 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004824 mAnrTracker.erase(dispatchEntry->timeoutTime,
4825 connection->inputChannel->getConnectionToken());
4826 if (!connection->responsive) {
4827 connection->responsive = isConnectionResponsive(*connection);
4828 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004829 traceWaitQueueLength(connection);
4830 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004831 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004832 traceOutboundQueueLength(connection);
4833 } else {
4834 releaseDispatchEntry(dispatchEntry);
4835 }
4836 }
4837
4838 // Start the next dispatch cycle for this connection.
4839 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840}
4841
4842bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004843 DispatchEntry* dispatchEntry,
4844 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004845 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004846 if (!handled) {
4847 // Report the key as unhandled, since the fallback was not handled.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004848 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004849 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004850 return false;
4851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004853 // Get the fallback key state.
4854 // Clear it out after dispatching the UP.
4855 int32_t originalKeyCode = keyEntry->keyCode;
4856 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4857 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4858 connection->inputState.removeFallbackKey(originalKeyCode);
4859 }
4860
4861 if (handled || !dispatchEntry->hasForegroundTarget()) {
4862 // If the application handles the original key for which we previously
4863 // generated a fallback or if the window is not a foreground window,
4864 // then cancel the associated fallback key, if any.
4865 if (fallbackKeyCode != -1) {
4866 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004868 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004869 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4870 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4871 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004872#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004873 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004874 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875
4876 mLock.unlock();
4877
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004878 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004879 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880
4881 mLock.lock();
4882
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004883 // Cancel the fallback key.
4884 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004886 "application handled the original non-fallback key "
4887 "or is no longer a foreground target, "
4888 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 options.keyCode = fallbackKeyCode;
4890 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004892 connection->inputState.removeFallbackKey(originalKeyCode);
4893 }
4894 } else {
4895 // If the application did not handle a non-fallback key, first check
4896 // that we are in a good state to perform unhandled key event processing
4897 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004898 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004899 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004901 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004902 "since this is not an initial down. "
4903 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4904 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004906 return false;
4907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004909 // Dispatch the unhandled key to the policy.
4910#if DEBUG_OUTBOUND_EVENT_DETAILS
4911 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004912 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4913 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004914#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004915 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004916
4917 mLock.unlock();
4918
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004919 bool fallback =
4920 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4921 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004922
4923 mLock.lock();
4924
4925 if (connection->status != Connection::STATUS_NORMAL) {
4926 connection->inputState.removeFallbackKey(originalKeyCode);
4927 return false;
4928 }
4929
4930 // Latch the fallback keycode for this key on an initial down.
4931 // The fallback keycode cannot change at any other point in the lifecycle.
4932 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004934 fallbackKeyCode = event.getKeyCode();
4935 } else {
4936 fallbackKeyCode = AKEYCODE_UNKNOWN;
4937 }
4938 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4939 }
4940
4941 ALOG_ASSERT(fallbackKeyCode != -1);
4942
4943 // Cancel the fallback key if the policy decides not to send it anymore.
4944 // We will continue to dispatch the key to the policy but we will no
4945 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004946 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4947 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004948#if DEBUG_OUTBOUND_EVENT_DETAILS
4949 if (fallback) {
4950 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004951 "as a fallback for %d, but on the DOWN it had requested "
4952 "to send %d instead. Fallback canceled.",
4953 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004954 } else {
4955 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004956 "but on the DOWN it had requested to send %d. "
4957 "Fallback canceled.",
4958 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004959 }
4960#endif
4961
4962 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4963 "canceling fallback, policy no longer desires it");
4964 options.keyCode = fallbackKeyCode;
4965 synthesizeCancelationEventsForConnectionLocked(connection, options);
4966
4967 fallback = false;
4968 fallbackKeyCode = AKEYCODE_UNKNOWN;
4969 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004970 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004971 }
4972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973
4974#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004975 {
4976 std::string msg;
4977 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4978 connection->inputState.getFallbackKeys();
4979 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004980 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004981 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004982 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004983 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004984 }
4985#endif
4986
4987 if (fallback) {
4988 // Restart the dispatch cycle using the fallback key.
4989 keyEntry->eventTime = event.getEventTime();
4990 keyEntry->deviceId = event.getDeviceId();
4991 keyEntry->source = event.getSource();
4992 keyEntry->displayId = event.getDisplayId();
4993 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4994 keyEntry->keyCode = fallbackKeyCode;
4995 keyEntry->scanCode = event.getScanCode();
4996 keyEntry->metaState = event.getMetaState();
4997 keyEntry->repeatCount = event.getRepeatCount();
4998 keyEntry->downTime = event.getDownTime();
4999 keyEntry->syntheticRepeat = false;
5000
5001#if DEBUG_OUTBOUND_EVENT_DETAILS
5002 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005003 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5004 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005005#endif
5006 return true; // restart the event
5007 } else {
5008#if DEBUG_OUTBOUND_EVENT_DETAILS
5009 ALOGD("Unhandled key event: No fallback key.");
5010#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005011
5012 // Report the key as unhandled, since there is no fallback key.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08005013 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 }
5015 }
5016 return false;
5017}
5018
5019bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005020 DispatchEntry* dispatchEntry,
5021 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022 return false;
5023}
5024
5025void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5026 mLock.unlock();
5027
5028 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5029
5030 mLock.lock();
5031}
5032
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005033KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5034 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08005035 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08005036 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5037 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005038 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039}
5040
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07005041void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5042 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005043 // TODO Write some statistics about how long we spend waiting.
5044}
5045
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005046/**
5047 * Report the touch event latency to the statsd server.
5048 * Input events are reported for statistics if:
5049 * - This is a touchscreen event
5050 * - InputFilter is not enabled
5051 * - Event is not injected or synthesized
5052 *
5053 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5054 * from getting aggregated with the "old" data.
5055 */
5056void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5057 REQUIRES(mLock) {
5058 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5059 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5060 if (!reportForStatistics) {
5061 return;
5062 }
5063
5064 if (mTouchStatistics.shouldReport()) {
5065 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5066 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5067 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5068 mTouchStatistics.reset();
5069 }
5070 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5071 mTouchStatistics.addValue(latencyMicros);
5072}
5073
Michael Wrightd02c5b62014-02-10 15:10:22 -08005074void InputDispatcher::traceInboundQueueLengthLocked() {
5075 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005076 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005077 }
5078}
5079
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005080void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081 if (ATRACE_ENABLED()) {
5082 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005083 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005084 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005085 }
5086}
5087
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005088void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089 if (ATRACE_ENABLED()) {
5090 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005091 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005092 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005093 }
5094}
5095
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005096void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005097 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005099 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100 dumpDispatchStateLocked(dump);
5101
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005102 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005103 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005104 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105 }
5106}
5107
5108void InputDispatcher::monitor() {
5109 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005110 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005112 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005113}
5114
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005115/**
5116 * Wake up the dispatcher and wait until it processes all events and commands.
5117 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5118 * this method can be safely called from any thread, as long as you've ensured that
5119 * the work you are interested in completing has already been queued.
5120 */
5121bool InputDispatcher::waitForIdle() {
5122 /**
5123 * Timeout should represent the longest possible time that a device might spend processing
5124 * events and commands.
5125 */
5126 constexpr std::chrono::duration TIMEOUT = 100ms;
5127 std::unique_lock lock(mLock);
5128 mLooper->wake();
5129 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5130 return result == std::cv_status::no_timeout;
5131}
5132
Garfield Tane84e6f92019-08-29 17:28:41 -07005133} // namespace android::inputdispatcher