blob: f011992daa647bfd6223f4371ae3a49d9584aa8e [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Garfield Tane84e6f92019-08-29 17:28:41 -070048#include "Connection.h"
49
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <errno.h>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080051#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <limits.h>
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -050053#include <statslog.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080055#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056#include <unistd.h>
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -070057#include <queue>
58#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070059
Michael Wright2b3c3302018-03-02 17:19:13 +000060#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070062#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080063#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070064#include <log/log.h>
Gang Wang342c9272020-01-13 13:15:04 -050065#include <openssl/hmac.h>
66#include <openssl/rand.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070067#include <powermanager/PowerManager.h>
68#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080069
70#define INDENT " "
71#define INDENT2 " "
72#define INDENT3 " "
73#define INDENT4 " "
74
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080075using android::base::StringPrintf;
76
Garfield Tane84e6f92019-08-29 17:28:41 -070077namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
79// Default input dispatching timeout if there is no focused application or paused window
80// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -070081constexpr std::chrono::nanoseconds DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5s;
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Amount of time to allow for all pending events to be processed when an app switch
84// key is on the way. This is used to preempt input dispatch and drop input events
85// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000086constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow for an event to be dispatched (measured since its eventTime)
89// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
Michael Wrightd02c5b62014-02-10 15:10:22 -080092// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000093constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
94
95// Log a warning when an interception call takes longer than this to process.
96constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Siarhei Vishniakoue4623042020-03-25 16:16:40 -070098// Additional key latency in case a connection is still processing some motion events.
99// This will help with the case when a user touched a button that opens a new window,
100// and gives us the chance to dispatch the key to this new window.
101constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
102
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000104constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
105
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106static inline nsecs_t now() {
107 return systemTime(SYSTEM_TIME_MONOTONIC);
108}
109
110static inline const char* toString(bool value) {
111 return value ? "true" : "false";
112}
113
114static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700115 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
116 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117}
118
119static bool isValidKeyAction(int32_t action) {
120 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700121 case AKEY_EVENT_ACTION_DOWN:
122 case AKEY_EVENT_ACTION_UP:
123 return true;
124 default:
125 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126 }
127}
128
129static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700130 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131 ALOGE("Key event has invalid action code 0x%x", action);
132 return false;
133 }
134 return true;
135}
136
Michael Wright7b159c92015-05-14 14:48:03 +0100137static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700139 case AMOTION_EVENT_ACTION_DOWN:
140 case AMOTION_EVENT_ACTION_UP:
141 case AMOTION_EVENT_ACTION_CANCEL:
142 case AMOTION_EVENT_ACTION_MOVE:
143 case AMOTION_EVENT_ACTION_OUTSIDE:
144 case AMOTION_EVENT_ACTION_HOVER_ENTER:
145 case AMOTION_EVENT_ACTION_HOVER_MOVE:
146 case AMOTION_EVENT_ACTION_HOVER_EXIT:
147 case AMOTION_EVENT_ACTION_SCROLL:
148 return true;
149 case AMOTION_EVENT_ACTION_POINTER_DOWN:
150 case AMOTION_EVENT_ACTION_POINTER_UP: {
151 int32_t index = getMotionEventActionPointerIndex(action);
152 return index >= 0 && index < pointerCount;
153 }
154 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
155 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
156 return actionButton != 0;
157 default:
158 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800159 }
160}
161
Michael Wright7b159c92015-05-14 14:48:03 +0100162static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700163 const PointerProperties* pointerProperties) {
164 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 ALOGE("Motion event has invalid action code 0x%x", action);
166 return false;
167 }
168 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000169 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700170 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800171 return false;
172 }
173 BitSet32 pointerIdBits;
174 for (size_t i = 0; i < pointerCount; i++) {
175 int32_t id = pointerProperties[i].id;
176 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700177 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
178 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800179 return false;
180 }
181 if (pointerIdBits.hasBit(id)) {
182 ALOGE("Motion event has duplicate pointer id %d", id);
183 return false;
184 }
185 pointerIdBits.markBit(id);
186 }
187 return true;
188}
189
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800190static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800192 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 return;
194 }
195
196 bool first = true;
197 Region::const_iterator cur = region.begin();
198 Region::const_iterator const tail = region.end();
199 while (cur != tail) {
200 if (first) {
201 first = false;
202 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800203 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800205 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800206 cur++;
207 }
208}
209
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700210/**
211 * Find the entry in std::unordered_map by key, and return it.
212 * If the entry is not found, return a default constructed entry.
213 *
214 * Useful when the entries are vectors, since an empty vector will be returned
215 * if the entry is not found.
216 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
217 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700218template <typename K, typename V>
219static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700220 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700221 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800222}
223
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700224/**
225 * Find the entry in std::unordered_map by value, and remove it.
226 * If more than one entry has the same value, then all matching
227 * key-value pairs will be removed.
228 *
229 * Return true if at least one value has been removed.
230 */
231template <typename K, typename V>
232static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
233 bool removed = false;
234 for (auto it = map.begin(); it != map.end();) {
235 if (it->second == value) {
236 it = map.erase(it);
237 removed = true;
238 } else {
239 it++;
240 }
241 }
242 return removed;
243}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244
chaviwaf87b3e2019-10-01 16:59:28 -0700245static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
246 if (first == second) {
247 return true;
248 }
249
250 if (first == nullptr || second == nullptr) {
251 return false;
252 }
253
254 return first->getToken() == second->getToken();
255}
256
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800257static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
258 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
259}
260
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000261static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
262 EventEntry* eventEntry,
263 int32_t inputTargetFlags) {
264 if (inputTarget.useDefaultPointerInfo()) {
265 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
266 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
267 inputTargetFlags, pointerInfo.xOffset,
268 pointerInfo.yOffset, inputTarget.globalScaleFactor,
269 pointerInfo.windowXScale, pointerInfo.windowYScale);
270 }
271
272 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
273 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
274
275 PointerCoords pointerCoords[motionEntry.pointerCount];
276
277 // Use the first pointer information to normalize all other pointers. This could be any pointer
278 // as long as all other pointers are normalized to the same value and the final DispatchEntry
279 // uses the offset and scale for the normalized pointer.
280 const PointerInfo& firstPointerInfo =
281 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
282
283 // Iterate through all pointers in the event to normalize against the first.
284 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
285 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
286 uint32_t pointerId = uint32_t(pointerProperties.id);
287 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
288
289 // The scale factor is the ratio of the current pointers scale to the normalized scale.
290 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
291 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
292
293 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
294 // First apply the current pointers offset to set the window at 0,0
295 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
296 // Next scale the coordinates.
297 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
298 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
299 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
300 -firstPointerInfo.yOffset);
301 }
302
303 MotionEntry* combinedMotionEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800304 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000305 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
306 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
307 motionEntry.metaState, motionEntry.buttonState,
308 motionEntry.classification, motionEntry.edgeFlags,
309 motionEntry.xPrecision, motionEntry.yPrecision,
310 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
311 motionEntry.downTime, motionEntry.pointerCount,
312 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
313 0 /* yOffset */);
314
315 if (motionEntry.injectionState) {
316 combinedMotionEntry->injectionState = motionEntry.injectionState;
317 combinedMotionEntry->injectionState->refCount += 1;
318 }
319
320 std::unique_ptr<DispatchEntry> dispatchEntry =
321 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
322 inputTargetFlags, firstPointerInfo.xOffset,
323 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
324 firstPointerInfo.windowXScale,
325 firstPointerInfo.windowYScale);
326 combinedMotionEntry->release();
327 return dispatchEntry;
328}
329
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -0700330static void addGestureMonitors(const std::vector<Monitor>& monitors,
331 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
332 float yOffset = 0) {
333 if (monitors.empty()) {
334 return;
335 }
336 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
337 for (const Monitor& monitor : monitors) {
338 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
339 }
340}
341
Gang Wang342c9272020-01-13 13:15:04 -0500342static std::array<uint8_t, 128> getRandomKey() {
343 std::array<uint8_t, 128> key;
344 if (RAND_bytes(key.data(), key.size()) != 1) {
345 LOG_ALWAYS_FATAL("Can't generate HMAC key");
346 }
347 return key;
348}
349
350// --- HmacKeyManager ---
351
352HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
353
354std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
355 size_t size;
356 switch (event.type) {
357 case VerifiedInputEvent::Type::KEY: {
358 size = sizeof(VerifiedKeyEvent);
359 break;
360 }
361 case VerifiedInputEvent::Type::MOTION: {
362 size = sizeof(VerifiedMotionEvent);
363 break;
364 }
365 }
Gang Wang342c9272020-01-13 13:15:04 -0500366 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700367 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500368}
369
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700370std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500371 // SHA256 always generates 32-bytes result
372 std::array<uint8_t, 32> hash;
373 unsigned int hashLen = 0;
Edgar Arriaga3d61bc12020-04-16 18:46:48 -0700374 uint8_t* result =
375 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500376 if (result == nullptr) {
377 ALOGE("Could not sign the data using HMAC");
378 return INVALID_HMAC;
379 }
380
381 if (hashLen != hash.size()) {
382 ALOGE("HMAC-SHA256 has unexpected length");
383 return INVALID_HMAC;
384 }
385
386 return hash;
387}
388
Michael Wrightd02c5b62014-02-10 15:10:22 -0800389// --- InputDispatcher ---
390
Garfield Tan00f511d2019-06-12 16:55:40 -0700391InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
392 : mPolicy(policy),
393 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700394 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tan1c7bc862020-01-28 13:24:04 -0800395 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700396 mAppSwitchSawKeyDown(false),
397 mAppSwitchDueTime(LONG_LONG_MAX),
398 mNextUnblockedEvent(nullptr),
399 mDispatchEnabled(false),
400 mDispatchFrozen(false),
401 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800402 // mInTouchMode will be initialized by the WindowManager to the default device config.
403 // To avoid leaking stack in case that call never comes, and for tests,
404 // initialize it here anyways.
405 mInTouchMode(true),
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700406 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800407 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800408 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409
Yi Kong9b14ac62018-07-17 13:48:38 -0700410 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411
412 policy->getDispatcherConfiguration(&mConfig);
413}
414
415InputDispatcher::~InputDispatcher() {
416 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800417 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418
419 resetKeyRepeatLocked();
420 releasePendingEventLocked();
421 drainInboundQueueLocked();
422 }
423
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700424 while (!mConnectionsByFd.empty()) {
425 sp<Connection> connection = mConnectionsByFd.begin()->second;
426 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800427 }
428}
429
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700430status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700431 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700432 return ALREADY_EXISTS;
433 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700434 mThread = std::make_unique<InputThread>(
435 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
436 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700437}
438
439status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700440 if (mThread && mThread->isCallingThread()) {
441 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700442 return INVALID_OPERATION;
443 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700444 mThread.reset();
445 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700446}
447
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448void InputDispatcher::dispatchOnce() {
449 nsecs_t nextWakeupTime = LONG_LONG_MAX;
450 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800451 std::scoped_lock _l(mLock);
452 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453
454 // Run a dispatch loop if there are no pending commands.
455 // The dispatch loop might enqueue commands to run afterwards.
456 if (!haveCommandsLocked()) {
457 dispatchOnceInnerLocked(&nextWakeupTime);
458 }
459
460 // Run all pending commands if there are any.
461 // If any commands were run then force the next poll to wake up immediately.
462 if (runCommandsLockedInterruptible()) {
463 nextWakeupTime = LONG_LONG_MIN;
464 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800465
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700466 // If we are still waiting for ack on some events,
467 // we might have to wake up earlier to check if an app is anr'ing.
468 const nsecs_t nextAnrCheck = processAnrsLocked();
469 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
470
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800471 // We are about to enter an infinitely long sleep, because we have no commands or
472 // pending or queued events
473 if (nextWakeupTime == LONG_LONG_MAX) {
474 mDispatcherEnteredIdle.notify_all();
475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800476 } // release lock
477
478 // Wait for callback or timeout or wake. (make sure we round up, not down)
479 nsecs_t currentTime = now();
480 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
481 mLooper->pollOnce(timeoutMillis);
482}
483
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700484/**
485 * Check if any of the connections' wait queues have events that are too old.
486 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
487 * Return the time at which we should wake up next.
488 */
489nsecs_t InputDispatcher::processAnrsLocked() {
490 const nsecs_t currentTime = now();
491 nsecs_t nextAnrCheck = LONG_LONG_MAX;
492 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
493 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
494 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
495 onAnrLocked(mAwaitedFocusedApplication);
496 mAwaitedFocusedApplication.clear();
497 return LONG_LONG_MIN;
498 } else {
499 // Keep waiting
500 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
501 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
502 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
503 }
504 }
505
506 // Check if any connection ANRs are due
507 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
508 if (currentTime < nextAnrCheck) { // most likely scenario
509 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
510 }
511
512 // If we reached here, we have an unresponsive connection.
513 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
514 if (connection == nullptr) {
515 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
516 return nextAnrCheck;
517 }
518 connection->responsive = false;
519 // Stop waking up for this unresponsive connection
520 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
521 onAnrLocked(connection);
522 return LONG_LONG_MIN;
523}
524
525nsecs_t InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
526 sp<InputWindowHandle> window = getWindowHandleLocked(token);
527 if (window != nullptr) {
528 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT).count();
529 }
530 return DEFAULT_INPUT_DISPATCHING_TIMEOUT.count();
531}
532
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
534 nsecs_t currentTime = now();
535
Jeff Browndc5992e2014-04-11 01:27:26 -0700536 // Reset the key repeat timer whenever normal dispatch is suspended while the
537 // device is in a non-interactive state. This is to ensure that we abort a key
538 // repeat if the device is just coming out of sleep.
539 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 resetKeyRepeatLocked();
541 }
542
543 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
544 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100545 if (DEBUG_FOCUS) {
546 ALOGD("Dispatch frozen. Waiting some more.");
547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548 return;
549 }
550
551 // Optimize latency of app switches.
552 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
553 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
554 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
555 if (mAppSwitchDueTime < *nextWakeupTime) {
556 *nextWakeupTime = mAppSwitchDueTime;
557 }
558
559 // Ready to start a new event.
560 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700561 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700562 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 if (isAppSwitchDue) {
564 // The inbound queue is empty so the app switch key we were waiting
565 // for will never arrive. Stop waiting for it.
566 resetPendingAppSwitchLocked(false);
567 isAppSwitchDue = false;
568 }
569
570 // Synthesize a key repeat if appropriate.
571 if (mKeyRepeatState.lastKeyEntry) {
572 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
573 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
574 } else {
575 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
576 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
577 }
578 }
579 }
580
581 // Nothing to do if there is no pending event.
582 if (!mPendingEvent) {
583 return;
584 }
585 } else {
586 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700587 mPendingEvent = mInboundQueue.front();
588 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 traceInboundQueueLengthLocked();
590 }
591
592 // Poke user activity for this event.
593 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700594 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596 }
597
598 // Now we have an event to dispatch.
599 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700600 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700602 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700604 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700606 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607 }
608
609 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700610 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 }
612
613 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700614 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700615 ConfigurationChangedEntry* typedEntry =
616 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
617 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700618 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700619 break;
620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700622 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700623 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
624 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700625 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700626 break;
627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100629 case EventEntry::Type::FOCUS: {
630 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
631 dispatchFocusLocked(currentTime, typedEntry);
632 done = true;
633 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
634 break;
635 }
636
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700637 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700638 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
639 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700640 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700641 resetPendingAppSwitchLocked(true);
642 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700643 } else if (dropReason == DropReason::NOT_DROPPED) {
644 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700645 }
646 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700647 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700648 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700649 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700650 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
651 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700652 }
653 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
654 break;
655 }
656
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700657 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700658 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700659 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
660 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700662 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700663 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700664 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700665 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
666 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700667 }
668 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
669 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671 }
672
673 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700674 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700675 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 }
Michael Wright3a981722015-06-10 15:26:13 +0100677 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678
679 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700680 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 }
682}
683
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700684/**
685 * Return true if the events preceding this incoming motion event should be dropped
686 * Return false otherwise (the default behaviour)
687 */
688bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700689 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700690 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700691
692 // Optimize case where the current application is unresponsive and the user
693 // decides to touch a window in a different application.
694 // If the application takes too long to catch up then we drop all events preceding
695 // the touch into the other window.
696 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700697 int32_t displayId = motionEntry.displayId;
698 int32_t x = static_cast<int32_t>(
699 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
700 int32_t y = static_cast<int32_t>(
701 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700702 sp<InputWindowHandle> touchedWindowHandle =
703 findTouchedWindowAtLocked(displayId, x, y, nullptr);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700704 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700705 touchedWindowHandle->getApplicationToken() !=
706 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700707 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700708 ALOGI("Pruning input queue because user touched a different application while waiting "
709 "for %s",
710 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700711 return true;
712 }
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700713
714 // Alternatively, maybe there's a gesture monitor that could handle this event
715 std::vector<TouchedMonitor> gestureMonitors =
716 findTouchedGestureMonitorsLocked(displayId, {});
717 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
718 sp<Connection> connection =
719 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000720 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -0700721 // This monitor could take more input. Drop all events preceding this
722 // event, so that gesture monitor could get a chance to receive the stream
723 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
724 "responsive gesture monitor that may handle the event",
725 mAwaitedFocusedApplication->getName().c_str());
726 return true;
727 }
728 }
729 }
730
731 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
732 // yet been processed by some connections, the dispatcher will wait for these motion
733 // events to be processed before dispatching the key event. This is because these motion events
734 // may cause a new window to be launched, which the user might expect to receive focus.
735 // To prevent waiting forever for such events, just send the key to the currently focused window
736 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
737 ALOGD("Received a new pointer down event, stop waiting for events to process and "
738 "just send the pending key event to the focused window.");
739 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700740 }
741 return false;
742}
743
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700745 bool needWake = mInboundQueue.empty();
746 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 traceInboundQueueLengthLocked();
748
749 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700750 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700751 // Optimize app switch latency.
752 // If the application takes too long to catch up then we drop all events preceding
753 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700754 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700755 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700756 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700757 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700758 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700759 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700761 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700763 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700764 mAppSwitchSawKeyDown = false;
765 needWake = true;
766 }
767 }
768 }
769 break;
770 }
771
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700772 case EventEntry::Type::MOTION: {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700773 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
774 mNextUnblockedEvent = entry;
775 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700777 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100779 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -0700780 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
781 break;
782 }
783 case EventEntry::Type::CONFIGURATION_CHANGED:
784 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700785 // nothing to do
786 break;
787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 }
789
790 return needWake;
791}
792
793void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
794 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700795 mRecentQueue.push_back(entry);
796 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
797 mRecentQueue.front()->release();
798 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 }
800}
801
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700802sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700803 int32_t y, TouchState* touchState,
804 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700805 bool addPortalWindows) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700806 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
807 LOG_ALWAYS_FATAL(
808 "Must provide a valid touch state if adding portal windows or outside targets");
809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800811 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
812 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 const InputWindowInfo* windowInfo = windowHandle->getInfo();
814 if (windowInfo->displayId == displayId) {
815 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816
817 if (windowInfo->visible) {
818 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700819 bool isTouchModal = (flags &
820 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
821 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800823 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 if (portalToDisplayId != ADISPLAY_ID_NONE &&
825 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800826 if (addPortalWindows) {
827 // For the monitoring channels of the display.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700828 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800829 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700830 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700831 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 // Found window.
834 return windowHandle;
835 }
836 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800837
838 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -0700839 touchState->addOrUpdateWindow(windowHandle,
840 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
841 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 }
845 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700846 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847}
848
Garfield Tane84e6f92019-08-29 17:28:41 -0700849std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -0700850 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000851 std::vector<TouchedMonitor> touchedMonitors;
852
853 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
854 addGestureMonitors(monitors, touchedMonitors);
855 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
856 const InputWindowInfo* windowInfo = portalWindow->getInfo();
857 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700858 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
859 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000860 }
861 return touchedMonitors;
862}
863
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700864void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 const char* reason;
866 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700867 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700869 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700871 reason = "inbound event was dropped because the policy consumed it";
872 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700873 case DropReason::DISABLED:
874 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 ALOGI("Dropped event because input dispatch is disabled.");
876 }
877 reason = "inbound event was dropped because input dispatch is disabled";
878 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700879 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700880 ALOGI("Dropped event because of pending overdue app switch.");
881 reason = "inbound event was dropped because of pending overdue app switch";
882 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 ALOGI("Dropped event because the current application is not responding and the user "
885 "has started interacting with a different application.");
886 reason = "inbound event was dropped because the current application is not responding "
887 "and the user has started interacting with a different application";
888 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700889 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700890 ALOGI("Dropped event because it is stale.");
891 reason = "inbound event was dropped because it is stale";
892 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700893 case DropReason::NOT_DROPPED: {
894 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700895 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
898
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700899 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700900 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
902 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700905 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700906 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
907 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700908 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
909 synthesizeCancelationEventsForAllConnectionsLocked(options);
910 } else {
911 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
912 synthesizeCancelationEventsForAllConnectionsLocked(options);
913 }
914 break;
915 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100916 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700917 case EventEntry::Type::CONFIGURATION_CHANGED:
918 case EventEntry::Type::DEVICE_RESET: {
919 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
920 break;
921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 }
923}
924
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800925static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700926 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
927 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928}
929
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700930bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
931 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
932 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
933 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934}
935
936bool InputDispatcher::isAppSwitchPendingLocked() {
937 return mAppSwitchDueTime != LONG_LONG_MAX;
938}
939
940void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
941 mAppSwitchDueTime = LONG_LONG_MAX;
942
943#if DEBUG_APP_SWITCH
944 if (handled) {
945 ALOGD("App switch has arrived.");
946 } else {
947 ALOGD("App switch was abandoned.");
948 }
949#endif
950}
951
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700953 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954}
955
956bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700957 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958 return false;
959 }
960
961 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700962 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700963 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800964 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700965 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966
967 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700968 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 return true;
970}
971
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700972void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
973 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974}
975
976void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700977 while (!mInboundQueue.empty()) {
978 EventEntry* entry = mInboundQueue.front();
979 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980 releaseInboundEventLocked(entry);
981 }
982 traceInboundQueueLengthLocked();
983}
984
985void InputDispatcher::releasePendingEventLocked() {
986 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700988 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 }
990}
991
992void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
993 InjectionState* injectionState = entry->injectionState;
994 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
995#if DEBUG_DISPATCH_CYCLE
996 ALOGD("Injected inbound event was dropped.");
997#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800998 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
1000 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001001 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 }
1003 addRecentEventLocked(entry);
1004 entry->release();
1005}
1006
1007void InputDispatcher::resetKeyRepeatLocked() {
1008 if (mKeyRepeatState.lastKeyEntry) {
1009 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001010 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 }
1012}
1013
Garfield Tane84e6f92019-08-29 17:28:41 -07001014KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1016
1017 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001018 uint32_t policyFlags = entry->policyFlags &
1019 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 if (entry->refCount == 1) {
1021 entry->recycle();
Garfield Tan1c7bc862020-01-28 13:24:04 -08001022 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 entry->eventTime = currentTime;
1024 entry->policyFlags = policyFlags;
1025 entry->repeatCount += 1;
1026 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 KeyEntry* newEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08001028 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001029 entry->displayId, policyFlags, entry->action, entry->flags,
1030 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032
1033 mKeyRepeatState.lastKeyEntry = newEntry;
1034 entry->release();
1035
1036 entry = newEntry;
1037 }
1038 entry->syntheticRepeat = true;
1039
1040 // Increment reference count since we keep a reference to the event in
1041 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1042 entry->refCount += 1;
1043
1044 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1045 return entry;
1046}
1047
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001048bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1049 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001051 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052#endif
1053
1054 // Reset key repeating in case a keyboard device was added or removed or something.
1055 resetKeyRepeatLocked();
1056
1057 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001058 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1059 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001061 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 return true;
1063}
1064
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001065bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001067 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001068 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069#endif
1070
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001071 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 options.deviceId = entry->deviceId;
1073 synthesizeCancelationEventsForAllConnectionsLocked(options);
1074 return true;
1075}
1076
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001077void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07001078 if (mPendingEvent != nullptr) {
1079 // Move the pending event to the front of the queue. This will give the chance
1080 // for the pending event to get dispatched to the newly focused window
1081 mInboundQueue.push_front(mPendingEvent);
1082 mPendingEvent = nullptr;
1083 }
1084
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001085 FocusEntry* focusEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08001086 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07001087
1088 // This event should go to the front of the queue, but behind all other focus events
1089 // Find the last focus event, and insert right after it
1090 std::deque<EventEntry*>::reverse_iterator it =
1091 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1092 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1093
1094 // Maintain the order of focus events. Insert the entry after all other focus events.
1095 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001096}
1097
1098void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1099 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1100 if (channel == nullptr) {
1101 return; // Window has gone away
1102 }
1103 InputTarget target;
1104 target.inputChannel = channel;
1105 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1106 entry->dispatchInProgress = true;
Selim Cinek3d989c22020-06-17 21:42:12 +00001107
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001108 dispatchEventLocked(currentTime, entry, {target});
1109}
1110
Michael Wrightd02c5b62014-02-10 15:10:22 -08001111bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001112 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001114 if (!entry->dispatchInProgress) {
1115 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1116 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1117 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1118 if (mKeyRepeatState.lastKeyEntry &&
1119 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 // We have seen two identical key downs in a row which indicates that the device
1121 // driver is automatically generating key repeats itself. We take note of the
1122 // repeat here, but we disable our own next key repeat timer since it is clear that
1123 // we will not need to synthesize key repeats ourselves.
1124 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1125 resetKeyRepeatLocked();
1126 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1127 } else {
1128 // Not a repeat. Save key down state in case we do see a repeat later.
1129 resetKeyRepeatLocked();
1130 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1131 }
1132 mKeyRepeatState.lastKeyEntry = entry;
1133 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001134 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135 resetKeyRepeatLocked();
1136 }
1137
1138 if (entry->repeatCount == 1) {
1139 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1140 } else {
1141 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1142 }
1143
1144 entry->dispatchInProgress = true;
1145
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001146 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
1148
1149 // Handle case where the policy asked us to try again later last time.
1150 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1151 if (currentTime < entry->interceptKeyWakeupTime) {
1152 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1153 *nextWakeupTime = entry->interceptKeyWakeupTime;
1154 }
1155 return false; // wait until next wakeup
1156 }
1157 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1158 entry->interceptKeyWakeupTime = 0;
1159 }
1160
1161 // Give the policy a chance to intercept the key.
1162 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1163 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001164 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001165 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001166 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001167 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001168 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001169 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 }
1171 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001172 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 entry->refCount += 1;
1174 return false; // wait for the command to run
1175 } else {
1176 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1177 }
1178 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001179 if (*dropReason == DropReason::NOT_DROPPED) {
1180 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 }
1182 }
1183
1184 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001185 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001186 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001187 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001188 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001189 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 return true;
1191 }
1192
1193 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001194 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001195 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001196 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1198 return false;
1199 }
1200
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001201 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1203 return true;
1204 }
1205
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001206 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001207 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208
1209 // Dispatch the key.
1210 dispatchEventLocked(currentTime, entry, inputTargets);
1211 return true;
1212}
1213
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001214void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001216 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001217 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1218 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001219 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1220 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1221 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222#endif
1223}
1224
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001225bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1226 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001227 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 entry->dispatchInProgress = true;
1231
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001232 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 }
1234
1235 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001236 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001238 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001239 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 return true;
1241 }
1242
1243 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1244
1245 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001246 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247
1248 bool conflictingPointerActions = false;
1249 int32_t injectionResult;
1250 if (isPointerEvent) {
1251 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001252 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001253 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001254 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 } else {
1256 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001257 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001258 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 }
1260 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1261 return false;
1262 }
1263
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001264 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001265 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1266 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1267 return true;
1268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001270 CancelationOptions::Mode mode(isPointerEvent
1271 ? CancelationOptions::CANCEL_POINTER_EVENTS
1272 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1273 CancelationOptions options(mode, "input event injection failed");
1274 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 return true;
1276 }
1277
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001278 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001279 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001281 if (isPointerEvent) {
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001282 std::unordered_map<int32_t, TouchState>::iterator it =
1283 mTouchStatesByDisplay.find(entry->displayId);
1284 if (it != mTouchStatesByDisplay.end()) {
1285 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001286 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001287 // The event has gone through these portal windows, so we add monitoring targets of
1288 // the corresponding displays as well.
1289 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001290 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001291 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001292 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001293 }
1294 }
1295 }
1296 }
1297
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 // Dispatch the motion.
1299 if (conflictingPointerActions) {
1300 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001301 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 synthesizeCancelationEventsForAllConnectionsLocked(options);
1303 }
1304 dispatchEventLocked(currentTime, entry, inputTargets);
1305 return true;
1306}
1307
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001308void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001310 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001311 ", policyFlags=0x%x, "
1312 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1313 "metaState=0x%x, buttonState=0x%x,"
1314 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001315 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1316 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1317 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001319 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001321 "x=%f, y=%f, pressure=%f, size=%f, "
1322 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1323 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001324 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1325 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1326 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1327 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1328 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1329 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1330 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1331 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1332 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1333 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 }
1335#endif
1336}
1337
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001338void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1339 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001340 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341#if DEBUG_DISPATCH_CYCLE
1342 ALOGD("dispatchEventToCurrentInputTargets");
1343#endif
1344
1345 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1346
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001347 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001349 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001350 sp<Connection> connection =
1351 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001352 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001353 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001355 if (DEBUG_FOCUS) {
1356 ALOGD("Dropping event delivery to target with channel '%s' because it "
1357 "is no longer registered with the input dispatcher.",
1358 inputTarget.inputChannel->getName().c_str());
1359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 }
1361 }
1362}
1363
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001364void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1365 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1366 // If the policy decides to close the app, we will get a channel removal event via
1367 // unregisterInputChannel, and will clean up the connection that way. We are already not
1368 // sending new pointers to the connection when it blocked, but focused events will continue to
1369 // pile up.
1370 ALOGW("Canceling events for %s because it is unresponsive",
1371 connection->inputChannel->getName().c_str());
1372 if (connection->status == Connection::STATUS_NORMAL) {
1373 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1374 "application not responding");
1375 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 }
1377}
1378
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001379void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001380 if (DEBUG_FOCUS) {
1381 ALOGD("Resetting ANR timeouts.");
1382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383
1384 // Reset input target wait timeout.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001385 mNoFocusedWindowTimeoutTime = std::nullopt;
1386 mAwaitedFocusedApplication.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387}
1388
Tiger Huang721e26f2018-07-24 22:26:19 +08001389/**
1390 * Get the display id that the given event should go to. If this event specifies a valid display id,
1391 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1392 * Focused display is the display that the user most recently interacted with.
1393 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001394int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001395 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001396 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001397 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1399 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001400 break;
1401 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001402 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001403 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1404 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001405 break;
1406 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001407 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001408 case EventEntry::Type::CONFIGURATION_CHANGED:
1409 case EventEntry::Type::DEVICE_RESET: {
1410 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001411 return ADISPLAY_ID_NONE;
1412 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001413 }
1414 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1415}
1416
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001417bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1418 const char* focusedWindowName) {
1419 if (mAnrTracker.empty()) {
1420 // already processed all events that we waited for
1421 mKeyIsWaitingForEventsTimeout = std::nullopt;
1422 return false;
1423 }
1424
1425 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1426 // Start the timer
1427 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1428 "focus to change",
1429 focusedWindowName);
1430 mKeyIsWaitingForEventsTimeout = currentTime + KEY_WAITING_FOR_EVENTS_TIMEOUT.count();
1431 return true;
1432 }
1433
1434 // We still have pending events, and already started the timer
1435 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1436 return true; // Still waiting
1437 }
1438
1439 // Waited too long, and some connection still hasn't processed all motions
1440 // Just send the key to the focused window
1441 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1442 focusedWindowName);
1443 mKeyIsWaitingForEventsTimeout = std::nullopt;
1444 return false;
1445}
1446
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001448 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001449 std::vector<InputTarget>& inputTargets,
1450 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001451 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452
Tiger Huang721e26f2018-07-24 22:26:19 +08001453 int32_t displayId = getTargetDisplayId(entry);
1454 sp<InputWindowHandle> focusedWindowHandle =
1455 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1456 sp<InputApplicationHandle> focusedApplicationHandle =
1457 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1458
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459 // If there is no currently focused window and no focused application
1460 // then drop the event.
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001461 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1462 ALOGI("Dropping %s event because there is no focused window or focused application in "
1463 "display %" PRId32 ".",
1464 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001465 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 }
1467
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001468 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1469 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1470 // start interacting with another application via touch (app switch). This code can be removed
1471 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1472 // an app is expected to have a focused window.
1473 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1474 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1475 // We just discovered that there's no focused window. Start the ANR timer
1476 const nsecs_t timeout = focusedApplicationHandle->getDispatchingTimeout(
1477 DEFAULT_INPUT_DISPATCHING_TIMEOUT.count());
1478 mNoFocusedWindowTimeoutTime = currentTime + timeout;
1479 mAwaitedFocusedApplication = focusedApplicationHandle;
1480 ALOGW("Waiting because no window has focus but %s may eventually add a "
1481 "window when it finishes starting up. Will wait for %" PRId64 "ms",
1482 mAwaitedFocusedApplication->getName().c_str(), ns2ms(timeout));
1483 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1484 return INPUT_EVENT_INJECTION_PENDING;
1485 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1486 // Already raised ANR. Drop the event
1487 ALOGE("Dropping %s event because there is no focused window",
1488 EventEntry::typeToString(entry.type));
1489 return INPUT_EVENT_INJECTION_FAILED;
1490 } else {
1491 // Still waiting for the focused window
1492 return INPUT_EVENT_INJECTION_PENDING;
1493 }
1494 }
1495
1496 // we have a valid, non-null focused window
1497 resetNoFocusedWindowTimeoutLocked();
1498
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001500 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001501 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 }
1503
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001504 if (focusedWindowHandle->getInfo()->paused) {
1505 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1506 return INPUT_EVENT_INJECTION_PENDING;
1507 }
1508
1509 // If the event is a key event, then we must wait for all previous events to
1510 // complete before delivering it because previous events may have the
1511 // side-effect of transferring focus to a different window and we want to
1512 // ensure that the following keys are sent to the new window.
1513 //
1514 // Suppose the user touches a button in a window then immediately presses "A".
1515 // If the button causes a pop-up window to appear then we want to ensure that
1516 // the "A" key is delivered to the new pop-up window. This is because users
1517 // often anticipate pending UI changes when typing on a keyboard.
1518 // To obtain this behavior, we must serialize key events with respect to all
1519 // prior input events.
1520 if (entry.type == EventEntry::Type::KEY) {
1521 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1522 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1523 return INPUT_EVENT_INJECTION_PENDING;
1524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 }
1526
1527 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001528 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001529 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1530 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531
1532 // Done.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001533 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534}
1535
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001536/**
1537 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1538 * that are currently unresponsive.
1539 */
1540std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1541 const std::vector<TouchedMonitor>& monitors) const {
1542 std::vector<TouchedMonitor> responsiveMonitors;
1543 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1544 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1545 sp<Connection> connection = getConnectionLocked(
1546 monitor.monitor.inputChannel->getConnectionToken());
1547 if (connection == nullptr) {
1548 ALOGE("Could not find connection for monitor %s",
1549 monitor.monitor.inputChannel->getName().c_str());
1550 return false;
1551 }
1552 if (!connection->responsive) {
1553 ALOGW("Unresponsive monitor %s will not get the new gesture",
1554 connection->inputChannel->getName().c_str());
1555 return false;
1556 }
1557 return true;
1558 });
1559 return responsiveMonitors;
1560}
1561
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001563 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001564 std::vector<InputTarget>& inputTargets,
1565 nsecs_t* nextWakeupTime,
1566 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001567 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 enum InjectionPermission {
1569 INJECTION_PERMISSION_UNKNOWN,
1570 INJECTION_PERMISSION_GRANTED,
1571 INJECTION_PERMISSION_DENIED
1572 };
1573
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 // For security reasons, we defer updating the touch state until we are sure that
1575 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001576 int32_t displayId = entry.displayId;
1577 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1579
1580 // Update the touch state as needed based on the properties of the touch event.
1581 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1582 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1583 sp<InputWindowHandle> newHoverWindowHandle;
1584
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001585 // Copy current touch state into tempTouchState.
1586 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1587 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001588 const TouchState* oldState = nullptr;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001589 TouchState tempTouchState;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001590 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1591 mTouchStatesByDisplay.find(displayId);
1592 if (oldStateIt != mTouchStatesByDisplay.end()) {
1593 oldState = &(oldStateIt->second);
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001594 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001595 }
1596
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001597 bool isSplit = tempTouchState.split;
1598 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1599 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1600 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001601 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1602 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1603 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1604 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1605 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001606 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 bool wrongDevice = false;
1608 if (newGesture) {
1609 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001610 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001611 ALOGI("Dropping event because a pointer for a different device is already down "
1612 "in display %" PRId32,
1613 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001614 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1616 switchedDevice = false;
1617 wrongDevice = true;
1618 goto Failed;
1619 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001620 tempTouchState.reset();
1621 tempTouchState.down = down;
1622 tempTouchState.deviceId = entry.deviceId;
1623 tempTouchState.source = entry.source;
1624 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001626 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001627 ALOGI("Dropping move event because a pointer for a different device is already active "
1628 "in display %" PRId32,
1629 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001630 // TODO: test multiple simultaneous input streams.
1631 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1632 switchedDevice = false;
1633 wrongDevice = true;
1634 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 }
1636
1637 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1638 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1639
Garfield Tan00f511d2019-06-12 16:55:40 -07001640 int32_t x;
1641 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001643 // Always dispatch mouse events to cursor position.
1644 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001645 x = int32_t(entry.xCursorPosition);
1646 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001647 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001648 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1649 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001650 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001651 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001652 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001653 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1654 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001655
1656 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001657 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001658 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001661 if (newTouchedWindowHandle != nullptr &&
1662 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001663 // New window supports splitting, but we should never split mouse events.
1664 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 } else if (isSplit) {
1666 // New window does not support splitting but we have already split events.
1667 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001668 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 }
1670
1671 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001672 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001674 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001675 }
1676
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07001677 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1678 ALOGI("Not sending touch event to %s because it is paused",
1679 newTouchedWindowHandle->getName().c_str());
1680 newTouchedWindowHandle = nullptr;
1681 }
1682
1683 if (newTouchedWindowHandle != nullptr) {
1684 sp<Connection> connection = getConnectionLocked(newTouchedWindowHandle->getToken());
1685 if (connection == nullptr) {
1686 ALOGI("Could not find connection for %s",
1687 newTouchedWindowHandle->getName().c_str());
1688 newTouchedWindowHandle = nullptr;
1689 } else if (!connection->responsive) {
1690 // don't send the new touch to an unresponsive window
1691 ALOGW("Unresponsive window %s will not get the new gesture at %" PRIu64,
1692 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1693 newTouchedWindowHandle = nullptr;
1694 }
1695 }
1696
1697 // Also don't send the new touch event to unresponsive gesture monitors
1698 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1699
Michael Wright3dd60e22019-03-27 22:06:44 +00001700 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1701 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001702 "(%d, %d) in display %" PRId32 ".",
1703 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001704 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1705 goto Failed;
1706 }
1707
1708 if (newTouchedWindowHandle != nullptr) {
1709 // Set target flags.
1710 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1711 if (isSplit) {
1712 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001714 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1715 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1716 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1717 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1718 }
1719
1720 // Update hover state.
1721 if (isHoverAction) {
1722 newHoverWindowHandle = newTouchedWindowHandle;
1723 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1724 newHoverWindowHandle = mLastHoverWindowHandle;
1725 }
1726
1727 // Update the temporary touch state.
1728 BitSet32 pointerIds;
1729 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001730 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001731 pointerIds.markBit(pointerId);
1732 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001733 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 }
1735
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001736 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 } else {
1738 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1739
1740 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001741 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001742 if (DEBUG_FOCUS) {
1743 ALOGD("Dropping event because the pointer is not down or we previously "
1744 "dropped the pointer down event in display %" PRId32,
1745 displayId);
1746 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1748 goto Failed;
1749 }
1750
1751 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001752 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001753 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001754 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1755 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756
1757 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001758 tempTouchState.getFirstForegroundWindowHandle();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 sp<InputWindowHandle> newTouchedWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001760 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001761 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1762 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001763 if (DEBUG_FOCUS) {
1764 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1765 oldTouchedWindowHandle->getName().c_str(),
1766 newTouchedWindowHandle->getName().c_str(), displayId);
1767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768 // Make a slippery exit from the old window.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001769 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1770 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1771 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772
1773 // Make a slippery entrance into the new window.
1774 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1775 isSplit = true;
1776 }
1777
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001778 int32_t targetFlags =
1779 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 if (isSplit) {
1781 targetFlags |= InputTarget::FLAG_SPLIT;
1782 }
1783 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1784 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1785 }
1786
1787 BitSet32 pointerIds;
1788 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001789 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001791 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 }
1793 }
1794 }
1795
1796 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1797 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001798 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799#if DEBUG_HOVER
1800 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001801 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802#endif
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001803 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1804 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805 }
1806
1807 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001808 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809#if DEBUG_HOVER
1810 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001811 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812#endif
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001813 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1814 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1815 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 }
1817 }
1818
1819 // Check permission to inject into all touched foreground windows and ensure there
1820 // is at least one touched foreground window.
1821 {
1822 bool haveForegroundWindow = false;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001823 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1825 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001826 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1828 injectionPermission = INJECTION_PERMISSION_DENIED;
1829 goto Failed;
1830 }
1831 }
1832 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001833 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001834 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakoue0fb6bd2020-04-13 11:40:37 -07001835 ALOGI("Dropping event because there is no touched foreground window in display "
1836 "%" PRId32 " or gesture monitor to receive it.",
1837 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1839 goto Failed;
1840 }
1841
1842 // Permission granted to injection into all touched foreground windows.
1843 injectionPermission = INJECTION_PERMISSION_GRANTED;
1844 }
1845
1846 // Check whether windows listening for outside touches are owned by the same UID. If it is
1847 // set the policy flag that we will not reveal coordinate information to this window.
1848 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1849 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001850 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001851 if (foregroundWindowHandle) {
1852 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001853 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001854 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1855 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1856 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001857 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1858 InputTarget::FLAG_ZERO_COORDS,
1859 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001860 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 }
1862 }
1863 }
1864 }
1865
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 // If this is the first pointer going down and the touched window has a wallpaper
1867 // then also add the touched wallpaper windows so they are locked in for the duration
1868 // of the touch gesture.
1869 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1870 // engine only supports touch events. We would need to add a mechanism similar
1871 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1872 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1873 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001874 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001875 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001876 const std::vector<sp<InputWindowHandle>> windowHandles =
1877 getWindowHandlesLocked(displayId);
1878 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001880 if (info->displayId == displayId &&
1881 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001882 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001883 .addOrUpdateWindow(windowHandle,
1884 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1885 InputTarget::
1886 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1887 InputTarget::FLAG_DISPATCH_AS_IS,
1888 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 }
1890 }
1891 }
1892 }
1893
1894 // Success! Output targets.
1895 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1896
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001897 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001899 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 }
1901
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001902 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001903 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001904 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001905 }
1906
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 // Drop the outside or hover touch windows since we will not care about them
1908 // in the next iteration.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001909 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910
1911Failed:
1912 // Check injection permission once and for all.
1913 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001914 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 injectionPermission = INJECTION_PERMISSION_GRANTED;
1916 } else {
1917 injectionPermission = INJECTION_PERMISSION_DENIED;
1918 }
1919 }
1920
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001921 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1922 return injectionResult;
1923 }
1924
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001926 if (!wrongDevice) {
1927 if (switchedDevice) {
1928 if (DEBUG_FOCUS) {
1929 ALOGD("Conflicting pointer actions: Switched to a different device.");
1930 }
1931 *outConflictingPointerActions = true;
1932 }
1933
1934 if (isHoverAction) {
1935 // Started hovering, therefore no longer down.
1936 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001937 if (DEBUG_FOCUS) {
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001938 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1939 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001940 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941 *outConflictingPointerActions = true;
1942 }
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001943 tempTouchState.reset();
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001944 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1945 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001946 tempTouchState.deviceId = entry.deviceId;
1947 tempTouchState.source = entry.source;
1948 tempTouchState.displayId = displayId;
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001949 }
1950 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1951 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1952 // All pointers up or canceled.
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001953 tempTouchState.reset();
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001954 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1955 // First pointer went down.
1956 if (oldState && oldState->down) {
1957 if (DEBUG_FOCUS) {
1958 ALOGD("Conflicting pointer actions: Down received while already down.");
1959 }
1960 *outConflictingPointerActions = true;
1961 }
1962 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1963 // One pointer went up.
1964 if (isSplit) {
1965 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1966 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001968 for (size_t i = 0; i < tempTouchState.windows.size();) {
1969 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001970 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1971 touchedWindow.pointerIds.clearBit(pointerId);
1972 if (touchedWindow.pointerIds.isEmpty()) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001973 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001974 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001977 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001979 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001980 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001981
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001982 // Save changes unless the action was scroll in which case the temporary touch
1983 // state was only valid for this one action.
1984 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou1ea3cf12020-03-24 19:50:03 -07001985 if (tempTouchState.displayId >= 0) {
1986 mTouchStatesByDisplay[displayId] = tempTouchState;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07001987 } else {
1988 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07001992 // Update hover state.
1993 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 }
1995
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996 return injectionResult;
1997}
1998
1999void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002000 int32_t targetFlags, BitSet32 pointerIds,
2001 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002002 std::vector<InputTarget>::iterator it =
2003 std::find_if(inputTargets.begin(), inputTargets.end(),
2004 [&windowHandle](const InputTarget& inputTarget) {
2005 return inputTarget.inputChannel->getConnectionToken() ==
2006 windowHandle->getToken();
2007 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002008
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002009 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002010
2011 if (it == inputTargets.end()) {
2012 InputTarget inputTarget;
2013 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2014 if (inputChannel == nullptr) {
2015 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2016 return;
2017 }
2018 inputTarget.inputChannel = inputChannel;
2019 inputTarget.flags = targetFlags;
2020 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2021 inputTargets.push_back(inputTarget);
2022 it = inputTargets.end() - 1;
2023 }
2024
2025 ALOG_ASSERT(it->flags == targetFlags);
2026 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2027
2028 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
2029 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030}
2031
Michael Wright3dd60e22019-03-27 22:06:44 +00002032void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002033 int32_t displayId, float xOffset,
2034 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002035 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2036 mGlobalMonitorsByDisplay.find(displayId);
2037
2038 if (it != mGlobalMonitorsByDisplay.end()) {
2039 const std::vector<Monitor>& monitors = it->second;
2040 for (const Monitor& monitor : monitors) {
2041 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 }
2044}
2045
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002046void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2047 float yOffset,
2048 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002049 InputTarget target;
2050 target.inputChannel = monitor.inputChannel;
2051 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002052 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00002053 inputTargets.push_back(target);
2054}
2055
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002057 const InjectionState* injectionState) {
2058 if (injectionState &&
2059 (windowHandle == nullptr ||
2060 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2061 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002062 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002064 "owned by uid %d",
2065 injectionState->injectorPid, injectionState->injectorUid,
2066 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 } else {
2068 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002069 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 }
2071 return false;
2072 }
2073 return true;
2074}
2075
Robert Carr9cada032020-04-13 17:21:08 -07002076/**
2077 * Indicate whether one window handle should be considered as obscuring
2078 * another window handle. We only check a few preconditions. Actually
2079 * checking the bounds is left to the caller.
2080 */
2081static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2082 const sp<InputWindowHandle>& otherHandle) {
2083 // Compare by token so cloned layers aren't counted
2084 if (haveSameToken(windowHandle, otherHandle)) {
2085 return false;
2086 }
2087 auto info = windowHandle->getInfo();
2088 auto otherInfo = otherHandle->getInfo();
2089 if (!otherInfo->visible) {
2090 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002091 } else if (info->ownerPid == otherInfo->ownerPid) {
2092 // If ownerPid is the same we don't generate occlusion events as there
2093 // is no in-process security boundary.
Robert Carr9cada032020-04-13 17:21:08 -07002094 return false;
2095 } else if (otherInfo->isTrustedOverlay()) {
2096 return false;
2097 } else if (otherInfo->displayId != info->displayId) {
2098 return false;
2099 }
2100 return true;
2101}
2102
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002103bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2104 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002106 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2107 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002108 if (windowHandle == otherHandle) {
2109 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002112 if (canBeObscuredBy(windowHandle, otherHandle) &&
2113 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 return true;
2115 }
2116 }
2117 return false;
2118}
2119
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002120bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2121 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002122 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002123 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002124 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carr9cada032020-04-13 17:21:08 -07002125 if (windowHandle == otherHandle) {
2126 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002127 }
2128
2129 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carr9cada032020-04-13 17:21:08 -07002130 if (canBeObscuredBy(windowHandle, otherHandle) &&
2131 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002132 return true;
2133 }
2134 }
2135 return false;
2136}
2137
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002138std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 const sp<InputApplicationHandle>& applicationHandle,
2140 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002141 if (applicationHandle != nullptr) {
2142 if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002143 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 } else {
2145 return applicationHandle->getName();
2146 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002147 } else if (windowHandle != nullptr) {
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07002148 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002150 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151 }
2152}
2153
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002154void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002155 if (eventEntry.type == EventEntry::Type::FOCUS) {
2156 // Focus events are passed to apps, but do not represent user activity.
2157 return;
2158 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002159 int32_t displayId = getTargetDisplayId(eventEntry);
2160 sp<InputWindowHandle> focusedWindowHandle =
2161 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2162 if (focusedWindowHandle != nullptr) {
2163 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2165#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002166 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167#endif
2168 return;
2169 }
2170 }
2171
2172 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002173 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002174 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002175 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2176 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002177 return;
2178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002179
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002180 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002181 eventType = USER_ACTIVITY_EVENT_TOUCH;
2182 }
2183 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002185 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002186 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2187 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002188 return;
2189 }
2190 eventType = USER_ACTIVITY_EVENT_BUTTON;
2191 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002193 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002194 case EventEntry::Type::CONFIGURATION_CHANGED:
2195 case EventEntry::Type::DEVICE_RESET: {
2196 LOG_ALWAYS_FATAL("%s events are not user activity",
2197 EventEntry::typeToString(eventEntry.type));
2198 break;
2199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 }
2201
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002202 std::unique_ptr<CommandEntry> commandEntry =
2203 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002204 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002206 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207}
2208
2209void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002210 const sp<Connection>& connection,
2211 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002212 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002213 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002214 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002215 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002216 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002217 ATRACE_NAME(message.c_str());
2218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219#if DEBUG_DISPATCH_CYCLE
2220 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002221 "globalScaleFactor=%f, pointerIds=0x%x %s",
2222 connection->getInputChannelName().c_str(), inputTarget.flags,
2223 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2224 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225#endif
2226
2227 // Skip this event if the connection status is not normal.
2228 // We don't want to enqueue additional outbound events if the connection is broken.
2229 if (connection->status != Connection::STATUS_NORMAL) {
2230#if DEBUG_DISPATCH_CYCLE
2231 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002232 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233#endif
2234 return;
2235 }
2236
2237 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002238 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2239 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2240 "Entry type %s should not have FLAG_SPLIT",
2241 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002243 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002244 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002245 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002246 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 if (!splitMotionEntry) {
2248 return; // split event was dropped
2249 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002250 if (DEBUG_FOCUS) {
2251 ALOGD("channel '%s' ~ Split motion event.",
2252 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002253 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002254 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002255 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 splitMotionEntry->release();
2257 return;
2258 }
2259 }
2260
2261 // Not splitting. Enqueue dispatch entries for the event as is.
2262 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2263}
2264
2265void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002266 const sp<Connection>& connection,
2267 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002268 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002269 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002270 std::string message =
Garfield Tan1c7bc862020-01-28 13:24:04 -08002271 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002272 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002273 ATRACE_NAME(message.c_str());
2274 }
2275
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002276 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277
2278 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002279 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002280 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002281 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002282 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002283 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002284 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002285 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002286 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002287 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002288 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002289 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002290 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291
2292 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002293 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 startDispatchCycleLocked(currentTime, connection);
2295 }
2296}
2297
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002298void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2299 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002300 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002301 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002302 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002303 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2304 connection->getInputChannelName().c_str(),
2305 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002306 ATRACE_NAME(message.c_str());
2307 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002308 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 if (!(inputTargetFlags & dispatchMode)) {
2310 return;
2311 }
2312 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2313
2314 // This is a new event.
2315 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002316 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002317 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002319 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2320 // different EventEntry than what was passed in.
2321 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002323 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002324 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002325 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002326 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002327 dispatchEntry->resolvedAction = keyEntry.action;
2328 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002330 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2331 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002333 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2334 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002336 return; // skip the inconsistent event
2337 }
2338 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002341 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002342 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002343 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2344 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2345 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2346 static_cast<int32_t>(IdGenerator::Source::OTHER);
2347 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002348 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2349 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2350 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2351 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2352 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2353 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2354 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2355 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2356 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2357 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2358 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002359 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002360 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002361 }
2362 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002363 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2364 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002366 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2367 "event",
2368 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002370 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002373 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002374 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2375 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2376 }
2377 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2378 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002381 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2382 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002384 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2385 "event",
2386 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002388 return; // skip the inconsistent event
2389 }
2390
Garfield Tan1c7bc862020-01-28 13:24:04 -08002391 dispatchEntry->resolvedEventId =
2392 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2393 ? mIdGenerator.nextId()
2394 : motionEntry.id;
2395 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2396 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2397 ") to MotionEvent(id=0x%" PRIx32 ").",
2398 motionEntry.id, dispatchEntry->resolvedEventId);
2399 ATRACE_NAME(message.c_str());
2400 }
2401
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002402 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002403 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002404
2405 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002407 case EventEntry::Type::FOCUS: {
2408 break;
2409 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002410 case EventEntry::Type::CONFIGURATION_CHANGED:
2411 case EventEntry::Type::DEVICE_RESET: {
2412 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002413 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002414 break;
2415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416 }
2417
2418 // Remember that we are waiting for this dispatch to complete.
2419 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002420 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 }
2422
2423 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002424 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002425 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002426}
2427
chaviwfd6d3512019-03-25 13:23:49 -07002428void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002429 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002430 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002431 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2432 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002433 return;
2434 }
2435
2436 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2437 if (inputWindowHandle == nullptr) {
2438 return;
2439 }
2440
chaviw8c9cf542019-03-25 13:02:48 -07002441 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002442 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002443
2444 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2445
2446 if (!hasFocusChanged) {
2447 return;
2448 }
2449
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002450 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2451 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002452 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002453 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454}
2455
2456void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002457 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002458 if (ATRACE_ENABLED()) {
2459 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002460 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002461 ATRACE_NAME(message.c_str());
2462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002464 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465#endif
2466
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002467 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2468 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07002470 const nsecs_t timeout =
2471 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
2472 dispatchEntry->timeoutTime = currentTime + timeout;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473
2474 // Publish the event.
2475 status_t status;
2476 EventEntry* eventEntry = dispatchEntry->eventEntry;
2477 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002478 case EventEntry::Type::KEY: {
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002479 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2480 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002482 // Publish the key event.
Garfield Tan1c7bc862020-01-28 13:24:04 -08002483 status =
2484 connection->inputPublisher
2485 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2486 keyEntry->deviceId, keyEntry->source,
2487 keyEntry->displayId, std::move(hmac),
2488 dispatchEntry->resolvedAction,
2489 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2490 keyEntry->scanCode, keyEntry->metaState,
2491 keyEntry->repeatCount, keyEntry->downTime,
2492 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002493 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 }
2495
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002496 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002497 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002499 PointerCoords scaledCoords[MAX_POINTERS];
2500 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2501
chaviw82357092020-01-28 13:13:06 -08002502 // Set the X and Y offset and X and Y scale depending on the input source.
2503 float xOffset = 0.0f, yOffset = 0.0f;
2504 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002505 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2506 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2507 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002508 xScale = dispatchEntry->windowXScale;
2509 yScale = dispatchEntry->windowYScale;
2510 xOffset = dispatchEntry->xOffset * xScale;
2511 yOffset = dispatchEntry->yOffset * yScale;
2512 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002513 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2514 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002515 // Don't apply window scale here since we don't want scale to affect raw
2516 // coordinates. The scale will be sent back to the client and applied
2517 // later when requesting relative coordinates.
2518 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2519 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002520 }
2521 usingCoords = scaledCoords;
2522 }
2523 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002524 // We don't want the dispatch target to know.
2525 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2526 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2527 scaledCoords[i].clear();
2528 }
2529 usingCoords = scaledCoords;
2530 }
2531 }
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002532
2533 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002534
2535 // Publish the motion event.
2536 status = connection->inputPublisher
Garfield Tan1c7bc862020-01-28 13:24:04 -08002537 .publishMotionEvent(dispatchEntry->seq,
2538 dispatchEntry->resolvedEventId,
2539 motionEntry->deviceId, motionEntry->source,
2540 motionEntry->displayId, std::move(hmac),
2541 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002542 motionEntry->actionButton,
2543 dispatchEntry->resolvedFlags,
2544 motionEntry->edgeFlags, motionEntry->metaState,
2545 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002546 motionEntry->classification, xScale, yScale,
2547 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002548 motionEntry->yPrecision,
2549 motionEntry->xCursorPosition,
2550 motionEntry->yCursorPosition,
2551 motionEntry->downTime, motionEntry->eventTime,
2552 motionEntry->pointerCount,
2553 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002554 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002555 break;
2556 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002557 case EventEntry::Type::FOCUS: {
2558 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2559 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tan1c7bc862020-01-28 13:24:04 -08002560 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002561 focusEntry->hasFocus,
2562 mInTouchMode);
2563 break;
2564 }
2565
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002566 case EventEntry::Type::CONFIGURATION_CHANGED:
2567 case EventEntry::Type::DEVICE_RESET: {
2568 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2569 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002570 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 }
2573
2574 // Check the result.
2575 if (status) {
2576 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002577 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002579 "This is unexpected because the wait queue is empty, so the pipe "
2580 "should be empty and we shouldn't have any problems writing an "
2581 "event to it, status=%d",
2582 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2584 } else {
2585 // Pipe is full and we are waiting for the app to finish process some events
2586 // before sending more events to it.
2587#if DEBUG_DISPATCH_CYCLE
2588 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002589 "waiting for the application to catch up",
2590 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002592 }
2593 } else {
2594 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002595 "status=%d",
2596 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2598 }
2599 return;
2600 }
2601
2602 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002603 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2604 connection->outboundQueue.end(),
2605 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002606 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002607 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07002608 if (connection->responsive) {
2609 mAnrTracker.insert(dispatchEntry->timeoutTime,
2610 connection->inputChannel->getConnectionToken());
2611 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002612 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 }
2614}
2615
Edgar Arriaga3d61bc12020-04-16 18:46:48 -07002616const std::array<uint8_t, 32> InputDispatcher::getSignature(
2617 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2618 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2619 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2620 // Only sign events up and down events as the purely move events
2621 // are tied to their up/down counterparts so signing would be redundant.
2622 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2623 verifiedEvent.actionMasked = actionMasked;
2624 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2625 return mHmacKeyManager.sign(verifiedEvent);
2626 }
2627 return INVALID_HMAC;
2628}
2629
2630const std::array<uint8_t, 32> InputDispatcher::getSignature(
2631 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2632 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2633 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2634 verifiedEvent.action = dispatchEntry.resolvedAction;
2635 return mHmacKeyManager.sign(verifiedEvent);
2636}
2637
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002639 const sp<Connection>& connection, uint32_t seq,
2640 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641#if DEBUG_DISPATCH_CYCLE
2642 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002643 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002644#endif
2645
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002646 if (connection->status == Connection::STATUS_BROKEN ||
2647 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 return;
2649 }
2650
2651 // Notify other system components and prepare to start the next dispatch cycle.
2652 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2653}
2654
2655void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002656 const sp<Connection>& connection,
2657 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658#if DEBUG_DISPATCH_CYCLE
2659 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002660 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661#endif
2662
2663 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002664 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002665 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002666 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002667 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668
2669 // The connection appears to be unrecoverably broken.
2670 // Ignore already broken or zombie connections.
2671 if (connection->status == Connection::STATUS_NORMAL) {
2672 connection->status = Connection::STATUS_BROKEN;
2673
2674 if (notify) {
2675 // Notify other system components.
2676 onDispatchCycleBrokenLocked(currentTime, connection);
2677 }
2678 }
2679}
2680
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002681void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2682 while (!queue.empty()) {
2683 DispatchEntry* dispatchEntry = queue.front();
2684 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002685 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 }
2687}
2688
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002689void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002691 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692 }
2693 delete dispatchEntry;
2694}
2695
2696int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2697 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2698
2699 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002700 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002702 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002704 "fd=%d, events=0x%x",
2705 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 return 0; // remove the callback
2707 }
2708
2709 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002710 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2712 if (!(events & ALOOPER_EVENT_INPUT)) {
2713 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002714 "events=0x%x",
2715 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716 return 1;
2717 }
2718
2719 nsecs_t currentTime = now();
2720 bool gotOne = false;
2721 status_t status;
2722 for (;;) {
2723 uint32_t seq;
2724 bool handled;
2725 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2726 if (status) {
2727 break;
2728 }
2729 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2730 gotOne = true;
2731 }
2732 if (gotOne) {
2733 d->runCommandsLockedInterruptible();
2734 if (status == WOULD_BLOCK) {
2735 return 1;
2736 }
2737 }
2738
2739 notify = status != DEAD_OBJECT || !connection->monitor;
2740 if (notify) {
2741 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002742 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743 }
2744 } else {
2745 // Monitor channels are never explicitly unregistered.
2746 // We do it automatically when the remote endpoint is closed so don't warn
2747 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002748 const bool stillHaveWindowHandle =
2749 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2750 nullptr;
2751 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 if (notify) {
2753 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002754 "events=0x%x",
2755 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756 }
2757 }
2758
2759 // Unregister the channel.
2760 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2761 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002762 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763}
2764
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002765void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002767 for (const auto& pair : mConnectionsByFd) {
2768 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 }
2770}
2771
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002772void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002773 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002774 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2775 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2776}
2777
2778void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2779 const CancelationOptions& options,
2780 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2781 for (const auto& it : monitorsByDisplay) {
2782 const std::vector<Monitor>& monitors = it.second;
2783 for (const Monitor& monitor : monitors) {
2784 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002785 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002786 }
2787}
2788
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2790 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002791 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002792 if (connection == nullptr) {
2793 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002794 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002795
2796 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797}
2798
2799void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2800 const sp<Connection>& connection, const CancelationOptions& options) {
2801 if (connection->status == Connection::STATUS_BROKEN) {
2802 return;
2803 }
2804
2805 nsecs_t currentTime = now();
2806
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002807 std::vector<EventEntry*> cancelationEvents =
2808 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002810 if (cancelationEvents.empty()) {
2811 return;
2812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002814 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2815 "with reality: %s, mode=%d.",
2816 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2817 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002819
2820 InputTarget target;
2821 sp<InputWindowHandle> windowHandle =
2822 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2823 if (windowHandle != nullptr) {
2824 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2825 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2826 windowInfo->windowXScale, windowInfo->windowYScale);
2827 target.globalScaleFactor = windowInfo->globalScaleFactor;
2828 }
2829 target.inputChannel = connection->inputChannel;
2830 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2831
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002832 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2833 EventEntry* cancelationEventEntry = cancelationEvents[i];
2834 switch (cancelationEventEntry->type) {
2835 case EventEntry::Type::KEY: {
2836 logOutboundKeyDetails("cancel - ",
2837 static_cast<const KeyEntry&>(*cancelationEventEntry));
2838 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002840 case EventEntry::Type::MOTION: {
2841 logOutboundMotionDetails("cancel - ",
2842 static_cast<const MotionEntry&>(*cancelationEventEntry));
2843 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002845 case EventEntry::Type::FOCUS: {
2846 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2847 break;
2848 }
2849 case EventEntry::Type::CONFIGURATION_CHANGED:
2850 case EventEntry::Type::DEVICE_RESET: {
2851 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2852 EventEntry::typeToString(cancelationEventEntry->type));
2853 break;
2854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855 }
2856
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002857 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2858 target, InputTarget::FLAG_DISPATCH_AS_IS);
2859
2860 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002862
2863 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864}
2865
Svet Ganov5d3bc372020-01-26 23:11:07 -08002866void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2867 const sp<Connection>& connection) {
2868 if (connection->status == Connection::STATUS_BROKEN) {
2869 return;
2870 }
2871
2872 nsecs_t currentTime = now();
2873
2874 std::vector<EventEntry*> downEvents =
2875 connection->inputState.synthesizePointerDownEvents(currentTime);
2876
2877 if (downEvents.empty()) {
2878 return;
2879 }
2880
2881#if DEBUG_OUTBOUND_EVENT_DETAILS
2882 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2883 connection->getInputChannelName().c_str(), downEvents.size());
2884#endif
2885
2886 InputTarget target;
2887 sp<InputWindowHandle> windowHandle =
2888 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2889 if (windowHandle != nullptr) {
2890 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2891 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2892 windowInfo->windowXScale, windowInfo->windowYScale);
2893 target.globalScaleFactor = windowInfo->globalScaleFactor;
2894 }
2895 target.inputChannel = connection->inputChannel;
2896 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2897
2898 for (EventEntry* downEventEntry : downEvents) {
2899 switch (downEventEntry->type) {
2900 case EventEntry::Type::MOTION: {
2901 logOutboundMotionDetails("down - ",
2902 static_cast<const MotionEntry&>(*downEventEntry));
2903 break;
2904 }
2905
2906 case EventEntry::Type::KEY:
2907 case EventEntry::Type::FOCUS:
2908 case EventEntry::Type::CONFIGURATION_CHANGED:
2909 case EventEntry::Type::DEVICE_RESET: {
2910 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2911 EventEntry::typeToString(downEventEntry->type));
2912 break;
2913 }
2914 }
2915
2916 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2917 target, InputTarget::FLAG_DISPATCH_AS_IS);
2918
2919 downEventEntry->release();
2920 }
2921
2922 startDispatchCycleLocked(currentTime, connection);
2923}
2924
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002925MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002926 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927 ALOG_ASSERT(pointerIds.value != 0);
2928
2929 uint32_t splitPointerIndexMap[MAX_POINTERS];
2930 PointerProperties splitPointerProperties[MAX_POINTERS];
2931 PointerCoords splitPointerCoords[MAX_POINTERS];
2932
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002933 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934 uint32_t splitPointerCount = 0;
2935
2936 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002937 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002939 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 uint32_t pointerId = uint32_t(pointerProperties.id);
2941 if (pointerIds.hasBit(pointerId)) {
2942 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2943 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2944 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002945 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946 splitPointerCount += 1;
2947 }
2948 }
2949
2950 if (splitPointerCount != pointerIds.count()) {
2951 // This is bad. We are missing some of the pointers that we expected to deliver.
2952 // Most likely this indicates that we received an ACTION_MOVE events that has
2953 // different pointer ids than we expected based on the previous ACTION_DOWN
2954 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2955 // in this way.
2956 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002957 "we expected there to be %d pointers. This probably means we received "
2958 "a broken sequence of pointer ids from the input device.",
2959 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002960 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961 }
2962
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002963 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002964 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002965 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2966 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2968 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002969 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970 uint32_t pointerId = uint32_t(pointerProperties.id);
2971 if (pointerIds.hasBit(pointerId)) {
2972 if (pointerIds.count() == 1) {
2973 // The first/last pointer went down/up.
2974 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002975 ? AMOTION_EVENT_ACTION_DOWN
2976 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002977 } else {
2978 // A secondary pointer went down/up.
2979 uint32_t splitPointerIndex = 0;
2980 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2981 splitPointerIndex += 1;
2982 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 action = maskedAction |
2984 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002985 }
2986 } else {
2987 // An unrelated pointer changed.
2988 action = AMOTION_EVENT_ACTION_MOVE;
2989 }
2990 }
2991
Garfield Tan1c7bc862020-01-28 13:24:04 -08002992 int32_t newId = mIdGenerator.nextId();
2993 if (ATRACE_ENABLED()) {
2994 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
2995 ") to MotionEvent(id=0x%" PRIx32 ").",
2996 originalMotionEntry.id, newId);
2997 ATRACE_NAME(message.c_str());
2998 }
Garfield Tan00f511d2019-06-12 16:55:40 -07002999 MotionEntry* splitMotionEntry =
Garfield Tan1c7bc862020-01-28 13:24:04 -08003000 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3001 originalMotionEntry.source, originalMotionEntry.displayId,
3002 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003003 originalMotionEntry.actionButton, originalMotionEntry.flags,
3004 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3005 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3006 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3007 originalMotionEntry.xCursorPosition,
3008 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003009 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003010
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003011 if (originalMotionEntry.injectionState) {
3012 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013 splitMotionEntry->injectionState->refCount += 1;
3014 }
3015
3016 return splitMotionEntry;
3017}
3018
3019void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3020#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003021 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003022#endif
3023
3024 bool needWake;
3025 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003026 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003027
Prabir Pradhan42611e02018-11-27 14:04:02 -08003028 ConfigurationChangedEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003029 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030 needWake = enqueueInboundEventLocked(newEntry);
3031 } // release lock
3032
3033 if (needWake) {
3034 mLooper->wake();
3035 }
3036}
3037
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003038/**
3039 * If one of the meta shortcuts is detected, process them here:
3040 * Meta + Backspace -> generate BACK
3041 * Meta + Enter -> generate HOME
3042 * This will potentially overwrite keyCode and metaState.
3043 */
3044void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003045 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003046 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3047 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3048 if (keyCode == AKEYCODE_DEL) {
3049 newKeyCode = AKEYCODE_BACK;
3050 } else if (keyCode == AKEYCODE_ENTER) {
3051 newKeyCode = AKEYCODE_HOME;
3052 }
3053 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003054 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003055 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003056 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003057 keyCode = newKeyCode;
3058 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3059 }
3060 } else if (action == AKEY_EVENT_ACTION_UP) {
3061 // In order to maintain a consistent stream of up and down events, check to see if the key
3062 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3063 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003064 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003065 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003066 auto replacementIt = mReplacedKeys.find(replacement);
3067 if (replacementIt != mReplacedKeys.end()) {
3068 keyCode = replacementIt->second;
3069 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003070 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3071 }
3072 }
3073}
3074
Michael Wrightd02c5b62014-02-10 15:10:22 -08003075void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3076#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003077 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3078 "policyFlags=0x%x, action=0x%x, "
3079 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3080 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3081 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3082 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083#endif
3084 if (!validateKeyEvent(args->action)) {
3085 return;
3086 }
3087
3088 uint32_t policyFlags = args->policyFlags;
3089 int32_t flags = args->flags;
3090 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003091 // InputDispatcher tracks and generates key repeats on behalf of
3092 // whatever notifies it, so repeatCount should always be set to 0
3093 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3095 policyFlags |= POLICY_FLAG_VIRTUAL;
3096 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098 if (policyFlags & POLICY_FLAG_FUNCTION) {
3099 metaState |= AMETA_FUNCTION_ON;
3100 }
3101
3102 policyFlags |= POLICY_FLAG_TRUSTED;
3103
Michael Wright78f24442014-08-06 15:55:28 -07003104 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003105 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003106
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003108 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08003109 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3110 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111
Michael Wright2b3c3302018-03-02 17:19:13 +00003112 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003114 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3115 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003116 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119 bool needWake;
3120 { // acquire lock
3121 mLock.lock();
3122
3123 if (shouldSendKeyToInputFilterLocked(args)) {
3124 mLock.unlock();
3125
3126 policyFlags |= POLICY_FLAG_FILTERED;
3127 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3128 return; // event was consumed by the filter
3129 }
3130
3131 mLock.lock();
3132 }
3133
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003134 KeyEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003135 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003136 args->displayId, policyFlags, args->action, flags, keyCode,
3137 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138
3139 needWake = enqueueInboundEventLocked(newEntry);
3140 mLock.unlock();
3141 } // release lock
3142
3143 if (needWake) {
3144 mLooper->wake();
3145 }
3146}
3147
3148bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3149 return mInputFilterEnabled;
3150}
3151
3152void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3153#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003154 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3155 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003156 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3157 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003158 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003159 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3160 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3161 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3162 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 for (uint32_t i = 0; i < args->pointerCount; i++) {
3164 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 "x=%f, y=%f, pressure=%f, size=%f, "
3166 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3167 "orientation=%f",
3168 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3169 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3170 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3171 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3172 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3173 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3174 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3175 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3176 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3177 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 }
3179#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003180 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3181 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 return;
3183 }
3184
3185 uint32_t policyFlags = args->policyFlags;
3186 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003187
3188 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003189 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003190 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3191 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003192 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194
3195 bool needWake;
3196 { // acquire lock
3197 mLock.lock();
3198
3199 if (shouldSendMotionToInputFilterLocked(args)) {
3200 mLock.unlock();
3201
3202 MotionEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003203 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3204 args->action, args->actionButton, args->flags, args->edgeFlags,
3205 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3206 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3207 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3208 args->downTime, args->eventTime, args->pointerCount,
3209 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210
3211 policyFlags |= POLICY_FLAG_FILTERED;
3212 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3213 return; // event was consumed by the filter
3214 }
3215
3216 mLock.lock();
3217 }
3218
3219 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003220 MotionEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003221 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003222 args->displayId, policyFlags, args->action, args->actionButton,
3223 args->flags, args->metaState, args->buttonState,
3224 args->classification, args->edgeFlags, args->xPrecision,
3225 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3226 args->downTime, args->pointerCount, args->pointerProperties,
3227 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228
3229 needWake = enqueueInboundEventLocked(newEntry);
3230 mLock.unlock();
3231 } // release lock
3232
3233 if (needWake) {
3234 mLooper->wake();
3235 }
3236}
3237
3238bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003239 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240}
3241
3242void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3243#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003244 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003245 "switchMask=0x%08x",
3246 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247#endif
3248
3249 uint32_t policyFlags = args->policyFlags;
3250 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003251 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252}
3253
3254void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3255#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003256 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3257 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258#endif
3259
3260 bool needWake;
3261 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003262 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263
Prabir Pradhan42611e02018-11-27 14:04:02 -08003264 DeviceResetEntry* newEntry =
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003265 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266 needWake = enqueueInboundEventLocked(newEntry);
3267 } // release lock
3268
3269 if (needWake) {
3270 mLooper->wake();
3271 }
3272}
3273
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003274int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3275 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003276 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277#if DEBUG_INBOUND_EVENT_DETAILS
3278 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003279 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3280 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281#endif
3282
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003283 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284
3285 policyFlags |= POLICY_FLAG_INJECTED;
3286 if (hasInjectionPermission(injectorPid, injectorUid)) {
3287 policyFlags |= POLICY_FLAG_TRUSTED;
3288 }
3289
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003290 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003292 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003293 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3294 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003295 if (!validateKeyEvent(action)) {
3296 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003299 int32_t flags = incomingKey.getFlags();
3300 int32_t keyCode = incomingKey.getKeyCode();
3301 int32_t metaState = incomingKey.getMetaState();
3302 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003303 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003304 KeyEvent keyEvent;
Garfield Tanfbe732e2020-01-24 11:26:14 -08003305 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003306 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3307 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3308 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003310 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3311 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003312 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003313
3314 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3315 android::base::Timer t;
3316 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3317 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3318 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3319 std::to_string(t.duration().count()).c_str());
3320 }
3321 }
3322
3323 mLock.lock();
3324 KeyEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003325 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3326 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003327 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3328 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tanfbe732e2020-01-24 11:26:14 -08003329 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003330 injectedEntries.push(injectedEntry);
3331 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 }
3333
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 case AINPUT_EVENT_TYPE_MOTION: {
3335 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3336 int32_t action = motionEvent->getAction();
3337 size_t pointerCount = motionEvent->getPointerCount();
3338 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3339 int32_t actionButton = motionEvent->getActionButton();
3340 int32_t displayId = motionEvent->getDisplayId();
3341 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3342 return INPUT_EVENT_INJECTION_FAILED;
3343 }
3344
3345 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3346 nsecs_t eventTime = motionEvent->getEventTime();
3347 android::base::Timer t;
3348 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3349 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3350 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3351 std::to_string(t.duration().count()).c_str());
3352 }
3353 }
3354
3355 mLock.lock();
3356 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3357 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3358 MotionEntry* injectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003359 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3360 motionEvent->getSource(), motionEvent->getDisplayId(),
3361 policyFlags, action, actionButton, motionEvent->getFlags(),
3362 motionEvent->getMetaState(), motionEvent->getButtonState(),
3363 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3364 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003365 motionEvent->getRawXCursorPosition(),
3366 motionEvent->getRawYCursorPosition(),
3367 motionEvent->getDownTime(), uint32_t(pointerCount),
3368 pointerProperties, samplePointerCoords,
3369 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003370 injectedEntries.push(injectedEntry);
3371 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3372 sampleEventTimes += 1;
3373 samplePointerCoords += pointerCount;
3374 MotionEntry* nextInjectedEntry =
Garfield Tanfbe732e2020-01-24 11:26:14 -08003375 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003376 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003377 motionEvent->getDisplayId(), policyFlags, action,
3378 actionButton, motionEvent->getFlags(),
3379 motionEvent->getMetaState(), motionEvent->getButtonState(),
3380 motionEvent->getClassification(),
3381 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3382 motionEvent->getYPrecision(),
3383 motionEvent->getRawXCursorPosition(),
3384 motionEvent->getRawYCursorPosition(),
3385 motionEvent->getDownTime(), uint32_t(pointerCount),
3386 pointerProperties, samplePointerCoords,
3387 motionEvent->getXOffset(), motionEvent->getYOffset());
3388 injectedEntries.push(nextInjectedEntry);
3389 }
3390 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003393 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003394 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003395 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 }
3397
3398 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3399 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3400 injectionState->injectionIsAsync = true;
3401 }
3402
3403 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003404 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405
3406 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003407 while (!injectedEntries.empty()) {
3408 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3409 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 }
3411
3412 mLock.unlock();
3413
3414 if (needWake) {
3415 mLooper->wake();
3416 }
3417
3418 int32_t injectionResult;
3419 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003420 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421
3422 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3423 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3424 } else {
3425 for (;;) {
3426 injectionResult = injectionState->injectionResult;
3427 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3428 break;
3429 }
3430
3431 nsecs_t remainingTimeout = endTime - now();
3432 if (remainingTimeout <= 0) {
3433#if DEBUG_INJECTION
3434 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003435 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436#endif
3437 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3438 break;
3439 }
3440
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003441 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442 }
3443
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003444 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3445 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446 while (injectionState->pendingForegroundDispatches != 0) {
3447#if DEBUG_INJECTION
3448 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003449 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450#endif
3451 nsecs_t remainingTimeout = endTime - now();
3452 if (remainingTimeout <= 0) {
3453#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003454 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3455 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456#endif
3457 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3458 break;
3459 }
3460
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003461 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462 }
3463 }
3464 }
3465
3466 injectionState->release();
3467 } // release lock
3468
3469#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003470 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003471 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472#endif
3473
3474 return injectionResult;
3475}
3476
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003477std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003478 std::array<uint8_t, 32> calculatedHmac;
3479 std::unique_ptr<VerifiedInputEvent> result;
3480 switch (event.getType()) {
3481 case AINPUT_EVENT_TYPE_KEY: {
3482 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3483 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3484 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3485 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3486 break;
3487 }
3488 case AINPUT_EVENT_TYPE_MOTION: {
3489 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3490 VerifiedMotionEvent verifiedMotionEvent =
3491 verifiedMotionEventFromMotionEvent(motionEvent);
3492 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3493 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3494 break;
3495 }
3496 default: {
3497 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3498 return nullptr;
3499 }
3500 }
3501 if (calculatedHmac == INVALID_HMAC) {
3502 return nullptr;
3503 }
3504 if (calculatedHmac != event.getHmac()) {
3505 return nullptr;
3506 }
3507 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003508}
3509
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003511 return injectorUid == 0 ||
3512 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513}
3514
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003515void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516 InjectionState* injectionState = entry->injectionState;
3517 if (injectionState) {
3518#if DEBUG_INJECTION
3519 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003520 "injectorPid=%d, injectorUid=%d",
3521 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522#endif
3523
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003524 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525 // Log the outcome since the injector did not wait for the injection result.
3526 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003527 case INPUT_EVENT_INJECTION_SUCCEEDED:
3528 ALOGV("Asynchronous input event injection succeeded.");
3529 break;
3530 case INPUT_EVENT_INJECTION_FAILED:
3531 ALOGW("Asynchronous input event injection failed.");
3532 break;
3533 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3534 ALOGW("Asynchronous input event injection permission denied.");
3535 break;
3536 case INPUT_EVENT_INJECTION_TIMED_OUT:
3537 ALOGW("Asynchronous input event injection timed out.");
3538 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539 }
3540 }
3541
3542 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003543 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544 }
3545}
3546
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003547void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548 InjectionState* injectionState = entry->injectionState;
3549 if (injectionState) {
3550 injectionState->pendingForegroundDispatches += 1;
3551 }
3552}
3553
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003554void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555 InjectionState* injectionState = entry->injectionState;
3556 if (injectionState) {
3557 injectionState->pendingForegroundDispatches -= 1;
3558
3559 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003560 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561 }
3562 }
3563}
3564
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003565std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3566 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003567 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003568}
3569
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003571 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003572 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003573 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3574 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003575 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003576 return windowHandle;
3577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578 }
3579 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003580 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581}
3582
Mady Mellor017bcd12020-06-23 19:12:00 +00003583bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3584 for (auto& it : mWindowHandlesByDisplay) {
3585 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3586 for (const sp<InputWindowHandle>& handle : windowHandles) {
3587 if (handle->getToken() == windowHandle->getToken()) {
3588 if (windowHandle->getInfo()->displayId != it.first) {
3589 ALOGE("Found window %s in display %" PRId32
3590 ", but it should belong to display %" PRId32,
3591 windowHandle->getName().c_str(), it.first,
3592 windowHandle->getInfo()->displayId);
3593 }
3594 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 }
3597 }
3598 return false;
3599}
3600
Robert Carr5c8a0262018-10-03 16:30:44 -07003601sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3602 size_t count = mInputChannelsByToken.count(token);
3603 if (count == 0) {
3604 return nullptr;
3605 }
3606 return mInputChannelsByToken.at(token);
3607}
3608
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003609void InputDispatcher::updateWindowHandlesForDisplayLocked(
3610 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3611 if (inputWindowHandles.empty()) {
3612 // Remove all handles on a display if there are no windows left.
3613 mWindowHandlesByDisplay.erase(displayId);
3614 return;
3615 }
3616
3617 // Since we compare the pointer of input window handles across window updates, we need
3618 // to make sure the handle object for the same window stays unchanged across updates.
3619 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003620 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003621 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003622 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003623 }
3624
3625 std::vector<sp<InputWindowHandle>> newHandles;
3626 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3627 if (!handle->updateInfo()) {
3628 // handle no longer valid
3629 continue;
3630 }
3631
3632 const InputWindowInfo* info = handle->getInfo();
3633 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3634 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3635 const bool noInputChannel =
3636 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3637 const bool canReceiveInput =
3638 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3639 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3640 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003641 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003642 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003643 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003644 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003645 }
3646
3647 if (info->displayId != displayId) {
3648 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3649 handle->getName().c_str(), displayId, info->displayId);
3650 continue;
3651 }
3652
Robert Carredd13602020-04-13 17:24:34 -07003653 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3654 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003655 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003656 oldHandle->updateFrom(handle);
3657 newHandles.push_back(oldHandle);
3658 } else {
3659 newHandles.push_back(handle);
3660 }
3661 }
3662
3663 // Insert or replace
3664 mWindowHandlesByDisplay[displayId] = newHandles;
3665}
3666
Arthur Hung72d8dc32020-03-28 00:48:39 +00003667void InputDispatcher::setInputWindows(
3668 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3669 { // acquire lock
3670 std::scoped_lock _l(mLock);
3671 for (auto const& i : handlesPerDisplay) {
3672 setInputWindowsLocked(i.second, i.first);
3673 }
3674 }
3675 // Wake up poll loop since it may need to make new input dispatching choices.
3676 mLooper->wake();
3677}
3678
Arthur Hungb92218b2018-08-14 12:00:21 +08003679/**
3680 * Called from InputManagerService, update window handle list by displayId that can receive input.
3681 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3682 * If set an empty list, remove all handles from the specific display.
3683 * For focused handle, check if need to change and send a cancel event to previous one.
3684 * For removed handle, check if need to send a cancel event if already in touch.
3685 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003686void InputDispatcher::setInputWindowsLocked(
3687 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003688 if (DEBUG_FOCUS) {
3689 std::string windowList;
3690 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3691 windowList += iwh->getName() + " ";
3692 }
3693 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3694 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695
Arthur Hung72d8dc32020-03-28 00:48:39 +00003696 // Copy old handles for release if they are no longer present.
3697 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698
Arthur Hung72d8dc32020-03-28 00:48:39 +00003699 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003700
Arthur Hung72d8dc32020-03-28 00:48:39 +00003701 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3702 bool foundHoveredWindow = false;
3703 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3704 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3705 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3706 windowHandle->getInfo()->visible) {
3707 newFocusedWindowHandle = windowHandle;
3708 }
3709 if (windowHandle == mLastHoverWindowHandle) {
3710 foundHoveredWindow = true;
3711 }
3712 }
3713
3714 if (!foundHoveredWindow) {
3715 mLastHoverWindowHandle = nullptr;
3716 }
3717
3718 sp<InputWindowHandle> oldFocusedWindowHandle =
3719 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3720
3721 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3722 if (oldFocusedWindowHandle != nullptr) {
3723 if (DEBUG_FOCUS) {
3724 ALOGD("Focus left window: %s in display %" PRId32,
3725 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003726 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003727 sp<InputChannel> focusedInputChannel =
3728 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3729 if (focusedInputChannel != nullptr) {
3730 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3731 "focus left window");
3732 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3733 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003734 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003735 mFocusedWindowHandlesByDisplay.erase(displayId);
3736 }
3737 if (newFocusedWindowHandle != nullptr) {
3738 if (DEBUG_FOCUS) {
3739 ALOGD("Focus entered window: %s in display %" PRId32,
3740 newFocusedWindowHandle->getName().c_str(), displayId);
3741 }
3742 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3743 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 }
3745
Arthur Hung72d8dc32020-03-28 00:48:39 +00003746 if (mFocusedDisplayId == displayId) {
3747 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003751 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3752 mTouchStatesByDisplay.find(displayId);
3753 if (stateIt != mTouchStatesByDisplay.end()) {
3754 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003755 for (size_t i = 0; i < state.windows.size();) {
3756 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003757 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003758 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003759 ALOGD("Touched window was removed: %s in display %" PRId32,
3760 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003761 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003762 sp<InputChannel> touchedInputChannel =
3763 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3764 if (touchedInputChannel != nullptr) {
3765 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3766 "touched window was removed");
3767 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003769 state.windows.erase(state.windows.begin() + i);
3770 } else {
3771 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 }
3773 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003774 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003775
Arthur Hung72d8dc32020-03-28 00:48:39 +00003776 // Release information for windows that are no longer present.
3777 // This ensures that unused input channels are released promptly.
3778 // Otherwise, they might stick around until the window handle is destroyed
3779 // which might not happen until the next GC.
3780 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003781 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003782 if (DEBUG_FOCUS) {
3783 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003784 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003785 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003786 }
chaviw291d88a2019-02-14 10:33:58 -08003787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788}
3789
3790void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003791 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003792 if (DEBUG_FOCUS) {
3793 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3794 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003797 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798
Tiger Huang721e26f2018-07-24 22:26:19 +08003799 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3800 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07003801
3802 if (oldFocusedApplicationHandle == mAwaitedFocusedApplication &&
3803 inputApplicationHandle != oldFocusedApplicationHandle) {
3804 resetNoFocusedWindowTimeoutLocked();
3805 }
3806
Yi Kong9b14ac62018-07-17 13:48:38 -07003807 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003808 if (oldFocusedApplicationHandle != inputApplicationHandle) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003809 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003811 } else if (oldFocusedApplicationHandle != nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003812 oldFocusedApplicationHandle.clear();
3813 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 } // release lock
3816
3817 // Wake up poll loop since it may need to make new input dispatching choices.
3818 mLooper->wake();
3819}
3820
Tiger Huang721e26f2018-07-24 22:26:19 +08003821/**
3822 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3823 * the display not specified.
3824 *
3825 * We track any unreleased events for each window. If a window loses the ability to receive the
3826 * released event, we will send a cancel event to it. So when the focused display is changed, we
3827 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3828 * display. The display-specified events won't be affected.
3829 */
3830void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003831 if (DEBUG_FOCUS) {
3832 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3833 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003834 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003835 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003836
3837 if (mFocusedDisplayId != displayId) {
3838 sp<InputWindowHandle> oldFocusedWindowHandle =
3839 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3840 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003841 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003842 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003843 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003844 CancelationOptions
3845 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3846 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003847 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003848 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3849 }
3850 }
3851 mFocusedDisplayId = displayId;
3852
3853 // Sanity check
3854 sp<InputWindowHandle> newFocusedWindowHandle =
3855 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003856 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003857
Tiger Huang721e26f2018-07-24 22:26:19 +08003858 if (newFocusedWindowHandle == nullptr) {
3859 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3860 if (!mFocusedWindowHandlesByDisplay.empty()) {
3861 ALOGE("But another display has a focused window:");
3862 for (auto& it : mFocusedWindowHandlesByDisplay) {
3863 const int32_t displayId = it.first;
3864 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003865 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3866 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003867 }
3868 }
3869 }
3870 }
3871
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003872 if (DEBUG_FOCUS) {
3873 logDispatchStateLocked();
3874 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003875 } // release lock
3876
3877 // Wake up poll loop since it may need to make new input dispatching choices.
3878 mLooper->wake();
3879}
3880
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003882 if (DEBUG_FOCUS) {
3883 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885
3886 bool changed;
3887 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003888 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889
3890 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3891 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07003892 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 }
3894
3895 if (mDispatchEnabled && !enabled) {
3896 resetAndDropEverythingLocked("dispatcher is being disabled");
3897 }
3898
3899 mDispatchEnabled = enabled;
3900 mDispatchFrozen = frozen;
3901 changed = true;
3902 } else {
3903 changed = false;
3904 }
3905
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003906 if (DEBUG_FOCUS) {
3907 logDispatchStateLocked();
3908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909 } // release lock
3910
3911 if (changed) {
3912 // Wake up poll loop since it may need to make new input dispatching choices.
3913 mLooper->wake();
3914 }
3915}
3916
3917void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003918 if (DEBUG_FOCUS) {
3919 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921
3922 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003923 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924
3925 if (mInputFilterEnabled == enabled) {
3926 return;
3927 }
3928
3929 mInputFilterEnabled = enabled;
3930 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3931 } // release lock
3932
3933 // Wake up poll loop since there might be work to do to drop everything.
3934 mLooper->wake();
3935}
3936
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003937void InputDispatcher::setInTouchMode(bool inTouchMode) {
3938 std::scoped_lock lock(mLock);
3939 mInTouchMode = inTouchMode;
3940}
3941
chaviwfbe5d9c2018-12-26 12:23:37 -08003942bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3943 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003944 if (DEBUG_FOCUS) {
3945 ALOGD("Trivial transfer to same window.");
3946 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003947 return true;
3948 }
3949
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003951 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952
chaviwfbe5d9c2018-12-26 12:23:37 -08003953 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3954 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003955 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003956 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 return false;
3958 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003959 if (DEBUG_FOCUS) {
3960 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3961 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003964 if (DEBUG_FOCUS) {
3965 ALOGD("Cannot transfer focus because windows are on different displays.");
3966 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 return false;
3968 }
3969
3970 bool found = false;
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07003971 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
3972 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003973 for (size_t i = 0; i < state.windows.size(); i++) {
3974 const TouchedWindow& touchedWindow = state.windows[i];
3975 if (touchedWindow.windowHandle == fromWindowHandle) {
3976 int32_t oldTargetFlags = touchedWindow.targetFlags;
3977 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003979 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003981 int32_t newTargetFlags = oldTargetFlags &
3982 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3983 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003984 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985
Jeff Brownf086ddb2014-02-11 14:28:48 -08003986 found = true;
3987 goto Found;
3988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 }
3990 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003991 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003993 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003994 if (DEBUG_FOCUS) {
3995 ALOGD("Focus transfer failed because from window did not have focus.");
3996 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997 return false;
3998 }
3999
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004000 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4001 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004002 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004003 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004004 CancelationOptions
4005 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4006 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004008 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 }
4010
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004011 if (DEBUG_FOCUS) {
4012 logDispatchStateLocked();
4013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014 } // release lock
4015
4016 // Wake up poll loop since it may need to make new input dispatching choices.
4017 mLooper->wake();
4018 return true;
4019}
4020
4021void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004022 if (DEBUG_FOCUS) {
4023 ALOGD("Resetting and dropping all events (%s).", reason);
4024 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025
4026 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4027 synthesizeCancelationEventsForAllConnectionsLocked(options);
4028
4029 resetKeyRepeatLocked();
4030 releasePendingEventLocked();
4031 drainInboundQueueLocked();
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004032 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004034 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004035 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004037 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038}
4039
4040void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004041 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042 dumpDispatchStateLocked(dump);
4043
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004044 std::istringstream stream(dump);
4045 std::string line;
4046
4047 while (std::getline(stream, line, '\n')) {
4048 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049 }
4050}
4051
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004052void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004053 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4054 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4055 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004056 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057
Tiger Huang721e26f2018-07-24 22:26:19 +08004058 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4059 dump += StringPrintf(INDENT "FocusedApplications:\n");
4060 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4061 const int32_t displayId = it.first;
4062 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004063 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004064 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004065 displayId, applicationHandle->getName().c_str(),
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004066 ns2ms(applicationHandle
4067 ->getDispatchingTimeout(
4068 DEFAULT_INPUT_DISPATCHING_TIMEOUT)
4069 .count()));
Tiger Huang721e26f2018-07-24 22:26:19 +08004070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004072 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004074
4075 if (!mFocusedWindowHandlesByDisplay.empty()) {
4076 dump += StringPrintf(INDENT "FocusedWindows:\n");
4077 for (auto& it : mFocusedWindowHandlesByDisplay) {
4078 const int32_t displayId = it.first;
4079 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004080 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4081 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004082 }
4083 } else {
4084 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004087 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004088 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004089 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4090 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004091 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004092 state.displayId, toString(state.down), toString(state.split),
4093 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004094 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004095 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004096 for (size_t i = 0; i < state.windows.size(); i++) {
4097 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004098 dump += StringPrintf(INDENT4
4099 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4100 i, touchedWindow.windowHandle->getName().c_str(),
4101 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004102 }
4103 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004104 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004105 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004106 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004107 dump += INDENT3 "Portal windows:\n";
4108 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004109 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004110 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4111 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004112 }
4113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 }
4115 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004116 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 }
4118
Arthur Hungb92218b2018-08-14 12:00:21 +08004119 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004120 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004121 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004122 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004123 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004124 dump += INDENT2 "Windows:\n";
4125 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004126 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004127 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128
Arthur Hungb92218b2018-08-14 12:00:21 +08004129 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004130 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004131 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4132 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004133 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004134 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004135 i, windowInfo->name.c_str(), windowInfo->displayId,
4136 windowInfo->portalToDisplayId,
4137 toString(windowInfo->paused),
4138 toString(windowInfo->hasFocus),
4139 toString(windowInfo->hasWallpaper),
4140 toString(windowInfo->visible),
4141 toString(windowInfo->canReceiveKeys),
4142 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004143 windowInfo->layoutParamsType, windowInfo->frameLeft,
4144 windowInfo->frameTop, windowInfo->frameRight,
4145 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4146 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004147 dumpRegion(dump, windowInfo->touchableRegion);
4148 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004149 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4150 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004151 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004152 ns2ms(windowInfo->dispatchingTimeout));
Arthur Hungb92218b2018-08-14 12:00:21 +08004153 }
4154 } else {
4155 dump += INDENT2 "Windows: <none>\n";
4156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 }
4158 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004159 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 }
4161
Michael Wright3dd60e22019-03-27 22:06:44 +00004162 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004163 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004164 const std::vector<Monitor>& monitors = it.second;
4165 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4166 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004167 }
4168 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004169 const std::vector<Monitor>& monitors = it.second;
4170 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4171 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004174 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 }
4176
4177 nsecs_t currentTime = now();
4178
4179 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004180 if (!mRecentQueue.empty()) {
4181 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4182 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004183 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004185 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 }
4187 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004188 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 }
4190
4191 // Dump event currently being dispatched.
4192 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004193 dump += INDENT "PendingEvent:\n";
4194 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004196 dump += StringPrintf(", age=%" PRId64 "ms\n",
4197 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004199 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 }
4201
4202 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004203 if (!mInboundQueue.empty()) {
4204 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4205 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004206 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 entry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004208 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209 }
4210 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004211 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 }
4213
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004214 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004215 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004216 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4217 const KeyReplacement& replacement = pair.first;
4218 int32_t newKeyCode = pair.second;
4219 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004220 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004221 }
4222 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004223 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004224 }
4225
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004226 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004227 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004228 for (const auto& pair : mConnectionsByFd) {
4229 const sp<Connection>& connection = pair.second;
4230 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004231 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004232 pair.first, connection->getInputChannelName().c_str(),
4233 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004234 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004236 if (!connection->outboundQueue.empty()) {
4237 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4238 connection->outboundQueue.size());
4239 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 dump.append(INDENT4);
4241 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004242 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4243 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004244 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004245 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246 }
4247 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004248 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 }
4250
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004251 if (!connection->waitQueue.empty()) {
4252 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4253 connection->waitQueue.size());
4254 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004255 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004257 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004258 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004259 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004260 ns2ms(currentTime - entry->eventEntry->eventTime),
4261 ns2ms(currentTime - entry->deliveryTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 }
4263 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004264 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 }
4266 }
4267 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004268 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 }
4270
4271 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004272 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4273 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004275 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 }
4277
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004278 dump += INDENT "Configuration:\n";
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004279 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4280 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4281 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282}
4283
Michael Wright3dd60e22019-03-27 22:06:44 +00004284void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4285 const size_t numMonitors = monitors.size();
4286 for (size_t i = 0; i < numMonitors; i++) {
4287 const Monitor& monitor = monitors[i];
4288 const sp<InputChannel>& channel = monitor.inputChannel;
4289 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4290 dump += "\n";
4291 }
4292}
4293
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004294status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004296 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297#endif
4298
4299 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004300 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004301 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004302 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004304 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 return BAD_VALUE;
4306 }
4307
Garfield Tan1c7bc862020-01-28 13:24:04 -08004308 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309
4310 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004311 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004312 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4315 } // release lock
4316
4317 // Wake the looper because some connections have changed.
4318 mLooper->wake();
4319 return OK;
4320}
4321
Michael Wright3dd60e22019-03-27 22:06:44 +00004322status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004323 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004324 { // acquire lock
4325 std::scoped_lock _l(mLock);
4326
4327 if (displayId < 0) {
4328 ALOGW("Attempted to register input monitor without a specified display.");
4329 return BAD_VALUE;
4330 }
4331
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004332 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004333 ALOGW("Attempted to register input monitor without an identifying token.");
4334 return BAD_VALUE;
4335 }
4336
Garfield Tan1c7bc862020-01-28 13:24:04 -08004337 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004338
4339 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004340 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004341 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004342
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004343 auto& monitorsByDisplay =
4344 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004345 monitorsByDisplay[displayId].emplace_back(inputChannel);
4346
4347 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004348 }
4349 // Wake the looper because some connections have changed.
4350 mLooper->wake();
4351 return OK;
4352}
4353
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4355#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004356 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357#endif
4358
4359 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004360 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361
4362 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4363 if (status) {
4364 return status;
4365 }
4366 } // release lock
4367
4368 // Wake the poll loop because removing the connection may have changed the current
4369 // synchronization state.
4370 mLooper->wake();
4371 return OK;
4372}
4373
4374status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004375 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004376 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004377 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004379 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 return BAD_VALUE;
4381 }
4382
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004383 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004384 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004385
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386 if (connection->monitor) {
4387 removeMonitorChannelLocked(inputChannel);
4388 }
4389
4390 mLooper->removeFd(inputChannel->getFd());
4391
4392 nsecs_t currentTime = now();
4393 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4394
4395 connection->status = Connection::STATUS_ZOMBIE;
4396 return OK;
4397}
4398
4399void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004400 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4401 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4402}
4403
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004404void InputDispatcher::removeMonitorChannelLocked(
4405 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004406 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004407 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004408 std::vector<Monitor>& monitors = it->second;
4409 const size_t numMonitors = monitors.size();
4410 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004411 if (monitors[i].inputChannel == inputChannel) {
4412 monitors.erase(monitors.begin() + i);
4413 break;
4414 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004415 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004416 if (monitors.empty()) {
4417 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004418 } else {
4419 ++it;
4420 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 }
4422}
4423
Michael Wright3dd60e22019-03-27 22:06:44 +00004424status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4425 { // acquire lock
4426 std::scoped_lock _l(mLock);
4427 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4428
4429 if (!foundDisplayId) {
4430 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4431 return BAD_VALUE;
4432 }
4433 int32_t displayId = foundDisplayId.value();
4434
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004435 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4436 mTouchStatesByDisplay.find(displayId);
4437 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004438 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4439 return BAD_VALUE;
4440 }
4441
Siarhei Vishniakoubde3d9e2020-03-24 19:05:54 -07004442 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004443 std::optional<int32_t> foundDeviceId;
4444 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004445 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004446 foundDeviceId = state.deviceId;
4447 }
4448 }
4449 if (!foundDeviceId || !state.down) {
4450 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004451 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004452 return BAD_VALUE;
4453 }
4454 int32_t deviceId = foundDeviceId.value();
4455
4456 // Send cancel events to all the input channels we're stealing from.
4457 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004458 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004459 options.deviceId = deviceId;
4460 options.displayId = displayId;
4461 for (const TouchedWindow& window : state.windows) {
4462 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004463 if (channel != nullptr) {
4464 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4465 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004466 }
4467 // Then clear the current touch state so we stop dispatching to them as well.
4468 state.filterNonMonitors();
4469 }
4470 return OK;
4471}
4472
Michael Wright3dd60e22019-03-27 22:06:44 +00004473std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4474 const sp<IBinder>& token) {
4475 for (const auto& it : mGestureMonitorsByDisplay) {
4476 const std::vector<Monitor>& monitors = it.second;
4477 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004478 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004479 return it.first;
4480 }
4481 }
4482 }
4483 return std::nullopt;
4484}
4485
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004486sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004487 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004488 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004489 }
4490
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004491 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004492 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004493 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004494 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 }
4496 }
Robert Carr4e670e52018-08-15 13:26:12 -07004497
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004498 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499}
4500
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004501void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004502 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004503 removeByValue(mConnectionsByFd, connection);
4504}
4505
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004506void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4507 const sp<Connection>& connection, uint32_t seq,
4508 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004509 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4510 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511 commandEntry->connection = connection;
4512 commandEntry->eventTime = currentTime;
4513 commandEntry->seq = seq;
4514 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004515 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004516}
4517
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004518void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4519 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004521 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004523 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4524 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004526 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527}
4528
chaviw0c06c6e2019-01-09 13:27:07 -08004529void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004530 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004531 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4532 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004533 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4534 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004535 commandEntry->oldToken = oldToken;
4536 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004537 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004538}
4539
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004540void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4541 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4542 // is already healthy again. Don't raise ANR in this situation
4543 if (connection->waitQueue.empty()) {
4544 ALOGI("Not raising ANR because the connection %s has recovered",
4545 connection->inputChannel->getName().c_str());
4546 return;
4547 }
4548 /**
4549 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4550 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4551 * has changed. This could cause newer entries to time out before the already dispatched
4552 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4553 * processes the events linearly. So providing information about the oldest entry seems to be
4554 * most useful.
4555 */
4556 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4557 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4558 std::string reason =
4559 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4560 connection->inputChannel->getName().c_str(),
4561 ns2ms(currentWait),
4562 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004564 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4565 reason);
4566
4567 std::unique_ptr<CommandEntry> commandEntry =
4568 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4569 commandEntry->inputApplicationHandle = nullptr;
4570 commandEntry->inputChannel = connection->inputChannel;
4571 commandEntry->reason = std::move(reason);
4572 postCommandLocked(std::move(commandEntry));
4573}
4574
4575void InputDispatcher::onAnrLocked(const sp<InputApplicationHandle>& application) {
4576 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4577 application->getName().c_str());
4578
4579 updateLastAnrStateLocked(application, reason);
4580
4581 std::unique_ptr<CommandEntry> commandEntry =
4582 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4583 commandEntry->inputApplicationHandle = application;
4584 commandEntry->inputChannel = nullptr;
4585 commandEntry->reason = std::move(reason);
4586 postCommandLocked(std::move(commandEntry));
4587}
4588
4589void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4590 const std::string& reason) {
4591 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4592 updateLastAnrStateLocked(windowLabel, reason);
4593}
4594
4595void InputDispatcher::updateLastAnrStateLocked(const sp<InputApplicationHandle>& application,
4596 const std::string& reason) {
4597 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4598 updateLastAnrStateLocked(windowLabel, reason);
4599}
4600
4601void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4602 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004604 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 struct tm tm;
4606 localtime_r(&t, &tm);
4607 char timestr[64];
4608 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004609 mLastAnrState.clear();
4610 mLastAnrState += INDENT "ANR:\n";
4611 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004612 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4613 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004614 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615}
4616
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004617void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618 mLock.unlock();
4619
4620 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4621
4622 mLock.lock();
4623}
4624
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004625void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626 sp<Connection> connection = commandEntry->connection;
4627
4628 if (connection->status != Connection::STATUS_ZOMBIE) {
4629 mLock.unlock();
4630
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004631 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632
4633 mLock.lock();
4634 }
4635}
4636
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004637void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004638 sp<IBinder> oldToken = commandEntry->oldToken;
4639 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004640 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004641 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004642 mLock.lock();
4643}
4644
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004645void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004646 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004647 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004648 mLock.unlock();
4649
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004650 const nsecs_t timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004651 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652
4653 mLock.lock();
4654
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004655 if (timeoutExtension > 0) {
4656 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4657 } else {
4658 // stop waking up for events in this connection, it is already not responding
4659 sp<Connection> connection = getConnectionLocked(token);
4660 if (connection == nullptr) {
4661 return;
4662 }
4663 cancelEventsForAnrLocked(connection);
4664 }
4665}
4666
4667void InputDispatcher::extendAnrTimeoutsLocked(const sp<InputApplicationHandle>& application,
4668 const sp<IBinder>& connectionToken,
4669 nsecs_t timeoutExtension) {
4670 sp<Connection> connection = getConnectionLocked(connectionToken);
4671 if (connection == nullptr) {
4672 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4673 // Maybe ANR happened because there's no focused window?
4674 mNoFocusedWindowTimeoutTime = now() + timeoutExtension;
4675 mAwaitedFocusedApplication = application;
4676 } else {
4677 // It's also possible that the connection already disappeared. No action necessary.
4678 }
4679 return;
4680 }
4681
4682 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
4683 connection->inputChannel->getName().c_str(), ns2ms(timeoutExtension));
4684
4685 connection->responsive = true;
4686 const nsecs_t newTimeout = now() + timeoutExtension;
4687 for (DispatchEntry* entry : connection->waitQueue) {
4688 if (newTimeout >= entry->timeoutTime) {
4689 // Already removed old entries when connection was marked unresponsive
4690 entry->timeoutTime = newTimeout;
4691 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4692 }
4693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694}
4695
4696void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4697 CommandEntry* commandEntry) {
4698 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004699 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700
4701 mLock.unlock();
4702
Michael Wright2b3c3302018-03-02 17:19:13 +00004703 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004704 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004705 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004706 : nullptr;
4707 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004708 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4709 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004710 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712
4713 mLock.lock();
4714
4715 if (delay < 0) {
4716 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4717 } else if (!delay) {
4718 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4719 } else {
4720 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4721 entry->interceptKeyWakeupTime = now() + delay;
4722 }
4723 entry->release();
4724}
4725
chaviwfd6d3512019-03-25 13:23:49 -07004726void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4727 mLock.unlock();
4728 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4729 mLock.lock();
4730}
4731
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004732/**
4733 * Connection is responsive if it has no events in the waitQueue that are older than the
4734 * current time.
4735 */
4736static bool isConnectionResponsive(const Connection& connection) {
4737 const nsecs_t currentTime = now();
4738 for (const DispatchEntry* entry : connection.waitQueue) {
4739 if (entry->timeoutTime < currentTime) {
4740 return false;
4741 }
4742 }
4743 return true;
4744}
4745
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004746void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004748 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004750 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751
4752 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004753 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004754 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004755 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004757 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004758 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004759 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouffaa2b12020-05-26 21:43:02 -07004760 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4761 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004762 }
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07004763 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004764
4765 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004766 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004767 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4768 restartEvent =
4769 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004770 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004771 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4772 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4773 handled);
4774 } else {
4775 restartEvent = false;
4776 }
4777
4778 // Dequeue the event and start the next cycle.
Siarhei Vishniakoude1bc4a2020-05-26 22:39:43 -07004779 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004780 // contents of the wait queue to have been drained, so we need to double-check
4781 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004782 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4783 if (dispatchEntryIt != connection->waitQueue.end()) {
4784 dispatchEntry = *dispatchEntryIt;
4785 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoue4623042020-03-25 16:16:40 -07004786 mAnrTracker.erase(dispatchEntry->timeoutTime,
4787 connection->inputChannel->getConnectionToken());
4788 if (!connection->responsive) {
4789 connection->responsive = isConnectionResponsive(*connection);
4790 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004791 traceWaitQueueLength(connection);
4792 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004793 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004794 traceOutboundQueueLength(connection);
4795 } else {
4796 releaseDispatchEntry(dispatchEntry);
4797 }
4798 }
4799
4800 // Start the next dispatch cycle for this connection.
4801 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802}
4803
4804bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004805 DispatchEntry* dispatchEntry,
4806 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004807 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004808 if (!handled) {
4809 // Report the key as unhandled, since the fallback was not handled.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004810 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004811 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004812 return false;
4813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004815 // Get the fallback key state.
4816 // Clear it out after dispatching the UP.
4817 int32_t originalKeyCode = keyEntry->keyCode;
4818 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4819 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4820 connection->inputState.removeFallbackKey(originalKeyCode);
4821 }
4822
4823 if (handled || !dispatchEntry->hasForegroundTarget()) {
4824 // If the application handles the original key for which we previously
4825 // generated a fallback or if the window is not a foreground window,
4826 // then cancel the associated fallback key, if any.
4827 if (fallbackKeyCode != -1) {
4828 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004829#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004830 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004831 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4832 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4833 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004835 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004836 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004837
4838 mLock.unlock();
4839
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004840 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004841 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842
4843 mLock.lock();
4844
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004845 // Cancel the fallback key.
4846 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004848 "application handled the original non-fallback key "
4849 "or is no longer a foreground target, "
4850 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 options.keyCode = fallbackKeyCode;
4852 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004854 connection->inputState.removeFallbackKey(originalKeyCode);
4855 }
4856 } else {
4857 // If the application did not handle a non-fallback key, first check
4858 // that we are in a good state to perform unhandled key event processing
4859 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004860 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004861 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004863 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004864 "since this is not an initial down. "
4865 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4866 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004868 return false;
4869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004871 // Dispatch the unhandled key to the policy.
4872#if DEBUG_OUTBOUND_EVENT_DETAILS
4873 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004874 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4875 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004876#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004877 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004878
4879 mLock.unlock();
4880
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004881 bool fallback =
4882 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4883 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004884
4885 mLock.lock();
4886
4887 if (connection->status != Connection::STATUS_NORMAL) {
4888 connection->inputState.removeFallbackKey(originalKeyCode);
4889 return false;
4890 }
4891
4892 // Latch the fallback keycode for this key on an initial down.
4893 // The fallback keycode cannot change at any other point in the lifecycle.
4894 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004895 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004896 fallbackKeyCode = event.getKeyCode();
4897 } else {
4898 fallbackKeyCode = AKEYCODE_UNKNOWN;
4899 }
4900 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4901 }
4902
4903 ALOG_ASSERT(fallbackKeyCode != -1);
4904
4905 // Cancel the fallback key if the policy decides not to send it anymore.
4906 // We will continue to dispatch the key to the policy but we will no
4907 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004908 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4909 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004910#if DEBUG_OUTBOUND_EVENT_DETAILS
4911 if (fallback) {
4912 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004913 "as a fallback for %d, but on the DOWN it had requested "
4914 "to send %d instead. Fallback canceled.",
4915 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004916 } else {
4917 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004918 "but on the DOWN it had requested to send %d. "
4919 "Fallback canceled.",
4920 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004921 }
4922#endif
4923
4924 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4925 "canceling fallback, policy no longer desires it");
4926 options.keyCode = fallbackKeyCode;
4927 synthesizeCancelationEventsForConnectionLocked(connection, options);
4928
4929 fallback = false;
4930 fallbackKeyCode = AKEYCODE_UNKNOWN;
4931 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004932 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004933 }
4934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935
4936#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004937 {
4938 std::string msg;
4939 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4940 connection->inputState.getFallbackKeys();
4941 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004942 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004944 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004945 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004946 }
4947#endif
4948
4949 if (fallback) {
4950 // Restart the dispatch cycle using the fallback key.
4951 keyEntry->eventTime = event.getEventTime();
4952 keyEntry->deviceId = event.getDeviceId();
4953 keyEntry->source = event.getSource();
4954 keyEntry->displayId = event.getDisplayId();
4955 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4956 keyEntry->keyCode = fallbackKeyCode;
4957 keyEntry->scanCode = event.getScanCode();
4958 keyEntry->metaState = event.getMetaState();
4959 keyEntry->repeatCount = event.getRepeatCount();
4960 keyEntry->downTime = event.getDownTime();
4961 keyEntry->syntheticRepeat = false;
4962
4963#if DEBUG_OUTBOUND_EVENT_DETAILS
4964 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004965 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4966 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004967#endif
4968 return true; // restart the event
4969 } else {
4970#if DEBUG_OUTBOUND_EVENT_DETAILS
4971 ALOGD("Unhandled key event: No fallback key.");
4972#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004973
4974 // Report the key as unhandled, since there is no fallback key.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004975 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976 }
4977 }
4978 return false;
4979}
4980
4981bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004982 DispatchEntry* dispatchEntry,
4983 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004984 return false;
4985}
4986
4987void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4988 mLock.unlock();
4989
4990 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4991
4992 mLock.lock();
4993}
4994
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004995KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
4996 KeyEvent event;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08004997 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tanfbe732e2020-01-24 11:26:14 -08004998 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
4999 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005000 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001}
5002
Siarhei Vishniakou7f0a4392020-03-24 20:49:09 -07005003void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5004 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005005 // TODO Write some statistics about how long we spend waiting.
5006}
5007
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005008/**
5009 * Report the touch event latency to the statsd server.
5010 * Input events are reported for statistics if:
5011 * - This is a touchscreen event
5012 * - InputFilter is not enabled
5013 * - Event is not injected or synthesized
5014 *
5015 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5016 * from getting aggregated with the "old" data.
5017 */
5018void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5019 REQUIRES(mLock) {
5020 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5021 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5022 if (!reportForStatistics) {
5023 return;
5024 }
5025
5026 if (mTouchStatistics.shouldReport()) {
5027 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5028 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5029 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5030 mTouchStatistics.reset();
5031 }
5032 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5033 mTouchStatistics.addValue(latencyMicros);
5034}
5035
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036void InputDispatcher::traceInboundQueueLengthLocked() {
5037 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005038 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039 }
5040}
5041
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005042void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005043 if (ATRACE_ENABLED()) {
5044 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005045 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005046 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047 }
5048}
5049
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005050void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051 if (ATRACE_ENABLED()) {
5052 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005053 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005054 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055 }
5056}
5057
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005058void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005059 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005061 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062 dumpDispatchStateLocked(dump);
5063
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005064 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005065 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005066 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005067 }
5068}
5069
5070void InputDispatcher::monitor() {
5071 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005072 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005073 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005074 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075}
5076
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005077/**
5078 * Wake up the dispatcher and wait until it processes all events and commands.
5079 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5080 * this method can be safely called from any thread, as long as you've ensured that
5081 * the work you are interested in completing has already been queued.
5082 */
5083bool InputDispatcher::waitForIdle() {
5084 /**
5085 * Timeout should represent the longest possible time that a device might spend processing
5086 * events and commands.
5087 */
5088 constexpr std::chrono::duration TIMEOUT = 100ms;
5089 std::unique_lock lock(mLock);
5090 mLooper->wake();
5091 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5092 return result == std::cv_status::no_timeout;
5093}
5094
Garfield Tane84e6f92019-08-29 17:28:41 -07005095} // namespace android::inputdispatcher