blob: 9deea63257cc0d65629f1bdb032486fb0eb5f892 [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 Vishniakou4cb50ca2020-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 Vishniakoud44dddf2020-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
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500162static int64_t millis(std::chrono::nanoseconds t) {
163 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
164}
165
Michael Wright7b159c92015-05-14 14:48:03 +0100166static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700167 const PointerProperties* pointerProperties) {
168 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800169 ALOGE("Motion event has invalid action code 0x%x", action);
170 return false;
171 }
172 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000173 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 return false;
176 }
177 BitSet32 pointerIdBits;
178 for (size_t i = 0; i < pointerCount; i++) {
179 int32_t id = pointerProperties[i].id;
180 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700181 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
182 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800183 return false;
184 }
185 if (pointerIdBits.hasBit(id)) {
186 ALOGE("Motion event has duplicate pointer id %d", id);
187 return false;
188 }
189 pointerIdBits.markBit(id);
190 }
191 return true;
192}
193
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800194static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800196 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800197 return;
198 }
199
200 bool first = true;
201 Region::const_iterator cur = region.begin();
202 Region::const_iterator const tail = region.end();
203 while (cur != tail) {
204 if (first) {
205 first = false;
206 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800207 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800209 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 cur++;
211 }
212}
213
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700214/**
215 * Find the entry in std::unordered_map by key, and return it.
216 * If the entry is not found, return a default constructed entry.
217 *
218 * Useful when the entries are vectors, since an empty vector will be returned
219 * if the entry is not found.
220 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
221 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700222template <typename K, typename V>
223static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700224 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700225 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800226}
227
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700228/**
229 * Find the entry in std::unordered_map by value, and remove it.
230 * If more than one entry has the same value, then all matching
231 * key-value pairs will be removed.
232 *
233 * Return true if at least one value has been removed.
234 */
235template <typename K, typename V>
236static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
237 bool removed = false;
238 for (auto it = map.begin(); it != map.end();) {
239 if (it->second == value) {
240 it = map.erase(it);
241 removed = true;
242 } else {
243 it++;
244 }
245 }
246 return removed;
247}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800248
chaviwaf87b3e2019-10-01 16:59:28 -0700249static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
250 if (first == second) {
251 return true;
252 }
253
254 if (first == nullptr || second == nullptr) {
255 return false;
256 }
257
258 return first->getToken() == second->getToken();
259}
260
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800261static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
262 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
263}
264
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000265static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
266 EventEntry* eventEntry,
267 int32_t inputTargetFlags) {
268 if (inputTarget.useDefaultPointerInfo()) {
269 const PointerInfo& pointerInfo = inputTarget.getDefaultPointerInfo();
270 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
271 inputTargetFlags, pointerInfo.xOffset,
272 pointerInfo.yOffset, inputTarget.globalScaleFactor,
273 pointerInfo.windowXScale, pointerInfo.windowYScale);
274 }
275
276 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
277 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
278
279 PointerCoords pointerCoords[motionEntry.pointerCount];
280
281 // Use the first pointer information to normalize all other pointers. This could be any pointer
282 // as long as all other pointers are normalized to the same value and the final DispatchEntry
283 // uses the offset and scale for the normalized pointer.
284 const PointerInfo& firstPointerInfo =
285 inputTarget.pointerInfos[inputTarget.pointerIds.firstMarkedBit()];
286
287 // Iterate through all pointers in the event to normalize against the first.
288 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
289 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
290 uint32_t pointerId = uint32_t(pointerProperties.id);
291 const PointerInfo& currPointerInfo = inputTarget.pointerInfos[pointerId];
292
293 // The scale factor is the ratio of the current pointers scale to the normalized scale.
294 float scaleXDiff = currPointerInfo.windowXScale / firstPointerInfo.windowXScale;
295 float scaleYDiff = currPointerInfo.windowYScale / firstPointerInfo.windowYScale;
296
297 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
298 // First apply the current pointers offset to set the window at 0,0
299 pointerCoords[pointerIndex].applyOffset(currPointerInfo.xOffset, currPointerInfo.yOffset);
300 // Next scale the coordinates.
301 pointerCoords[pointerIndex].scale(1, scaleXDiff, scaleYDiff);
302 // Lastly, offset the coordinates so they're in the normalized pointer's frame.
303 pointerCoords[pointerIndex].applyOffset(-firstPointerInfo.xOffset,
304 -firstPointerInfo.yOffset);
305 }
306
307 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800308 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000309 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
310 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
311 motionEntry.metaState, motionEntry.buttonState,
312 motionEntry.classification, motionEntry.edgeFlags,
313 motionEntry.xPrecision, motionEntry.yPrecision,
314 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
315 motionEntry.downTime, motionEntry.pointerCount,
316 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
317 0 /* yOffset */);
318
319 if (motionEntry.injectionState) {
320 combinedMotionEntry->injectionState = motionEntry.injectionState;
321 combinedMotionEntry->injectionState->refCount += 1;
322 }
323
324 std::unique_ptr<DispatchEntry> dispatchEntry =
325 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
326 inputTargetFlags, firstPointerInfo.xOffset,
327 firstPointerInfo.yOffset, inputTarget.globalScaleFactor,
328 firstPointerInfo.windowXScale,
329 firstPointerInfo.windowYScale);
330 combinedMotionEntry->release();
331 return dispatchEntry;
332}
333
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700334static void addGestureMonitors(const std::vector<Monitor>& monitors,
335 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
336 float yOffset = 0) {
337 if (monitors.empty()) {
338 return;
339 }
340 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
341 for (const Monitor& monitor : monitors) {
342 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
343 }
344}
345
Gang Wang342c9272020-01-13 13:15:04 -0500346static std::array<uint8_t, 128> getRandomKey() {
347 std::array<uint8_t, 128> key;
348 if (RAND_bytes(key.data(), key.size()) != 1) {
349 LOG_ALWAYS_FATAL("Can't generate HMAC key");
350 }
351 return key;
352}
353
354// --- HmacKeyManager ---
355
356HmacKeyManager::HmacKeyManager() : mHmacKey(getRandomKey()) {}
357
358std::array<uint8_t, 32> HmacKeyManager::sign(const VerifiedInputEvent& event) const {
359 size_t size;
360 switch (event.type) {
361 case VerifiedInputEvent::Type::KEY: {
362 size = sizeof(VerifiedKeyEvent);
363 break;
364 }
365 case VerifiedInputEvent::Type::MOTION: {
366 size = sizeof(VerifiedMotionEvent);
367 break;
368 }
369 }
Gang Wang342c9272020-01-13 13:15:04 -0500370 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700371 return sign(start, size);
Gang Wang342c9272020-01-13 13:15:04 -0500372}
373
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700374std::array<uint8_t, 32> HmacKeyManager::sign(const uint8_t* data, size_t size) const {
Gang Wang342c9272020-01-13 13:15:04 -0500375 // SHA256 always generates 32-bytes result
376 std::array<uint8_t, 32> hash;
377 unsigned int hashLen = 0;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700378 uint8_t* result =
379 HMAC(EVP_sha256(), mHmacKey.data(), mHmacKey.size(), data, size, hash.data(), &hashLen);
Gang Wang342c9272020-01-13 13:15:04 -0500380 if (result == nullptr) {
381 ALOGE("Could not sign the data using HMAC");
382 return INVALID_HMAC;
383 }
384
385 if (hashLen != hash.size()) {
386 ALOGE("HMAC-SHA256 has unexpected length");
387 return INVALID_HMAC;
388 }
389
390 return hash;
391}
392
Michael Wrightd02c5b62014-02-10 15:10:22 -0800393// --- InputDispatcher ---
394
Garfield Tan00f511d2019-06-12 16:55:40 -0700395InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
396 : mPolicy(policy),
397 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700398 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800399 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700400 mAppSwitchSawKeyDown(false),
401 mAppSwitchDueTime(LONG_LONG_MAX),
402 mNextUnblockedEvent(nullptr),
403 mDispatchEnabled(false),
404 mDispatchFrozen(false),
405 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800406 // mInTouchMode will be initialized by the WindowManager to the default device config.
407 // To avoid leaking stack in case that call never comes, and for tests,
408 // initialize it here anyways.
409 mInTouchMode(true),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700410 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800412 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413
Yi Kong9b14ac62018-07-17 13:48:38 -0700414 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800415
416 policy->getDispatcherConfiguration(&mConfig);
417}
418
419InputDispatcher::~InputDispatcher() {
420 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800421 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800422
423 resetKeyRepeatLocked();
424 releasePendingEventLocked();
425 drainInboundQueueLocked();
426 }
427
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700428 while (!mConnectionsByFd.empty()) {
429 sp<Connection> connection = mConnectionsByFd.begin()->second;
430 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 }
432}
433
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700434status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700435 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700436 return ALREADY_EXISTS;
437 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700438 mThread = std::make_unique<InputThread>(
439 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
440 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700441}
442
443status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700444 if (mThread && mThread->isCallingThread()) {
445 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700446 return INVALID_OPERATION;
447 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700448 mThread.reset();
449 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700450}
451
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452void InputDispatcher::dispatchOnce() {
453 nsecs_t nextWakeupTime = LONG_LONG_MAX;
454 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800455 std::scoped_lock _l(mLock);
456 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800457
458 // Run a dispatch loop if there are no pending commands.
459 // The dispatch loop might enqueue commands to run afterwards.
460 if (!haveCommandsLocked()) {
461 dispatchOnceInnerLocked(&nextWakeupTime);
462 }
463
464 // Run all pending commands if there are any.
465 // If any commands were run then force the next poll to wake up immediately.
466 if (runCommandsLockedInterruptible()) {
467 nextWakeupTime = LONG_LONG_MIN;
468 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800469
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700470 // If we are still waiting for ack on some events,
471 // we might have to wake up earlier to check if an app is anr'ing.
472 const nsecs_t nextAnrCheck = processAnrsLocked();
473 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
474
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800475 // We are about to enter an infinitely long sleep, because we have no commands or
476 // pending or queued events
477 if (nextWakeupTime == LONG_LONG_MAX) {
478 mDispatcherEnteredIdle.notify_all();
479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800480 } // release lock
481
482 // Wait for callback or timeout or wake. (make sure we round up, not down)
483 nsecs_t currentTime = now();
484 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
485 mLooper->pollOnce(timeoutMillis);
486}
487
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700488/**
489 * Check if any of the connections' wait queues have events that are too old.
490 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
491 * Return the time at which we should wake up next.
492 */
493nsecs_t InputDispatcher::processAnrsLocked() {
494 const nsecs_t currentTime = now();
495 nsecs_t nextAnrCheck = LONG_LONG_MAX;
496 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
497 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
498 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
499 onAnrLocked(mAwaitedFocusedApplication);
500 mAwaitedFocusedApplication.clear();
501 return LONG_LONG_MIN;
502 } else {
503 // Keep waiting
504 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
505 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
506 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
507 }
508 }
509
510 // Check if any connection ANRs are due
511 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
512 if (currentTime < nextAnrCheck) { // most likely scenario
513 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
514 }
515
516 // If we reached here, we have an unresponsive connection.
517 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
518 if (connection == nullptr) {
519 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
520 return nextAnrCheck;
521 }
522 connection->responsive = false;
523 // Stop waking up for this unresponsive connection
524 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
525 onAnrLocked(connection);
526 return LONG_LONG_MIN;
527}
528
529nsecs_t InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
530 sp<InputWindowHandle> window = getWindowHandleLocked(token);
531 if (window != nullptr) {
532 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT).count();
533 }
534 return DEFAULT_INPUT_DISPATCHING_TIMEOUT.count();
535}
536
Michael Wrightd02c5b62014-02-10 15:10:22 -0800537void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
538 nsecs_t currentTime = now();
539
Jeff Browndc5992e2014-04-11 01:27:26 -0700540 // Reset the key repeat timer whenever normal dispatch is suspended while the
541 // device is in a non-interactive state. This is to ensure that we abort a key
542 // repeat if the device is just coming out of sleep.
543 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 resetKeyRepeatLocked();
545 }
546
547 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
548 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100549 if (DEBUG_FOCUS) {
550 ALOGD("Dispatch frozen. Waiting some more.");
551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 return;
553 }
554
555 // Optimize latency of app switches.
556 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
557 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
558 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
559 if (mAppSwitchDueTime < *nextWakeupTime) {
560 *nextWakeupTime = mAppSwitchDueTime;
561 }
562
563 // Ready to start a new event.
564 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700565 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700566 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 if (isAppSwitchDue) {
568 // The inbound queue is empty so the app switch key we were waiting
569 // for will never arrive. Stop waiting for it.
570 resetPendingAppSwitchLocked(false);
571 isAppSwitchDue = false;
572 }
573
574 // Synthesize a key repeat if appropriate.
575 if (mKeyRepeatState.lastKeyEntry) {
576 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
577 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
578 } else {
579 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
580 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
581 }
582 }
583 }
584
585 // Nothing to do if there is no pending event.
586 if (!mPendingEvent) {
587 return;
588 }
589 } else {
590 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700591 mPendingEvent = mInboundQueue.front();
592 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593 traceInboundQueueLengthLocked();
594 }
595
596 // Poke user activity for this event.
597 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700598 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600 }
601
602 // Now we have an event to dispatch.
603 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700604 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700606 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700608 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700610 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 }
612
613 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700614 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800615 }
616
617 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700618 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700619 ConfigurationChangedEntry* typedEntry =
620 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
621 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700622 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700623 break;
624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700626 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700627 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
628 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700629 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700630 break;
631 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100633 case EventEntry::Type::FOCUS: {
634 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
635 dispatchFocusLocked(currentTime, typedEntry);
636 done = true;
637 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
638 break;
639 }
640
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700641 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700642 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
643 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700644 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700645 resetPendingAppSwitchLocked(true);
646 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700647 } else if (dropReason == DropReason::NOT_DROPPED) {
648 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700649 }
650 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700651 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700652 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700653 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700654 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
655 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700656 }
657 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
658 break;
659 }
660
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700661 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700662 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700663 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
664 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700666 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700667 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700668 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700669 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
670 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700671 }
672 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
673 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 }
676
677 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700678 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700679 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 }
Michael Wright3a981722015-06-10 15:26:13 +0100681 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682
683 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700684 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685 }
686}
687
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700688/**
689 * Return true if the events preceding this incoming motion event should be dropped
690 * Return false otherwise (the default behaviour)
691 */
692bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700693 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700694 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700695
696 // Optimize case where the current application is unresponsive and the user
697 // decides to touch a window in a different application.
698 // If the application takes too long to catch up then we drop all events preceding
699 // the touch into the other window.
700 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700701 int32_t displayId = motionEntry.displayId;
702 int32_t x = static_cast<int32_t>(
703 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
704 int32_t y = static_cast<int32_t>(
705 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
706 sp<InputWindowHandle> touchedWindowHandle =
707 findTouchedWindowAtLocked(displayId, x, y, nullptr);
708 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700709 touchedWindowHandle->getApplicationToken() !=
710 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700711 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700712 ALOGI("Pruning input queue because user touched a different application while waiting "
713 "for %s",
714 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700715 return true;
716 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700717
718 // Alternatively, maybe there's a gesture monitor that could handle this event
719 std::vector<TouchedMonitor> gestureMonitors =
720 findTouchedGestureMonitorsLocked(displayId, {});
721 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
722 sp<Connection> connection =
723 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000724 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700725 // This monitor could take more input. Drop all events preceding this
726 // event, so that gesture monitor could get a chance to receive the stream
727 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
728 "responsive gesture monitor that may handle the event",
729 mAwaitedFocusedApplication->getName().c_str());
730 return true;
731 }
732 }
733 }
734
735 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
736 // yet been processed by some connections, the dispatcher will wait for these motion
737 // events to be processed before dispatching the key event. This is because these motion events
738 // may cause a new window to be launched, which the user might expect to receive focus.
739 // To prevent waiting forever for such events, just send the key to the currently focused window
740 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
741 ALOGD("Received a new pointer down event, stop waiting for events to process and "
742 "just send the pending key event to the focused window.");
743 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700744 }
745 return false;
746}
747
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700749 bool needWake = mInboundQueue.empty();
750 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751 traceInboundQueueLengthLocked();
752
753 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700754 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700755 // Optimize app switch latency.
756 // If the application takes too long to catch up then we drop all events preceding
757 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700758 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700759 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700760 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700761 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700762 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700763 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700765 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700767 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700768 mAppSwitchSawKeyDown = false;
769 needWake = true;
770 }
771 }
772 }
773 break;
774 }
775
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700776 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700777 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
778 mNextUnblockedEvent = entry;
779 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700781 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100783 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700784 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
785 break;
786 }
787 case EventEntry::Type::CONFIGURATION_CHANGED:
788 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700789 // nothing to do
790 break;
791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 }
793
794 return needWake;
795}
796
797void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
798 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700799 mRecentQueue.push_back(entry);
800 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
801 mRecentQueue.front()->release();
802 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 }
804}
805
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700806sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700807 int32_t y, TouchState* touchState,
808 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700810 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
811 LOG_ALWAYS_FATAL(
812 "Must provide a valid touch state if adding portal windows or outside targets");
813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800815 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
816 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800817 const InputWindowInfo* windowInfo = windowHandle->getInfo();
818 if (windowInfo->displayId == displayId) {
819 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820
821 if (windowInfo->visible) {
822 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700823 bool isTouchModal = (flags &
824 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
825 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800827 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700828 if (portalToDisplayId != ADISPLAY_ID_NONE &&
829 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800830 if (addPortalWindows) {
831 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700832 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800833 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700834 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 // Found window.
838 return windowHandle;
839 }
840 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800841
842 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700843 touchState->addOrUpdateWindow(windowHandle,
844 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
845 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 }
849 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700850 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851}
852
Garfield Tane84e6f92019-08-29 17:28:41 -0700853std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700854 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000855 std::vector<TouchedMonitor> touchedMonitors;
856
857 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
858 addGestureMonitors(monitors, touchedMonitors);
859 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
860 const InputWindowInfo* windowInfo = portalWindow->getInfo();
861 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
863 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000864 }
865 return touchedMonitors;
866}
867
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700868void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 const char* reason;
870 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700873 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 reason = "inbound event was dropped because the policy consumed it";
876 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700877 case DropReason::DISABLED:
878 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 ALOGI("Dropped event because input dispatch is disabled.");
880 }
881 reason = "inbound event was dropped because input dispatch is disabled";
882 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 ALOGI("Dropped event because of pending overdue app switch.");
885 reason = "inbound event was dropped because of pending overdue app switch";
886 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700887 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 ALOGI("Dropped event because the current application is not responding and the user "
889 "has started interacting with a different application.");
890 reason = "inbound event was dropped because the current application is not responding "
891 "and the user has started interacting with a different application";
892 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700893 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700894 ALOGI("Dropped event because it is stale.");
895 reason = "inbound event was dropped because it is stale";
896 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700897 case DropReason::NOT_DROPPED: {
898 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 }
902
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700903 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700904 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
906 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700907 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700909 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700910 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
911 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700912 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
913 synthesizeCancelationEventsForAllConnectionsLocked(options);
914 } else {
915 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
916 synthesizeCancelationEventsForAllConnectionsLocked(options);
917 }
918 break;
919 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100920 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700921 case EventEntry::Type::CONFIGURATION_CHANGED:
922 case EventEntry::Type::DEVICE_RESET: {
923 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
924 break;
925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 }
927}
928
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800929static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700930 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
931 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932}
933
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700934bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
935 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
936 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
937 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938}
939
940bool InputDispatcher::isAppSwitchPendingLocked() {
941 return mAppSwitchDueTime != LONG_LONG_MAX;
942}
943
944void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
945 mAppSwitchDueTime = LONG_LONG_MAX;
946
947#if DEBUG_APP_SWITCH
948 if (handled) {
949 ALOGD("App switch has arrived.");
950 } else {
951 ALOGD("App switch was abandoned.");
952 }
953#endif
954}
955
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700957 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958}
959
960bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700961 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 return false;
963 }
964
965 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700966 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700967 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700969 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970
971 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700972 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 return true;
974}
975
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700976void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
977 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978}
979
980void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700981 while (!mInboundQueue.empty()) {
982 EventEntry* entry = mInboundQueue.front();
983 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 releaseInboundEventLocked(entry);
985 }
986 traceInboundQueueLengthLocked();
987}
988
989void InputDispatcher::releasePendingEventLocked() {
990 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700992 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 }
994}
995
996void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
997 InjectionState* injectionState = entry->injectionState;
998 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
999#if DEBUG_DISPATCH_CYCLE
1000 ALOGD("Injected inbound event was dropped.");
1001#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001002 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 }
1004 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001005 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 }
1007 addRecentEventLocked(entry);
1008 entry->release();
1009}
1010
1011void InputDispatcher::resetKeyRepeatLocked() {
1012 if (mKeyRepeatState.lastKeyEntry) {
1013 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07001014 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 }
1016}
1017
Garfield Tane84e6f92019-08-29 17:28:41 -07001018KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
1020
1021 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -07001022 uint32_t policyFlags = entry->policyFlags &
1023 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 if (entry->refCount == 1) {
1025 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001026 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 entry->eventTime = currentTime;
1028 entry->policyFlags = policyFlags;
1029 entry->repeatCount += 1;
1030 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001032 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001033 entry->displayId, policyFlags, entry->action, entry->flags,
1034 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001035 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036
1037 mKeyRepeatState.lastKeyEntry = newEntry;
1038 entry->release();
1039
1040 entry = newEntry;
1041 }
1042 entry->syntheticRepeat = true;
1043
1044 // Increment reference count since we keep a reference to the event in
1045 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
1046 entry->refCount += 1;
1047
1048 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1049 return entry;
1050}
1051
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1053 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001055 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056#endif
1057
1058 // Reset key repeating in case a keyboard device was added or removed or something.
1059 resetKeyRepeatLocked();
1060
1061 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001062 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1063 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001065 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 return true;
1067}
1068
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001069bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001071 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073#endif
1074
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001075 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 options.deviceId = entry->deviceId;
1077 synthesizeCancelationEventsForAllConnectionsLocked(options);
1078 return true;
1079}
1080
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001081void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001082 if (mPendingEvent != nullptr) {
1083 // Move the pending event to the front of the queue. This will give the chance
1084 // for the pending event to get dispatched to the newly focused window
1085 mInboundQueue.push_front(mPendingEvent);
1086 mPendingEvent = nullptr;
1087 }
1088
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001089 FocusEntry* focusEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08001090 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), hasFocus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001091
1092 // This event should go to the front of the queue, but behind all other focus events
1093 // Find the last focus event, and insert right after it
1094 std::deque<EventEntry*>::reverse_iterator it =
1095 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1096 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1097
1098 // Maintain the order of focus events. Insert the entry after all other focus events.
1099 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001100}
1101
1102void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
1103 sp<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1104 if (channel == nullptr) {
1105 return; // Window has gone away
1106 }
1107 InputTarget target;
1108 target.inputChannel = channel;
1109 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1110 entry->dispatchInProgress = true;
Selim Cinek3d989c22020-06-17 21:42:12 +00001111
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001112 dispatchEventLocked(currentTime, entry, {target});
1113}
1114
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001116 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001118 if (!entry->dispatchInProgress) {
1119 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1120 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1121 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1122 if (mKeyRepeatState.lastKeyEntry &&
1123 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 // We have seen two identical key downs in a row which indicates that the device
1125 // driver is automatically generating key repeats itself. We take note of the
1126 // repeat here, but we disable our own next key repeat timer since it is clear that
1127 // we will not need to synthesize key repeats ourselves.
1128 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1129 resetKeyRepeatLocked();
1130 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1131 } else {
1132 // Not a repeat. Save key down state in case we do see a repeat later.
1133 resetKeyRepeatLocked();
1134 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1135 }
1136 mKeyRepeatState.lastKeyEntry = entry;
1137 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001138 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 resetKeyRepeatLocked();
1140 }
1141
1142 if (entry->repeatCount == 1) {
1143 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1144 } else {
1145 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1146 }
1147
1148 entry->dispatchInProgress = true;
1149
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001150 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 }
1152
1153 // Handle case where the policy asked us to try again later last time.
1154 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1155 if (currentTime < entry->interceptKeyWakeupTime) {
1156 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1157 *nextWakeupTime = entry->interceptKeyWakeupTime;
1158 }
1159 return false; // wait until next wakeup
1160 }
1161 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1162 entry->interceptKeyWakeupTime = 0;
1163 }
1164
1165 // Give the policy a chance to intercept the key.
1166 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1167 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001168 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001169 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +08001170 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001171 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001172 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001173 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 }
1175 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001176 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 entry->refCount += 1;
1178 return false; // wait for the command to run
1179 } else {
1180 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1181 }
1182 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001183 if (*dropReason == DropReason::NOT_DROPPED) {
1184 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 }
1186 }
1187
1188 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001189 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001190 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001191 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001192 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001193 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 return true;
1195 }
1196
1197 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001198 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001199 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001200 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1202 return false;
1203 }
1204
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001205 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1207 return true;
1208 }
1209
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001210 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001211 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212
1213 // Dispatch the key.
1214 dispatchEventLocked(currentTime, entry, inputTargets);
1215 return true;
1216}
1217
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001218void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001220 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001221 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1222 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001223 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1224 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1225 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226#endif
1227}
1228
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1230 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001231 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001233 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 entry->dispatchInProgress = true;
1235
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001236 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 }
1238
1239 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001240 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001241 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001242 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001243 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 return true;
1245 }
1246
1247 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1248
1249 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001250 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251
1252 bool conflictingPointerActions = false;
1253 int32_t injectionResult;
1254 if (isPointerEvent) {
1255 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001256 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001257 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001258 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 } else {
1260 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001261 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001262 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 }
1264 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1265 return false;
1266 }
1267
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001268 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001269 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1270 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1271 return true;
1272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001274 CancelationOptions::Mode mode(isPointerEvent
1275 ? CancelationOptions::CANCEL_POINTER_EVENTS
1276 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1277 CancelationOptions options(mode, "input event injection failed");
1278 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 return true;
1280 }
1281
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001282 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001283 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001285 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001286 std::unordered_map<int32_t, TouchState>::iterator it =
1287 mTouchStatesByDisplay.find(entry->displayId);
1288 if (it != mTouchStatesByDisplay.end()) {
1289 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001290 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001291 // The event has gone through these portal windows, so we add monitoring targets of
1292 // the corresponding displays as well.
1293 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001294 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001295 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001296 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001297 }
1298 }
1299 }
1300 }
1301
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 // Dispatch the motion.
1303 if (conflictingPointerActions) {
1304 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001305 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 synthesizeCancelationEventsForAllConnectionsLocked(options);
1307 }
1308 dispatchEventLocked(currentTime, entry, inputTargets);
1309 return true;
1310}
1311
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001312void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001314 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001315 ", policyFlags=0x%x, "
1316 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1317 "metaState=0x%x, buttonState=0x%x,"
1318 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001319 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1320 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1321 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001323 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001325 "x=%f, y=%f, pressure=%f, size=%f, "
1326 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1327 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001328 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1329 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1330 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1331 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1332 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1333 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1334 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1335 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1336 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1337 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 }
1339#endif
1340}
1341
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001342void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1343 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001344 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345#if DEBUG_DISPATCH_CYCLE
1346 ALOGD("dispatchEventToCurrentInputTargets");
1347#endif
1348
1349 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1350
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001351 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001353 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001354 sp<Connection> connection =
1355 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001356 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001357 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001359 if (DEBUG_FOCUS) {
1360 ALOGD("Dropping event delivery to target with channel '%s' because it "
1361 "is no longer registered with the input dispatcher.",
1362 inputTarget.inputChannel->getName().c_str());
1363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 }
1365 }
1366}
1367
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001368void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1369 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1370 // If the policy decides to close the app, we will get a channel removal event via
1371 // unregisterInputChannel, and will clean up the connection that way. We are already not
1372 // sending new pointers to the connection when it blocked, but focused events will continue to
1373 // pile up.
1374 ALOGW("Canceling events for %s because it is unresponsive",
1375 connection->inputChannel->getName().c_str());
1376 if (connection->status == Connection::STATUS_NORMAL) {
1377 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1378 "application not responding");
1379 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380 }
1381}
1382
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001383void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001384 if (DEBUG_FOCUS) {
1385 ALOGD("Resetting ANR timeouts.");
1386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387
1388 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001389 mNoFocusedWindowTimeoutTime = std::nullopt;
1390 mAwaitedFocusedApplication.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391}
1392
Tiger Huang721e26f2018-07-24 22:26:19 +08001393/**
1394 * Get the display id that the given event should go to. If this event specifies a valid display id,
1395 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1396 * Focused display is the display that the user most recently interacted with.
1397 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001398int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001399 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001400 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001401 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001402 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1403 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001404 break;
1405 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001406 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001407 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1408 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001409 break;
1410 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001411 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001412 case EventEntry::Type::CONFIGURATION_CHANGED:
1413 case EventEntry::Type::DEVICE_RESET: {
1414 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001415 return ADISPLAY_ID_NONE;
1416 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001417 }
1418 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1419}
1420
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001421bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1422 const char* focusedWindowName) {
1423 if (mAnrTracker.empty()) {
1424 // already processed all events that we waited for
1425 mKeyIsWaitingForEventsTimeout = std::nullopt;
1426 return false;
1427 }
1428
1429 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1430 // Start the timer
1431 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1432 "focus to change",
1433 focusedWindowName);
1434 mKeyIsWaitingForEventsTimeout = currentTime + KEY_WAITING_FOR_EVENTS_TIMEOUT.count();
1435 return true;
1436 }
1437
1438 // We still have pending events, and already started the timer
1439 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1440 return true; // Still waiting
1441 }
1442
1443 // Waited too long, and some connection still hasn't processed all motions
1444 // Just send the key to the focused window
1445 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1446 focusedWindowName);
1447 mKeyIsWaitingForEventsTimeout = std::nullopt;
1448 return false;
1449}
1450
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001452 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001453 std::vector<InputTarget>& inputTargets,
1454 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001455 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456
Tiger Huang721e26f2018-07-24 22:26:19 +08001457 int32_t displayId = getTargetDisplayId(entry);
1458 sp<InputWindowHandle> focusedWindowHandle =
1459 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1460 sp<InputApplicationHandle> focusedApplicationHandle =
1461 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1462
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 // If there is no currently focused window and no focused application
1464 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001465 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1466 ALOGI("Dropping %s event because there is no focused window or focused application in "
1467 "display %" PRId32 ".",
1468 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001469 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001470 }
1471
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001472 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1473 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1474 // start interacting with another application via touch (app switch). This code can be removed
1475 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1476 // an app is expected to have a focused window.
1477 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1478 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1479 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001480 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1481 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1482 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001483 mAwaitedFocusedApplication = focusedApplicationHandle;
1484 ALOGW("Waiting because no window has focus but %s may eventually add a "
1485 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001486 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001487 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1488 return INPUT_EVENT_INJECTION_PENDING;
1489 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1490 // Already raised ANR. Drop the event
1491 ALOGE("Dropping %s event because there is no focused window",
1492 EventEntry::typeToString(entry.type));
1493 return INPUT_EVENT_INJECTION_FAILED;
1494 } else {
1495 // Still waiting for the focused window
1496 return INPUT_EVENT_INJECTION_PENDING;
1497 }
1498 }
1499
1500 // we have a valid, non-null focused window
1501 resetNoFocusedWindowTimeoutLocked();
1502
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001504 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001505 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 }
1507
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001508 if (focusedWindowHandle->getInfo()->paused) {
1509 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1510 return INPUT_EVENT_INJECTION_PENDING;
1511 }
1512
1513 // If the event is a key event, then we must wait for all previous events to
1514 // complete before delivering it because previous events may have the
1515 // side-effect of transferring focus to a different window and we want to
1516 // ensure that the following keys are sent to the new window.
1517 //
1518 // Suppose the user touches a button in a window then immediately presses "A".
1519 // If the button causes a pop-up window to appear then we want to ensure that
1520 // the "A" key is delivered to the new pop-up window. This is because users
1521 // often anticipate pending UI changes when typing on a keyboard.
1522 // To obtain this behavior, we must serialize key events with respect to all
1523 // prior input events.
1524 if (entry.type == EventEntry::Type::KEY) {
1525 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1526 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1527 return INPUT_EVENT_INJECTION_PENDING;
1528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529 }
1530
1531 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001532 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001533 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1534 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535
1536 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001537 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538}
1539
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001540/**
1541 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1542 * that are currently unresponsive.
1543 */
1544std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1545 const std::vector<TouchedMonitor>& monitors) const {
1546 std::vector<TouchedMonitor> responsiveMonitors;
1547 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1548 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1549 sp<Connection> connection = getConnectionLocked(
1550 monitor.monitor.inputChannel->getConnectionToken());
1551 if (connection == nullptr) {
1552 ALOGE("Could not find connection for monitor %s",
1553 monitor.monitor.inputChannel->getName().c_str());
1554 return false;
1555 }
1556 if (!connection->responsive) {
1557 ALOGW("Unresponsive monitor %s will not get the new gesture",
1558 connection->inputChannel->getName().c_str());
1559 return false;
1560 }
1561 return true;
1562 });
1563 return responsiveMonitors;
1564}
1565
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001567 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001568 std::vector<InputTarget>& inputTargets,
1569 nsecs_t* nextWakeupTime,
1570 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001571 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 enum InjectionPermission {
1573 INJECTION_PERMISSION_UNKNOWN,
1574 INJECTION_PERMISSION_GRANTED,
1575 INJECTION_PERMISSION_DENIED
1576 };
1577
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 // For security reasons, we defer updating the touch state until we are sure that
1579 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001580 int32_t displayId = entry.displayId;
1581 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1583
1584 // Update the touch state as needed based on the properties of the touch event.
1585 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1586 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001587 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1588 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001590 // Copy current touch state into tempTouchState.
1591 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1592 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001593 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001594 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001595 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1596 mTouchStatesByDisplay.find(displayId);
1597 if (oldStateIt != mTouchStatesByDisplay.end()) {
1598 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001599 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001600 }
1601
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001602 bool isSplit = tempTouchState.split;
1603 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1604 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1605 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001606 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1607 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1608 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1609 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1610 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001611 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 bool wrongDevice = false;
1613 if (newGesture) {
1614 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001615 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001616 ALOGI("Dropping event because a pointer for a different device is already down "
1617 "in display %" PRId32,
1618 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001619 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1621 switchedDevice = false;
1622 wrongDevice = true;
1623 goto Failed;
1624 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001625 tempTouchState.reset();
1626 tempTouchState.down = down;
1627 tempTouchState.deviceId = entry.deviceId;
1628 tempTouchState.source = entry.source;
1629 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001631 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001632 ALOGI("Dropping move event because a pointer for a different device is already active "
1633 "in display %" PRId32,
1634 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001635 // TODO: test multiple simultaneous input streams.
1636 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1637 switchedDevice = false;
1638 wrongDevice = true;
1639 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 }
1641
1642 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1643 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1644
Garfield Tan00f511d2019-06-12 16:55:40 -07001645 int32_t x;
1646 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001648 // Always dispatch mouse events to cursor position.
1649 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001650 x = int32_t(entry.xCursorPosition);
1651 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001652 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001653 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1654 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001655 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001656 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001657 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001658 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1659 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001660
1661 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001662 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001663 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001666 if (newTouchedWindowHandle != nullptr &&
1667 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001668 // New window supports splitting, but we should never split mouse events.
1669 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 } else if (isSplit) {
1671 // New window does not support splitting but we have already split events.
1672 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001673 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 }
1675
1676 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001677 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001679 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001680 }
1681
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001682 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1683 ALOGI("Not sending touch event to %s because it is paused",
1684 newTouchedWindowHandle->getName().c_str());
1685 newTouchedWindowHandle = nullptr;
1686 }
1687
1688 if (newTouchedWindowHandle != nullptr) {
1689 sp<Connection> connection = getConnectionLocked(newTouchedWindowHandle->getToken());
1690 if (connection == nullptr) {
1691 ALOGI("Could not find connection for %s",
1692 newTouchedWindowHandle->getName().c_str());
1693 newTouchedWindowHandle = nullptr;
1694 } else if (!connection->responsive) {
1695 // don't send the new touch to an unresponsive window
1696 ALOGW("Unresponsive window %s will not get the new gesture at %" PRIu64,
1697 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1698 newTouchedWindowHandle = nullptr;
1699 }
1700 }
1701
1702 // Also don't send the new touch event to unresponsive gesture monitors
1703 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1704
Michael Wright3dd60e22019-03-27 22:06:44 +00001705 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1706 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001707 "(%d, %d) in display %" PRId32 ".",
1708 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001709 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1710 goto Failed;
1711 }
1712
1713 if (newTouchedWindowHandle != nullptr) {
1714 // Set target flags.
1715 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1716 if (isSplit) {
1717 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001719 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1720 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1721 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1722 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1723 }
1724
1725 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001726 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1727 newHoverWindowHandle = nullptr;
1728 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001729 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001730 }
1731
1732 // Update the temporary touch state.
1733 BitSet32 pointerIds;
1734 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001735 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001736 pointerIds.markBit(pointerId);
1737 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001738 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 }
1740
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001741 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 } else {
1743 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1744
1745 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001746 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001747 if (DEBUG_FOCUS) {
1748 ALOGD("Dropping event because the pointer is not down or we previously "
1749 "dropped the pointer down event in display %" PRId32,
1750 displayId);
1751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1753 goto Failed;
1754 }
1755
1756 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001757 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001758 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001759 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1760 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761
1762 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001763 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001764 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001765 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1766 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001767 if (DEBUG_FOCUS) {
1768 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1769 oldTouchedWindowHandle->getName().c_str(),
1770 newTouchedWindowHandle->getName().c_str(), displayId);
1771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001773 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1774 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1775 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776
1777 // Make a slippery entrance into the new window.
1778 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1779 isSplit = true;
1780 }
1781
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001782 int32_t targetFlags =
1783 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 if (isSplit) {
1785 targetFlags |= InputTarget::FLAG_SPLIT;
1786 }
1787 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1788 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1789 }
1790
1791 BitSet32 pointerIds;
1792 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001793 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001795 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 }
1797 }
1798 }
1799
1800 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001801 // Let the previous window know that the hover sequence is over, unless we already did it
1802 // when dispatching it as is to newTouchedWindowHandle.
1803 if (mLastHoverWindowHandle != nullptr &&
1804 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1805 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806#if DEBUG_HOVER
1807 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001808 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001810 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1811 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 }
1813
Garfield Tandf26e862020-07-01 20:18:19 -07001814 // Let the new window know that the hover sequence is starting, unless we already did it
1815 // when dispatching it as is to newTouchedWindowHandle.
1816 if (newHoverWindowHandle != nullptr &&
1817 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1818 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819#if DEBUG_HOVER
1820 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001821 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001823 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1824 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1825 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 }
1827 }
1828
1829 // Check permission to inject into all touched foreground windows and ensure there
1830 // is at least one touched foreground window.
1831 {
1832 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001833 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1835 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001836 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1838 injectionPermission = INJECTION_PERMISSION_DENIED;
1839 goto Failed;
1840 }
1841 }
1842 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001843 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001844 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001845 ALOGI("Dropping event because there is no touched foreground window in display "
1846 "%" PRId32 " or gesture monitor to receive it.",
1847 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1849 goto Failed;
1850 }
1851
1852 // Permission granted to injection into all touched foreground windows.
1853 injectionPermission = INJECTION_PERMISSION_GRANTED;
1854 }
1855
1856 // Check whether windows listening for outside touches are owned by the same UID. If it is
1857 // set the policy flag that we will not reveal coordinate information to this window.
1858 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1859 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001860 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001861 if (foregroundWindowHandle) {
1862 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001863 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001864 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1865 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1866 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001867 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1868 InputTarget::FLAG_ZERO_COORDS,
1869 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 }
1872 }
1873 }
1874 }
1875
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 // If this is the first pointer going down and the touched window has a wallpaper
1877 // then also add the touched wallpaper windows so they are locked in for the duration
1878 // of the touch gesture.
1879 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1880 // engine only supports touch events. We would need to add a mechanism similar
1881 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1882 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1883 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001884 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001885 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001886 const std::vector<sp<InputWindowHandle>> windowHandles =
1887 getWindowHandlesLocked(displayId);
1888 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001890 if (info->displayId == displayId &&
1891 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001892 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001893 .addOrUpdateWindow(windowHandle,
1894 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1895 InputTarget::
1896 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1897 InputTarget::FLAG_DISPATCH_AS_IS,
1898 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 }
1900 }
1901 }
1902 }
1903
1904 // Success! Output targets.
1905 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1906
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001907 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001909 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 }
1911
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001912 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001913 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001914 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001915 }
1916
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 // Drop the outside or hover touch windows since we will not care about them
1918 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001919 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920
1921Failed:
1922 // Check injection permission once and for all.
1923 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001924 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 injectionPermission = INJECTION_PERMISSION_GRANTED;
1926 } else {
1927 injectionPermission = INJECTION_PERMISSION_DENIED;
1928 }
1929 }
1930
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001931 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1932 return injectionResult;
1933 }
1934
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001936 if (!wrongDevice) {
1937 if (switchedDevice) {
1938 if (DEBUG_FOCUS) {
1939 ALOGD("Conflicting pointer actions: Switched to a different device.");
1940 }
1941 *outConflictingPointerActions = true;
1942 }
1943
1944 if (isHoverAction) {
1945 // Started hovering, therefore no longer down.
1946 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001947 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001948 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1949 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951 *outConflictingPointerActions = true;
1952 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001953 tempTouchState.reset();
1954 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1955 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1956 tempTouchState.deviceId = entry.deviceId;
1957 tempTouchState.source = entry.source;
1958 tempTouchState.displayId = displayId;
1959 }
1960 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1961 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1962 // All pointers up or canceled.
1963 tempTouchState.reset();
1964 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1965 // First pointer went down.
1966 if (oldState && oldState->down) {
1967 if (DEBUG_FOCUS) {
1968 ALOGD("Conflicting pointer actions: Down received while already down.");
1969 }
1970 *outConflictingPointerActions = true;
1971 }
1972 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1973 // One pointer went up.
1974 if (isSplit) {
1975 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1976 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001978 for (size_t i = 0; i < tempTouchState.windows.size();) {
1979 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1980 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1981 touchedWindow.pointerIds.clearBit(pointerId);
1982 if (touchedWindow.pointerIds.isEmpty()) {
1983 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1984 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001987 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001989 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001990 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001991
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001992 // Save changes unless the action was scroll in which case the temporary touch
1993 // state was only valid for this one action.
1994 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1995 if (tempTouchState.displayId >= 0) {
1996 mTouchStatesByDisplay[displayId] = tempTouchState;
1997 } else {
1998 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002002 // Update hover state.
2003 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 }
2005
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 return injectionResult;
2007}
2008
2009void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002010 int32_t targetFlags, BitSet32 pointerIds,
2011 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002012 std::vector<InputTarget>::iterator it =
2013 std::find_if(inputTargets.begin(), inputTargets.end(),
2014 [&windowHandle](const InputTarget& inputTarget) {
2015 return inputTarget.inputChannel->getConnectionToken() ==
2016 windowHandle->getToken();
2017 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002018
Chavi Weingarten114b77f2020-01-15 22:35:10 +00002019 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002020
2021 if (it == inputTargets.end()) {
2022 InputTarget inputTarget;
2023 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2024 if (inputChannel == nullptr) {
2025 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2026 return;
2027 }
2028 inputTarget.inputChannel = inputChannel;
2029 inputTarget.flags = targetFlags;
2030 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
2031 inputTargets.push_back(inputTarget);
2032 it = inputTargets.end() - 1;
2033 }
2034
2035 ALOG_ASSERT(it->flags == targetFlags);
2036 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2037
2038 it->addPointers(pointerIds, -windowInfo->frameLeft, -windowInfo->frameTop,
2039 windowInfo->windowXScale, windowInfo->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040}
2041
Michael Wright3dd60e22019-03-27 22:06:44 +00002042void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002043 int32_t displayId, float xOffset,
2044 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002045 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2046 mGlobalMonitorsByDisplay.find(displayId);
2047
2048 if (it != mGlobalMonitorsByDisplay.end()) {
2049 const std::vector<Monitor>& monitors = it->second;
2050 for (const Monitor& monitor : monitors) {
2051 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 }
2054}
2055
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002056void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2057 float yOffset,
2058 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002059 InputTarget target;
2060 target.inputChannel = monitor.inputChannel;
2061 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002062 target.setDefaultPointerInfo(xOffset, yOffset, 1 /* windowXScale */, 1 /* windowYScale */);
Michael Wright3dd60e22019-03-27 22:06:44 +00002063 inputTargets.push_back(target);
2064}
2065
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002067 const InjectionState* injectionState) {
2068 if (injectionState &&
2069 (windowHandle == nullptr ||
2070 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2071 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002072 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002074 "owned by uid %d",
2075 injectionState->injectorPid, injectionState->injectorUid,
2076 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 } else {
2078 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002079 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 }
2081 return false;
2082 }
2083 return true;
2084}
2085
Robert Carrc9bf1d32020-04-13 17:21:08 -07002086/**
2087 * Indicate whether one window handle should be considered as obscuring
2088 * another window handle. We only check a few preconditions. Actually
2089 * checking the bounds is left to the caller.
2090 */
2091static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2092 const sp<InputWindowHandle>& otherHandle) {
2093 // Compare by token so cloned layers aren't counted
2094 if (haveSameToken(windowHandle, otherHandle)) {
2095 return false;
2096 }
2097 auto info = windowHandle->getInfo();
2098 auto otherInfo = otherHandle->getInfo();
2099 if (!otherInfo->visible) {
2100 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002101 } else if (info->ownerPid == otherInfo->ownerPid) {
2102 // If ownerPid is the same we don't generate occlusion events as there
2103 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002104 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002105 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002106 return false;
2107 } else if (otherInfo->displayId != info->displayId) {
2108 return false;
2109 }
2110 return true;
2111}
2112
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002113bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2114 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002116 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2117 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002118 if (windowHandle == otherHandle) {
2119 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002122 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002123 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 return true;
2125 }
2126 }
2127 return false;
2128}
2129
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002130bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2131 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002132 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002133 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002134 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002135 if (windowHandle == otherHandle) {
2136 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002137 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002138 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002139 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002140 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002141 return true;
2142 }
2143 }
2144 return false;
2145}
2146
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002147std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 const sp<InputApplicationHandle>& applicationHandle,
2149 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002150 if (applicationHandle != nullptr) {
2151 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002152 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 } else {
2154 return applicationHandle->getName();
2155 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002156 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002157 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002159 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 }
2161}
2162
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002163void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002164 if (eventEntry.type == EventEntry::Type::FOCUS) {
2165 // Focus events are passed to apps, but do not represent user activity.
2166 return;
2167 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002168 int32_t displayId = getTargetDisplayId(eventEntry);
2169 sp<InputWindowHandle> focusedWindowHandle =
2170 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2171 if (focusedWindowHandle != nullptr) {
2172 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
2174#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002175 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176#endif
2177 return;
2178 }
2179 }
2180
2181 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002182 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002183 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002184 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2185 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002186 return;
2187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002189 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002190 eventType = USER_ACTIVITY_EVENT_TOUCH;
2191 }
2192 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002194 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002195 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2196 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002197 return;
2198 }
2199 eventType = USER_ACTIVITY_EVENT_BUTTON;
2200 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002202 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002203 case EventEntry::Type::CONFIGURATION_CHANGED:
2204 case EventEntry::Type::DEVICE_RESET: {
2205 LOG_ALWAYS_FATAL("%s events are not user activity",
2206 EventEntry::typeToString(eventEntry.type));
2207 break;
2208 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 }
2210
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002211 std::unique_ptr<CommandEntry> commandEntry =
2212 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002213 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002215 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216}
2217
2218void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002219 const sp<Connection>& connection,
2220 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002221 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002222 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002223 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002224 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002225 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002226 ATRACE_NAME(message.c_str());
2227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228#if DEBUG_DISPATCH_CYCLE
2229 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002230 "globalScaleFactor=%f, pointerIds=0x%x %s",
2231 connection->getInputChannelName().c_str(), inputTarget.flags,
2232 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2233 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234#endif
2235
2236 // Skip this event if the connection status is not normal.
2237 // We don't want to enqueue additional outbound events if the connection is broken.
2238 if (connection->status != Connection::STATUS_NORMAL) {
2239#if DEBUG_DISPATCH_CYCLE
2240 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002241 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242#endif
2243 return;
2244 }
2245
2246 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002247 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2248 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2249 "Entry type %s should not have FLAG_SPLIT",
2250 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002252 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002253 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002255 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 if (!splitMotionEntry) {
2257 return; // split event was dropped
2258 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002259 if (DEBUG_FOCUS) {
2260 ALOGD("channel '%s' ~ Split motion event.",
2261 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002262 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002263 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002264 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 splitMotionEntry->release();
2266 return;
2267 }
2268 }
2269
2270 // Not splitting. Enqueue dispatch entries for the event as is.
2271 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2272}
2273
2274void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002275 const sp<Connection>& connection,
2276 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002277 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002278 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002279 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002280 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002281 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002282 ATRACE_NAME(message.c_str());
2283 }
2284
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002285 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286
2287 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002288 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002289 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002290 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002291 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002292 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002293 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002294 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002295 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002296 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002298 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002299 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300
2301 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002302 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 startDispatchCycleLocked(currentTime, connection);
2304 }
2305}
2306
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002307void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2308 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002309 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002310 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002311 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002312 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2313 connection->getInputChannelName().c_str(),
2314 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002315 ATRACE_NAME(message.c_str());
2316 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002317 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 if (!(inputTargetFlags & dispatchMode)) {
2319 return;
2320 }
2321 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2322
2323 // This is a new event.
2324 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002325 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002326 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002328 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2329 // different EventEntry than what was passed in.
2330 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002332 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002333 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002334 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002335 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002336 dispatchEntry->resolvedAction = keyEntry.action;
2337 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002339 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2340 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002342 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2343 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002345 return; // skip the inconsistent event
2346 }
2347 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002350 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002351 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002352 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2353 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2354 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2355 static_cast<int32_t>(IdGenerator::Source::OTHER);
2356 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002357 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2358 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2359 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2360 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2361 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2362 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2363 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2364 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2365 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2366 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2367 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002368 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002369 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002370 }
2371 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002372 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2373 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002375 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2376 "event",
2377 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002379 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002382 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002383 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2384 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2385 }
2386 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2387 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002390 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2391 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002393 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2394 "event",
2395 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002397 return; // skip the inconsistent event
2398 }
2399
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002400 dispatchEntry->resolvedEventId =
2401 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2402 ? mIdGenerator.nextId()
2403 : motionEntry.id;
2404 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2405 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2406 ") to MotionEvent(id=0x%" PRIx32 ").",
2407 motionEntry.id, dispatchEntry->resolvedEventId);
2408 ATRACE_NAME(message.c_str());
2409 }
2410
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002411 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002412 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002413
2414 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002416 case EventEntry::Type::FOCUS: {
2417 break;
2418 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002419 case EventEntry::Type::CONFIGURATION_CHANGED:
2420 case EventEntry::Type::DEVICE_RESET: {
2421 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002422 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002423 break;
2424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 }
2426
2427 // Remember that we are waiting for this dispatch to complete.
2428 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002429 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 }
2431
2432 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002433 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002434 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002435}
2436
chaviwfd6d3512019-03-25 13:23:49 -07002437void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002438 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002439 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002440 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2441 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002442 return;
2443 }
2444
2445 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2446 if (inputWindowHandle == nullptr) {
2447 return;
2448 }
2449
chaviw8c9cf542019-03-25 13:02:48 -07002450 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002451 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002452
2453 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2454
2455 if (!hasFocusChanged) {
2456 return;
2457 }
2458
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002459 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2460 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002461 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002462 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463}
2464
2465void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002466 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002467 if (ATRACE_ENABLED()) {
2468 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002469 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002470 ATRACE_NAME(message.c_str());
2471 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002473 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474#endif
2475
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002476 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2477 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002479 const nsecs_t timeout =
2480 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
2481 dispatchEntry->timeoutTime = currentTime + timeout;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482
2483 // Publish the event.
2484 status_t status;
2485 EventEntry* eventEntry = dispatchEntry->eventEntry;
2486 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002487 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002488 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2489 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002491 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002492 status =
2493 connection->inputPublisher
2494 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2495 keyEntry->deviceId, keyEntry->source,
2496 keyEntry->displayId, std::move(hmac),
2497 dispatchEntry->resolvedAction,
2498 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2499 keyEntry->scanCode, keyEntry->metaState,
2500 keyEntry->repeatCount, keyEntry->downTime,
2501 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002502 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 }
2504
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002505 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002506 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002508 PointerCoords scaledCoords[MAX_POINTERS];
2509 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2510
chaviw82357092020-01-28 13:13:06 -08002511 // Set the X and Y offset and X and Y scale depending on the input source.
2512 float xOffset = 0.0f, yOffset = 0.0f;
2513 float xScale = 1.0f, yScale = 1.0f;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002514 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2515 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2516 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002517 xScale = dispatchEntry->windowXScale;
2518 yScale = dispatchEntry->windowYScale;
2519 xOffset = dispatchEntry->xOffset * xScale;
2520 yOffset = dispatchEntry->yOffset * yScale;
2521 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002522 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2523 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002524 // Don't apply window scale here since we don't want scale to affect raw
2525 // coordinates. The scale will be sent back to the client and applied
2526 // later when requesting relative coordinates.
2527 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2528 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002529 }
2530 usingCoords = scaledCoords;
2531 }
2532 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002533 // We don't want the dispatch target to know.
2534 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2535 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2536 scaledCoords[i].clear();
2537 }
2538 usingCoords = scaledCoords;
2539 }
2540 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002541
2542 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002543
2544 // Publish the motion event.
2545 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002546 .publishMotionEvent(dispatchEntry->seq,
2547 dispatchEntry->resolvedEventId,
2548 motionEntry->deviceId, motionEntry->source,
2549 motionEntry->displayId, std::move(hmac),
2550 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002551 motionEntry->actionButton,
2552 dispatchEntry->resolvedFlags,
2553 motionEntry->edgeFlags, motionEntry->metaState,
2554 motionEntry->buttonState,
chaviw82357092020-01-28 13:13:06 -08002555 motionEntry->classification, xScale, yScale,
2556 xOffset, yOffset, motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002557 motionEntry->yPrecision,
2558 motionEntry->xCursorPosition,
2559 motionEntry->yCursorPosition,
2560 motionEntry->downTime, motionEntry->eventTime,
2561 motionEntry->pointerCount,
2562 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002563 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002564 break;
2565 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002566 case EventEntry::Type::FOCUS: {
2567 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2568 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002569 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002570 focusEntry->hasFocus,
2571 mInTouchMode);
2572 break;
2573 }
2574
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002575 case EventEntry::Type::CONFIGURATION_CHANGED:
2576 case EventEntry::Type::DEVICE_RESET: {
2577 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2578 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002579 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 }
2582
2583 // Check the result.
2584 if (status) {
2585 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002586 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002588 "This is unexpected because the wait queue is empty, so the pipe "
2589 "should be empty and we shouldn't have any problems writing an "
2590 "event to it, status=%d",
2591 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002592 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2593 } else {
2594 // Pipe is full and we are waiting for the app to finish process some events
2595 // before sending more events to it.
2596#if DEBUG_DISPATCH_CYCLE
2597 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002598 "waiting for the application to catch up",
2599 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 }
2602 } else {
2603 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002604 "status=%d",
2605 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2607 }
2608 return;
2609 }
2610
2611 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002612 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2613 connection->outboundQueue.end(),
2614 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002615 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002616 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002617 if (connection->responsive) {
2618 mAnrTracker.insert(dispatchEntry->timeoutTime,
2619 connection->inputChannel->getConnectionToken());
2620 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002621 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622 }
2623}
2624
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002625const std::array<uint8_t, 32> InputDispatcher::getSignature(
2626 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2627 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2628 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2629 // Only sign events up and down events as the purely move events
2630 // are tied to their up/down counterparts so signing would be redundant.
2631 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2632 verifiedEvent.actionMasked = actionMasked;
2633 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
2634 return mHmacKeyManager.sign(verifiedEvent);
2635 }
2636 return INVALID_HMAC;
2637}
2638
2639const std::array<uint8_t, 32> InputDispatcher::getSignature(
2640 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2641 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2642 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2643 verifiedEvent.action = dispatchEntry.resolvedAction;
2644 return mHmacKeyManager.sign(verifiedEvent);
2645}
2646
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002648 const sp<Connection>& connection, uint32_t seq,
2649 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650#if DEBUG_DISPATCH_CYCLE
2651 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002652 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653#endif
2654
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002655 if (connection->status == Connection::STATUS_BROKEN ||
2656 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 return;
2658 }
2659
2660 // Notify other system components and prepare to start the next dispatch cycle.
2661 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2662}
2663
2664void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002665 const sp<Connection>& connection,
2666 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667#if DEBUG_DISPATCH_CYCLE
2668 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002669 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670#endif
2671
2672 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002673 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002674 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002675 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002676 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677
2678 // The connection appears to be unrecoverably broken.
2679 // Ignore already broken or zombie connections.
2680 if (connection->status == Connection::STATUS_NORMAL) {
2681 connection->status = Connection::STATUS_BROKEN;
2682
2683 if (notify) {
2684 // Notify other system components.
2685 onDispatchCycleBrokenLocked(currentTime, connection);
2686 }
2687 }
2688}
2689
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002690void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2691 while (!queue.empty()) {
2692 DispatchEntry* dispatchEntry = queue.front();
2693 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002694 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695 }
2696}
2697
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002698void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002700 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 }
2702 delete dispatchEntry;
2703}
2704
2705int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2706 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2707
2708 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002709 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002711 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002713 "fd=%d, events=0x%x",
2714 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715 return 0; // remove the callback
2716 }
2717
2718 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002719 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2721 if (!(events & ALOOPER_EVENT_INPUT)) {
2722 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002723 "events=0x%x",
2724 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725 return 1;
2726 }
2727
2728 nsecs_t currentTime = now();
2729 bool gotOne = false;
2730 status_t status;
2731 for (;;) {
2732 uint32_t seq;
2733 bool handled;
2734 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2735 if (status) {
2736 break;
2737 }
2738 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2739 gotOne = true;
2740 }
2741 if (gotOne) {
2742 d->runCommandsLockedInterruptible();
2743 if (status == WOULD_BLOCK) {
2744 return 1;
2745 }
2746 }
2747
2748 notify = status != DEAD_OBJECT || !connection->monitor;
2749 if (notify) {
2750 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002751 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 }
2753 } else {
2754 // Monitor channels are never explicitly unregistered.
2755 // We do it automatically when the remote endpoint is closed so don't warn
2756 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002757 const bool stillHaveWindowHandle =
2758 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2759 nullptr;
2760 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761 if (notify) {
2762 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002763 "events=0x%x",
2764 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 }
2766 }
2767
2768 // Unregister the channel.
2769 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2770 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002771 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772}
2773
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002774void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002776 for (const auto& pair : mConnectionsByFd) {
2777 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778 }
2779}
2780
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002781void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002782 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002783 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2784 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2785}
2786
2787void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2788 const CancelationOptions& options,
2789 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2790 for (const auto& it : monitorsByDisplay) {
2791 const std::vector<Monitor>& monitors = it.second;
2792 for (const Monitor& monitor : monitors) {
2793 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002794 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002795 }
2796}
2797
Michael Wrightd02c5b62014-02-10 15:10:22 -08002798void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2799 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002800 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002801 if (connection == nullptr) {
2802 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002804
2805 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806}
2807
2808void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2809 const sp<Connection>& connection, const CancelationOptions& options) {
2810 if (connection->status == Connection::STATUS_BROKEN) {
2811 return;
2812 }
2813
2814 nsecs_t currentTime = now();
2815
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002816 std::vector<EventEntry*> cancelationEvents =
2817 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002819 if (cancelationEvents.empty()) {
2820 return;
2821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002823 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2824 "with reality: %s, mode=%d.",
2825 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2826 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002828
2829 InputTarget target;
2830 sp<InputWindowHandle> windowHandle =
2831 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2832 if (windowHandle != nullptr) {
2833 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2834 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2835 windowInfo->windowXScale, windowInfo->windowYScale);
2836 target.globalScaleFactor = windowInfo->globalScaleFactor;
2837 }
2838 target.inputChannel = connection->inputChannel;
2839 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2840
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002841 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2842 EventEntry* cancelationEventEntry = cancelationEvents[i];
2843 switch (cancelationEventEntry->type) {
2844 case EventEntry::Type::KEY: {
2845 logOutboundKeyDetails("cancel - ",
2846 static_cast<const KeyEntry&>(*cancelationEventEntry));
2847 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002849 case EventEntry::Type::MOTION: {
2850 logOutboundMotionDetails("cancel - ",
2851 static_cast<const MotionEntry&>(*cancelationEventEntry));
2852 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002854 case EventEntry::Type::FOCUS: {
2855 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2856 break;
2857 }
2858 case EventEntry::Type::CONFIGURATION_CHANGED:
2859 case EventEntry::Type::DEVICE_RESET: {
2860 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2861 EventEntry::typeToString(cancelationEventEntry->type));
2862 break;
2863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 }
2865
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002866 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2867 target, InputTarget::FLAG_DISPATCH_AS_IS);
2868
2869 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002871
2872 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873}
2874
Svet Ganov5d3bc372020-01-26 23:11:07 -08002875void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2876 const sp<Connection>& connection) {
2877 if (connection->status == Connection::STATUS_BROKEN) {
2878 return;
2879 }
2880
2881 nsecs_t currentTime = now();
2882
2883 std::vector<EventEntry*> downEvents =
2884 connection->inputState.synthesizePointerDownEvents(currentTime);
2885
2886 if (downEvents.empty()) {
2887 return;
2888 }
2889
2890#if DEBUG_OUTBOUND_EVENT_DETAILS
2891 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2892 connection->getInputChannelName().c_str(), downEvents.size());
2893#endif
2894
2895 InputTarget target;
2896 sp<InputWindowHandle> windowHandle =
2897 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2898 if (windowHandle != nullptr) {
2899 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2900 target.setDefaultPointerInfo(-windowInfo->frameLeft, -windowInfo->frameTop,
2901 windowInfo->windowXScale, windowInfo->windowYScale);
2902 target.globalScaleFactor = windowInfo->globalScaleFactor;
2903 }
2904 target.inputChannel = connection->inputChannel;
2905 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2906
2907 for (EventEntry* downEventEntry : downEvents) {
2908 switch (downEventEntry->type) {
2909 case EventEntry::Type::MOTION: {
2910 logOutboundMotionDetails("down - ",
2911 static_cast<const MotionEntry&>(*downEventEntry));
2912 break;
2913 }
2914
2915 case EventEntry::Type::KEY:
2916 case EventEntry::Type::FOCUS:
2917 case EventEntry::Type::CONFIGURATION_CHANGED:
2918 case EventEntry::Type::DEVICE_RESET: {
2919 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2920 EventEntry::typeToString(downEventEntry->type));
2921 break;
2922 }
2923 }
2924
2925 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2926 target, InputTarget::FLAG_DISPATCH_AS_IS);
2927
2928 downEventEntry->release();
2929 }
2930
2931 startDispatchCycleLocked(currentTime, connection);
2932}
2933
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002934MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002935 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936 ALOG_ASSERT(pointerIds.value != 0);
2937
2938 uint32_t splitPointerIndexMap[MAX_POINTERS];
2939 PointerProperties splitPointerProperties[MAX_POINTERS];
2940 PointerCoords splitPointerCoords[MAX_POINTERS];
2941
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002942 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943 uint32_t splitPointerCount = 0;
2944
2945 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002946 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002947 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002948 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949 uint32_t pointerId = uint32_t(pointerProperties.id);
2950 if (pointerIds.hasBit(pointerId)) {
2951 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2952 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2953 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002954 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955 splitPointerCount += 1;
2956 }
2957 }
2958
2959 if (splitPointerCount != pointerIds.count()) {
2960 // This is bad. We are missing some of the pointers that we expected to deliver.
2961 // Most likely this indicates that we received an ACTION_MOVE events that has
2962 // different pointer ids than we expected based on the previous ACTION_DOWN
2963 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2964 // in this way.
2965 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002966 "we expected there to be %d pointers. This probably means we received "
2967 "a broken sequence of pointer ids from the input device.",
2968 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002969 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970 }
2971
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002972 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002974 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2975 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2977 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002978 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002979 uint32_t pointerId = uint32_t(pointerProperties.id);
2980 if (pointerIds.hasBit(pointerId)) {
2981 if (pointerIds.count() == 1) {
2982 // The first/last pointer went down/up.
2983 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002984 ? AMOTION_EVENT_ACTION_DOWN
2985 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986 } else {
2987 // A secondary pointer went down/up.
2988 uint32_t splitPointerIndex = 0;
2989 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2990 splitPointerIndex += 1;
2991 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002992 action = maskedAction |
2993 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994 }
2995 } else {
2996 // An unrelated pointer changed.
2997 action = AMOTION_EVENT_ACTION_MOVE;
2998 }
2999 }
3000
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003001 int32_t newId = mIdGenerator.nextId();
3002 if (ATRACE_ENABLED()) {
3003 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3004 ") to MotionEvent(id=0x%" PRIx32 ").",
3005 originalMotionEntry.id, newId);
3006 ATRACE_NAME(message.c_str());
3007 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003008 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003009 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3010 originalMotionEntry.source, originalMotionEntry.displayId,
3011 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003012 originalMotionEntry.actionButton, originalMotionEntry.flags,
3013 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3014 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3015 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3016 originalMotionEntry.xCursorPosition,
3017 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003018 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003020 if (originalMotionEntry.injectionState) {
3021 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003022 splitMotionEntry->injectionState->refCount += 1;
3023 }
3024
3025 return splitMotionEntry;
3026}
3027
3028void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3029#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003030 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031#endif
3032
3033 bool needWake;
3034 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003035 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036
Prabir Pradhan42611e02018-11-27 14:04:02 -08003037 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003038 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039 needWake = enqueueInboundEventLocked(newEntry);
3040 } // release lock
3041
3042 if (needWake) {
3043 mLooper->wake();
3044 }
3045}
3046
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003047/**
3048 * If one of the meta shortcuts is detected, process them here:
3049 * Meta + Backspace -> generate BACK
3050 * Meta + Enter -> generate HOME
3051 * This will potentially overwrite keyCode and metaState.
3052 */
3053void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003054 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003055 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3056 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3057 if (keyCode == AKEYCODE_DEL) {
3058 newKeyCode = AKEYCODE_BACK;
3059 } else if (keyCode == AKEYCODE_ENTER) {
3060 newKeyCode = AKEYCODE_HOME;
3061 }
3062 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003063 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003064 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003065 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003066 keyCode = newKeyCode;
3067 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3068 }
3069 } else if (action == AKEY_EVENT_ACTION_UP) {
3070 // In order to maintain a consistent stream of up and down events, check to see if the key
3071 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3072 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003073 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003074 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003075 auto replacementIt = mReplacedKeys.find(replacement);
3076 if (replacementIt != mReplacedKeys.end()) {
3077 keyCode = replacementIt->second;
3078 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003079 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3080 }
3081 }
3082}
3083
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3085#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3087 "policyFlags=0x%x, action=0x%x, "
3088 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3089 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3090 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3091 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092#endif
3093 if (!validateKeyEvent(args->action)) {
3094 return;
3095 }
3096
3097 uint32_t policyFlags = args->policyFlags;
3098 int32_t flags = args->flags;
3099 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003100 // InputDispatcher tracks and generates key repeats on behalf of
3101 // whatever notifies it, so repeatCount should always be set to 0
3102 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3104 policyFlags |= POLICY_FLAG_VIRTUAL;
3105 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3106 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 if (policyFlags & POLICY_FLAG_FUNCTION) {
3108 metaState |= AMETA_FUNCTION_ON;
3109 }
3110
3111 policyFlags |= POLICY_FLAG_TRUSTED;
3112
Michael Wright78f24442014-08-06 15:55:28 -07003113 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003114 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003115
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003117 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003118 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3119 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120
Michael Wright2b3c3302018-03-02 17:19:13 +00003121 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003123 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3124 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003125 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003126 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128 bool needWake;
3129 { // acquire lock
3130 mLock.lock();
3131
3132 if (shouldSendKeyToInputFilterLocked(args)) {
3133 mLock.unlock();
3134
3135 policyFlags |= POLICY_FLAG_FILTERED;
3136 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3137 return; // event was consumed by the filter
3138 }
3139
3140 mLock.lock();
3141 }
3142
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003143 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003144 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003145 args->displayId, policyFlags, args->action, flags, keyCode,
3146 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147
3148 needWake = enqueueInboundEventLocked(newEntry);
3149 mLock.unlock();
3150 } // release lock
3151
3152 if (needWake) {
3153 mLooper->wake();
3154 }
3155}
3156
3157bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3158 return mInputFilterEnabled;
3159}
3160
3161void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3162#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003163 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3164 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003165 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3166 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003167 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003168 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3169 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3170 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3171 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172 for (uint32_t i = 0; i < args->pointerCount; i++) {
3173 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003174 "x=%f, y=%f, pressure=%f, size=%f, "
3175 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3176 "orientation=%f",
3177 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3178 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3179 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3180 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3181 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3182 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3183 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3184 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3185 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3186 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 }
3188#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003189 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3190 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191 return;
3192 }
3193
3194 uint32_t policyFlags = args->policyFlags;
3195 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003196
3197 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003198 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003199 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3200 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003201 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203
3204 bool needWake;
3205 { // acquire lock
3206 mLock.lock();
3207
3208 if (shouldSendMotionToInputFilterLocked(args)) {
3209 mLock.unlock();
3210
3211 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003212 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3213 args->action, args->actionButton, args->flags, args->edgeFlags,
3214 args->metaState, args->buttonState, args->classification, 1 /*xScale*/,
3215 1 /*yScale*/, 0 /* xOffset */, 0 /* yOffset */, args->xPrecision,
3216 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3217 args->downTime, args->eventTime, args->pointerCount,
3218 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219
3220 policyFlags |= POLICY_FLAG_FILTERED;
3221 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3222 return; // event was consumed by the filter
3223 }
3224
3225 mLock.lock();
3226 }
3227
3228 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003229 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003230 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003231 args->displayId, policyFlags, args->action, args->actionButton,
3232 args->flags, args->metaState, args->buttonState,
3233 args->classification, args->edgeFlags, args->xPrecision,
3234 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3235 args->downTime, args->pointerCount, args->pointerProperties,
3236 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237
3238 needWake = enqueueInboundEventLocked(newEntry);
3239 mLock.unlock();
3240 } // release lock
3241
3242 if (needWake) {
3243 mLooper->wake();
3244 }
3245}
3246
3247bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003248 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249}
3250
3251void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3252#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003253 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254 "switchMask=0x%08x",
3255 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256#endif
3257
3258 uint32_t policyFlags = args->policyFlags;
3259 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003260 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261}
3262
3263void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3264#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003265 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3266 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267#endif
3268
3269 bool needWake;
3270 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003271 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272
Prabir Pradhan42611e02018-11-27 14:04:02 -08003273 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003274 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275 needWake = enqueueInboundEventLocked(newEntry);
3276 } // release lock
3277
3278 if (needWake) {
3279 mLooper->wake();
3280 }
3281}
3282
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003283int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3284 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003285 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286#if DEBUG_INBOUND_EVENT_DETAILS
3287 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003288 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3289 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290#endif
3291
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003292 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293
3294 policyFlags |= POLICY_FLAG_INJECTED;
3295 if (hasInjectionPermission(injectorPid, injectorUid)) {
3296 policyFlags |= POLICY_FLAG_TRUSTED;
3297 }
3298
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003299 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003302 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3303 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003304 if (!validateKeyEvent(action)) {
3305 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003306 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003308 int32_t flags = incomingKey.getFlags();
3309 int32_t keyCode = incomingKey.getKeyCode();
3310 int32_t metaState = incomingKey.getMetaState();
3311 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003312 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003313 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003314 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003315 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3316 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3317 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003319 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3320 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003321 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003322
3323 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3324 android::base::Timer t;
3325 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3326 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3327 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3328 std::to_string(t.duration().count()).c_str());
3329 }
3330 }
3331
3332 mLock.lock();
3333 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003334 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3335 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003336 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3337 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003338 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 injectedEntries.push(injectedEntry);
3340 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 }
3342
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003343 case AINPUT_EVENT_TYPE_MOTION: {
3344 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3345 int32_t action = motionEvent->getAction();
3346 size_t pointerCount = motionEvent->getPointerCount();
3347 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3348 int32_t actionButton = motionEvent->getActionButton();
3349 int32_t displayId = motionEvent->getDisplayId();
3350 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3351 return INPUT_EVENT_INJECTION_FAILED;
3352 }
3353
3354 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3355 nsecs_t eventTime = motionEvent->getEventTime();
3356 android::base::Timer t;
3357 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3358 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3359 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3360 std::to_string(t.duration().count()).c_str());
3361 }
3362 }
3363
3364 mLock.lock();
3365 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3366 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3367 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003368 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3369 motionEvent->getSource(), motionEvent->getDisplayId(),
3370 policyFlags, action, actionButton, motionEvent->getFlags(),
3371 motionEvent->getMetaState(), motionEvent->getButtonState(),
3372 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3373 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003374 motionEvent->getRawXCursorPosition(),
3375 motionEvent->getRawYCursorPosition(),
3376 motionEvent->getDownTime(), uint32_t(pointerCount),
3377 pointerProperties, samplePointerCoords,
3378 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379 injectedEntries.push(injectedEntry);
3380 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3381 sampleEventTimes += 1;
3382 samplePointerCoords += pointerCount;
3383 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003384 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003385 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003386 motionEvent->getDisplayId(), policyFlags, action,
3387 actionButton, motionEvent->getFlags(),
3388 motionEvent->getMetaState(), motionEvent->getButtonState(),
3389 motionEvent->getClassification(),
3390 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3391 motionEvent->getYPrecision(),
3392 motionEvent->getRawXCursorPosition(),
3393 motionEvent->getRawYCursorPosition(),
3394 motionEvent->getDownTime(), uint32_t(pointerCount),
3395 pointerProperties, samplePointerCoords,
3396 motionEvent->getXOffset(), motionEvent->getYOffset());
3397 injectedEntries.push(nextInjectedEntry);
3398 }
3399 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003402 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003403 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003404 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 }
3406
3407 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3408 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3409 injectionState->injectionIsAsync = true;
3410 }
3411
3412 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003413 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414
3415 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003416 while (!injectedEntries.empty()) {
3417 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3418 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 }
3420
3421 mLock.unlock();
3422
3423 if (needWake) {
3424 mLooper->wake();
3425 }
3426
3427 int32_t injectionResult;
3428 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003429 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430
3431 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3432 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3433 } else {
3434 for (;;) {
3435 injectionResult = injectionState->injectionResult;
3436 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3437 break;
3438 }
3439
3440 nsecs_t remainingTimeout = endTime - now();
3441 if (remainingTimeout <= 0) {
3442#if DEBUG_INJECTION
3443 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003444 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445#endif
3446 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3447 break;
3448 }
3449
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003450 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451 }
3452
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003453 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3454 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455 while (injectionState->pendingForegroundDispatches != 0) {
3456#if DEBUG_INJECTION
3457 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003458 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459#endif
3460 nsecs_t remainingTimeout = endTime - now();
3461 if (remainingTimeout <= 0) {
3462#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003463 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3464 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465#endif
3466 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3467 break;
3468 }
3469
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003470 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 }
3472 }
3473 }
3474
3475 injectionState->release();
3476 } // release lock
3477
3478#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003479 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003480 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481#endif
3482
3483 return injectionResult;
3484}
3485
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003486std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003487 std::array<uint8_t, 32> calculatedHmac;
3488 std::unique_ptr<VerifiedInputEvent> result;
3489 switch (event.getType()) {
3490 case AINPUT_EVENT_TYPE_KEY: {
3491 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3492 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3493 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
3494 calculatedHmac = mHmacKeyManager.sign(verifiedKeyEvent);
3495 break;
3496 }
3497 case AINPUT_EVENT_TYPE_MOTION: {
3498 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3499 VerifiedMotionEvent verifiedMotionEvent =
3500 verifiedMotionEventFromMotionEvent(motionEvent);
3501 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
3502 calculatedHmac = mHmacKeyManager.sign(verifiedMotionEvent);
3503 break;
3504 }
3505 default: {
3506 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3507 return nullptr;
3508 }
3509 }
3510 if (calculatedHmac == INVALID_HMAC) {
3511 return nullptr;
3512 }
3513 if (calculatedHmac != event.getHmac()) {
3514 return nullptr;
3515 }
3516 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003517}
3518
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003520 return injectorUid == 0 ||
3521 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522}
3523
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003524void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525 InjectionState* injectionState = entry->injectionState;
3526 if (injectionState) {
3527#if DEBUG_INJECTION
3528 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003529 "injectorPid=%d, injectorUid=%d",
3530 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531#endif
3532
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003533 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 // Log the outcome since the injector did not wait for the injection result.
3535 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003536 case INPUT_EVENT_INJECTION_SUCCEEDED:
3537 ALOGV("Asynchronous input event injection succeeded.");
3538 break;
3539 case INPUT_EVENT_INJECTION_FAILED:
3540 ALOGW("Asynchronous input event injection failed.");
3541 break;
3542 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3543 ALOGW("Asynchronous input event injection permission denied.");
3544 break;
3545 case INPUT_EVENT_INJECTION_TIMED_OUT:
3546 ALOGW("Asynchronous input event injection timed out.");
3547 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548 }
3549 }
3550
3551 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003552 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553 }
3554}
3555
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003556void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 InjectionState* injectionState = entry->injectionState;
3558 if (injectionState) {
3559 injectionState->pendingForegroundDispatches += 1;
3560 }
3561}
3562
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003563void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 InjectionState* injectionState = entry->injectionState;
3565 if (injectionState) {
3566 injectionState->pendingForegroundDispatches -= 1;
3567
3568 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003569 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570 }
3571 }
3572}
3573
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003574std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3575 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003576 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003577}
3578
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003580 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003581 if (windowHandleToken == nullptr) {
3582 return nullptr;
3583 }
3584
Arthur Hungb92218b2018-08-14 12:00:21 +08003585 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003586 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3587 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003588 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003589 return windowHandle;
3590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 }
3592 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003593 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594}
3595
Mady Mellor017bcd12020-06-23 19:12:00 +00003596bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3597 for (auto& it : mWindowHandlesByDisplay) {
3598 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3599 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003600 if (handle->getId() == windowHandle->getId() &&
3601 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003602 if (windowHandle->getInfo()->displayId != it.first) {
3603 ALOGE("Found window %s in display %" PRId32
3604 ", but it should belong to display %" PRId32,
3605 windowHandle->getName().c_str(), it.first,
3606 windowHandle->getInfo()->displayId);
3607 }
3608 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 }
3611 }
3612 return false;
3613}
3614
Robert Carr5c8a0262018-10-03 16:30:44 -07003615sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3616 size_t count = mInputChannelsByToken.count(token);
3617 if (count == 0) {
3618 return nullptr;
3619 }
3620 return mInputChannelsByToken.at(token);
3621}
3622
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003623void InputDispatcher::updateWindowHandlesForDisplayLocked(
3624 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3625 if (inputWindowHandles.empty()) {
3626 // Remove all handles on a display if there are no windows left.
3627 mWindowHandlesByDisplay.erase(displayId);
3628 return;
3629 }
3630
3631 // Since we compare the pointer of input window handles across window updates, we need
3632 // to make sure the handle object for the same window stays unchanged across updates.
3633 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003634 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003635 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003636 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003637 }
3638
3639 std::vector<sp<InputWindowHandle>> newHandles;
3640 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3641 if (!handle->updateInfo()) {
3642 // handle no longer valid
3643 continue;
3644 }
3645
3646 const InputWindowInfo* info = handle->getInfo();
3647 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3648 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3649 const bool noInputChannel =
3650 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3651 const bool canReceiveInput =
3652 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3653 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3654 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003655 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003656 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003657 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003658 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003659 }
3660
3661 if (info->displayId != displayId) {
3662 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3663 handle->getName().c_str(), displayId, info->displayId);
3664 continue;
3665 }
3666
Robert Carredd13602020-04-13 17:24:34 -07003667 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3668 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003669 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003670 oldHandle->updateFrom(handle);
3671 newHandles.push_back(oldHandle);
3672 } else {
3673 newHandles.push_back(handle);
3674 }
3675 }
3676
3677 // Insert or replace
3678 mWindowHandlesByDisplay[displayId] = newHandles;
3679}
3680
Arthur Hung72d8dc32020-03-28 00:48:39 +00003681void InputDispatcher::setInputWindows(
3682 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3683 { // acquire lock
3684 std::scoped_lock _l(mLock);
3685 for (auto const& i : handlesPerDisplay) {
3686 setInputWindowsLocked(i.second, i.first);
3687 }
3688 }
3689 // Wake up poll loop since it may need to make new input dispatching choices.
3690 mLooper->wake();
3691}
3692
Arthur Hungb92218b2018-08-14 12:00:21 +08003693/**
3694 * Called from InputManagerService, update window handle list by displayId that can receive input.
3695 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3696 * If set an empty list, remove all handles from the specific display.
3697 * For focused handle, check if need to change and send a cancel event to previous one.
3698 * For removed handle, check if need to send a cancel event if already in touch.
3699 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003700void InputDispatcher::setInputWindowsLocked(
3701 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003702 if (DEBUG_FOCUS) {
3703 std::string windowList;
3704 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3705 windowList += iwh->getName() + " ";
3706 }
3707 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3708 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709
Arthur Hung72d8dc32020-03-28 00:48:39 +00003710 // Copy old handles for release if they are no longer present.
3711 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712
Arthur Hung72d8dc32020-03-28 00:48:39 +00003713 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003714
Arthur Hung72d8dc32020-03-28 00:48:39 +00003715 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3716 bool foundHoveredWindow = false;
3717 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3718 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3719 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3720 windowHandle->getInfo()->visible) {
3721 newFocusedWindowHandle = windowHandle;
3722 }
3723 if (windowHandle == mLastHoverWindowHandle) {
3724 foundHoveredWindow = true;
3725 }
3726 }
3727
3728 if (!foundHoveredWindow) {
3729 mLastHoverWindowHandle = nullptr;
3730 }
3731
3732 sp<InputWindowHandle> oldFocusedWindowHandle =
3733 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3734
3735 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
3736 if (oldFocusedWindowHandle != nullptr) {
3737 if (DEBUG_FOCUS) {
3738 ALOGD("Focus left window: %s in display %" PRId32,
3739 oldFocusedWindowHandle->getName().c_str(), displayId);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003740 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003741 sp<InputChannel> focusedInputChannel =
3742 getInputChannelLocked(oldFocusedWindowHandle->getToken());
3743 if (focusedInputChannel != nullptr) {
3744 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3745 "focus left window");
3746 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
3747 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003748 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003749 mFocusedWindowHandlesByDisplay.erase(displayId);
3750 }
3751 if (newFocusedWindowHandle != nullptr) {
3752 if (DEBUG_FOCUS) {
3753 ALOGD("Focus entered window: %s in display %" PRId32,
3754 newFocusedWindowHandle->getName().c_str(), displayId);
3755 }
3756 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
3757 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 }
3759
Arthur Hung72d8dc32020-03-28 00:48:39 +00003760 if (mFocusedDisplayId == displayId) {
3761 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003765 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3766 mTouchStatesByDisplay.find(displayId);
3767 if (stateIt != mTouchStatesByDisplay.end()) {
3768 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003769 for (size_t i = 0; i < state.windows.size();) {
3770 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003771 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003772 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003773 ALOGD("Touched window was removed: %s in display %" PRId32,
3774 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003775 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003776 sp<InputChannel> touchedInputChannel =
3777 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3778 if (touchedInputChannel != nullptr) {
3779 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3780 "touched window was removed");
3781 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003783 state.windows.erase(state.windows.begin() + i);
3784 } else {
3785 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 }
3787 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003788 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003789
Arthur Hung72d8dc32020-03-28 00:48:39 +00003790 // Release information for windows that are no longer present.
3791 // This ensures that unused input channels are released promptly.
3792 // Otherwise, they might stick around until the window handle is destroyed
3793 // which might not happen until the next GC.
3794 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003795 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003796 if (DEBUG_FOCUS) {
3797 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003798 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003799 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003800 }
chaviw291d88a2019-02-14 10:33:58 -08003801 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802}
3803
3804void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003805 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003806 if (DEBUG_FOCUS) {
3807 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3808 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003811 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812
Tiger Huang721e26f2018-07-24 22:26:19 +08003813 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3814 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003815
3816 if (oldFocusedApplicationHandle == mAwaitedFocusedApplication &&
3817 inputApplicationHandle != oldFocusedApplicationHandle) {
3818 resetNoFocusedWindowTimeoutLocked();
3819 }
3820
Yi Kong9b14ac62018-07-17 13:48:38 -07003821 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003822 if (oldFocusedApplicationHandle != inputApplicationHandle) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003823 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003825 } else if (oldFocusedApplicationHandle != nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003826 oldFocusedApplicationHandle.clear();
3827 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829 } // release lock
3830
3831 // Wake up poll loop since it may need to make new input dispatching choices.
3832 mLooper->wake();
3833}
3834
Tiger Huang721e26f2018-07-24 22:26:19 +08003835/**
3836 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3837 * the display not specified.
3838 *
3839 * We track any unreleased events for each window. If a window loses the ability to receive the
3840 * released event, we will send a cancel event to it. So when the focused display is changed, we
3841 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3842 * display. The display-specified events won't be affected.
3843 */
3844void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003845 if (DEBUG_FOCUS) {
3846 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3847 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003848 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003849 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003850
3851 if (mFocusedDisplayId != displayId) {
3852 sp<InputWindowHandle> oldFocusedWindowHandle =
3853 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3854 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003855 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003856 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003857 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003858 CancelationOptions
3859 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3860 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003861 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003862 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3863 }
3864 }
3865 mFocusedDisplayId = displayId;
3866
3867 // Sanity check
3868 sp<InputWindowHandle> newFocusedWindowHandle =
3869 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003870 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003871
Tiger Huang721e26f2018-07-24 22:26:19 +08003872 if (newFocusedWindowHandle == nullptr) {
3873 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3874 if (!mFocusedWindowHandlesByDisplay.empty()) {
3875 ALOGE("But another display has a focused window:");
3876 for (auto& it : mFocusedWindowHandlesByDisplay) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003877 const sp<InputWindowHandle>& windowHandle = it.second;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05003878 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", it.first,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003879 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003880 }
3881 }
3882 }
3883 }
3884
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003885 if (DEBUG_FOCUS) {
3886 logDispatchStateLocked();
3887 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003888 } // release lock
3889
3890 // Wake up poll loop since it may need to make new input dispatching choices.
3891 mLooper->wake();
3892}
3893
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003895 if (DEBUG_FOCUS) {
3896 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898
3899 bool changed;
3900 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003901 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902
3903 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3904 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003905 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906 }
3907
3908 if (mDispatchEnabled && !enabled) {
3909 resetAndDropEverythingLocked("dispatcher is being disabled");
3910 }
3911
3912 mDispatchEnabled = enabled;
3913 mDispatchFrozen = frozen;
3914 changed = true;
3915 } else {
3916 changed = false;
3917 }
3918
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003919 if (DEBUG_FOCUS) {
3920 logDispatchStateLocked();
3921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922 } // release lock
3923
3924 if (changed) {
3925 // Wake up poll loop since it may need to make new input dispatching choices.
3926 mLooper->wake();
3927 }
3928}
3929
3930void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003931 if (DEBUG_FOCUS) {
3932 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934
3935 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003936 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937
3938 if (mInputFilterEnabled == enabled) {
3939 return;
3940 }
3941
3942 mInputFilterEnabled = enabled;
3943 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3944 } // release lock
3945
3946 // Wake up poll loop since there might be work to do to drop everything.
3947 mLooper->wake();
3948}
3949
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08003950void InputDispatcher::setInTouchMode(bool inTouchMode) {
3951 std::scoped_lock lock(mLock);
3952 mInTouchMode = inTouchMode;
3953}
3954
chaviwfbe5d9c2018-12-26 12:23:37 -08003955bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3956 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003957 if (DEBUG_FOCUS) {
3958 ALOGD("Trivial transfer to same window.");
3959 }
chaviwfbe5d9c2018-12-26 12:23:37 -08003960 return true;
3961 }
3962
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003964 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965
chaviwfbe5d9c2018-12-26 12:23:37 -08003966 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3967 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003968 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003969 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 return false;
3971 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003972 if (DEBUG_FOCUS) {
3973 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3974 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003977 if (DEBUG_FOCUS) {
3978 ALOGD("Cannot transfer focus because windows are on different displays.");
3979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 return false;
3981 }
3982
3983 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003984 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
3985 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003986 for (size_t i = 0; i < state.windows.size(); i++) {
3987 const TouchedWindow& touchedWindow = state.windows[i];
3988 if (touchedWindow.windowHandle == fromWindowHandle) {
3989 int32_t oldTargetFlags = touchedWindow.targetFlags;
3990 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003992 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003994 int32_t newTargetFlags = oldTargetFlags &
3995 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3996 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003997 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998
Jeff Brownf086ddb2014-02-11 14:28:48 -08003999 found = true;
4000 goto Found;
4001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002 }
4003 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004004 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004006 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004007 if (DEBUG_FOCUS) {
4008 ALOGD("Focus transfer failed because from window did not have focus.");
4009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 return false;
4011 }
4012
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004013 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4014 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004015 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004016 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004017 CancelationOptions
4018 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4019 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004021 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022 }
4023
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004024 if (DEBUG_FOCUS) {
4025 logDispatchStateLocked();
4026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027 } // release lock
4028
4029 // Wake up poll loop since it may need to make new input dispatching choices.
4030 mLooper->wake();
4031 return true;
4032}
4033
4034void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004035 if (DEBUG_FOCUS) {
4036 ALOGD("Resetting and dropping all events (%s).", reason);
4037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038
4039 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4040 synthesizeCancelationEventsForAllConnectionsLocked(options);
4041
4042 resetKeyRepeatLocked();
4043 releasePendingEventLocked();
4044 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004045 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004047 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004048 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004050 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051}
4052
4053void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004054 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055 dumpDispatchStateLocked(dump);
4056
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004057 std::istringstream stream(dump);
4058 std::string line;
4059
4060 while (std::getline(stream, line, '\n')) {
4061 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062 }
4063}
4064
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004065void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004066 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4067 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4068 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004069 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070
Tiger Huang721e26f2018-07-24 22:26:19 +08004071 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4072 dump += StringPrintf(INDENT "FocusedApplications:\n");
4073 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4074 const int32_t displayId = it.first;
4075 const sp<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004076 const int64_t timeoutMillis = millis(
4077 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004078 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004079 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004080 displayId, applicationHandle->getName().c_str(), timeoutMillis);
Tiger Huang721e26f2018-07-24 22:26:19 +08004081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004083 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004085
4086 if (!mFocusedWindowHandlesByDisplay.empty()) {
4087 dump += StringPrintf(INDENT "FocusedWindows:\n");
4088 for (auto& it : mFocusedWindowHandlesByDisplay) {
4089 const int32_t displayId = it.first;
4090 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004091 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4092 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004093 }
4094 } else {
4095 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004098 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004099 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004100 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4101 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004102 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004103 state.displayId, toString(state.down), toString(state.split),
4104 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004105 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004106 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004107 for (size_t i = 0; i < state.windows.size(); i++) {
4108 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004109 dump += StringPrintf(INDENT4
4110 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4111 i, touchedWindow.windowHandle->getName().c_str(),
4112 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004113 }
4114 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004115 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004116 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004117 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004118 dump += INDENT3 "Portal windows:\n";
4119 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004120 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004121 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4122 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004123 }
4124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 }
4126 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004127 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128 }
4129
Arthur Hungb92218b2018-08-14 12:00:21 +08004130 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004131 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004132 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004133 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004134 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004135 dump += INDENT2 "Windows:\n";
4136 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004137 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004138 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139
Arthur Hungb92218b2018-08-14 12:00:21 +08004140 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004141 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
chaviwcb923212019-12-30 14:05:11 -08004142 "hasWallpaper=%s, visible=%s, canReceiveKeys=%s, "
4143 "flags=0x%08x, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004144 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviwcb923212019-12-30 14:05:11 -08004145 "windowScale=(%f,%f), touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004146 i, windowInfo->name.c_str(), windowInfo->displayId,
4147 windowInfo->portalToDisplayId,
4148 toString(windowInfo->paused),
4149 toString(windowInfo->hasFocus),
4150 toString(windowInfo->hasWallpaper),
4151 toString(windowInfo->visible),
4152 toString(windowInfo->canReceiveKeys),
4153 windowInfo->layoutParamsFlags,
chaviwcb923212019-12-30 14:05:11 -08004154 windowInfo->layoutParamsType, windowInfo->frameLeft,
4155 windowInfo->frameTop, windowInfo->frameRight,
4156 windowInfo->frameBottom, windowInfo->globalScaleFactor,
4157 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08004158 dumpRegion(dump, windowInfo->touchableRegion);
4159 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004160 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4161 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004162 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004163 millis(windowInfo->dispatchingTimeout));
Siarhei Vishniakou67d44502020-04-09 11:09:29 -07004164 dump += StringPrintf(INDENT4 " flags: %s\n",
4165 inputWindowFlagsToString(windowInfo->layoutParamsFlags)
4166 .c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08004167 }
4168 } else {
4169 dump += INDENT2 "Windows: <none>\n";
4170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 }
4172 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004173 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 }
4175
Michael Wright3dd60e22019-03-27 22:06:44 +00004176 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004177 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004178 const std::vector<Monitor>& monitors = it.second;
4179 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4180 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004181 }
4182 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004183 const std::vector<Monitor>& monitors = it.second;
4184 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4185 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004188 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 }
4190
4191 nsecs_t currentTime = now();
4192
4193 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004194 if (!mRecentQueue.empty()) {
4195 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4196 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004197 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004199 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 }
4201 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004202 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 }
4204
4205 // Dump event currently being dispatched.
4206 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004207 dump += INDENT "PendingEvent:\n";
4208 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004210 dump += StringPrintf(", age=%" PRId64 "ms\n",
4211 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004213 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 }
4215
4216 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004217 if (!mInboundQueue.empty()) {
4218 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4219 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004220 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004222 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 }
4224 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004225 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 }
4227
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004228 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004229 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004230 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4231 const KeyReplacement& replacement = pair.first;
4232 int32_t newKeyCode = pair.second;
4233 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004234 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004235 }
4236 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004237 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004238 }
4239
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004240 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004241 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004242 for (const auto& pair : mConnectionsByFd) {
4243 const sp<Connection>& connection = pair.second;
4244 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004245 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004246 pair.first, connection->getInputChannelName().c_str(),
4247 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004248 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004250 if (!connection->outboundQueue.empty()) {
4251 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4252 connection->outboundQueue.size());
4253 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254 dump.append(INDENT4);
4255 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004256 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4257 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004258 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004259 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 }
4261 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004262 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 }
4264
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004265 if (!connection->waitQueue.empty()) {
4266 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4267 connection->waitQueue.size());
4268 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004269 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004271 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004272 "age=%" PRId64 "ms, wait=%" PRId64 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004273 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004274 ns2ms(currentTime - entry->eventEntry->eventTime),
4275 ns2ms(currentTime - entry->deliveryTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 }
4277 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004278 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 }
4280 }
4281 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004282 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 }
4284
4285 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004286 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4287 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004289 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 }
4291
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004292 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004293 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4294 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4295 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296}
4297
Michael Wright3dd60e22019-03-27 22:06:44 +00004298void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4299 const size_t numMonitors = monitors.size();
4300 for (size_t i = 0; i < numMonitors; i++) {
4301 const Monitor& monitor = monitors[i];
4302 const sp<InputChannel>& channel = monitor.inputChannel;
4303 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4304 dump += "\n";
4305 }
4306}
4307
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004308status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004310 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311#endif
4312
4313 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004314 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004315 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004316 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004318 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 return BAD_VALUE;
4320 }
4321
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004322 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323
4324 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004325 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004326 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4329 } // release lock
4330
4331 // Wake the looper because some connections have changed.
4332 mLooper->wake();
4333 return OK;
4334}
4335
Michael Wright3dd60e22019-03-27 22:06:44 +00004336status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004337 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004338 { // acquire lock
4339 std::scoped_lock _l(mLock);
4340
4341 if (displayId < 0) {
4342 ALOGW("Attempted to register input monitor without a specified display.");
4343 return BAD_VALUE;
4344 }
4345
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004346 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004347 ALOGW("Attempted to register input monitor without an identifying token.");
4348 return BAD_VALUE;
4349 }
4350
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004351 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004352
4353 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004354 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004355 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004356
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004357 auto& monitorsByDisplay =
4358 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004359 monitorsByDisplay[displayId].emplace_back(inputChannel);
4360
4361 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004362 }
4363 // Wake the looper because some connections have changed.
4364 mLooper->wake();
4365 return OK;
4366}
4367
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
4369#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004370 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371#endif
4372
4373 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004374 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375
4376 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4377 if (status) {
4378 return status;
4379 }
4380 } // release lock
4381
4382 // Wake the poll loop because removing the connection may have changed the current
4383 // synchronization state.
4384 mLooper->wake();
4385 return OK;
4386}
4387
4388status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004389 bool notify) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004390 sp<Connection> connection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004391 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004393 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 return BAD_VALUE;
4395 }
4396
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004397 removeConnectionLocked(connection);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004398 mInputChannelsByToken.erase(inputChannel->getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004399
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400 if (connection->monitor) {
4401 removeMonitorChannelLocked(inputChannel);
4402 }
4403
4404 mLooper->removeFd(inputChannel->getFd());
4405
4406 nsecs_t currentTime = now();
4407 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4408
4409 connection->status = Connection::STATUS_ZOMBIE;
4410 return OK;
4411}
4412
4413void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004414 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4415 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4416}
4417
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004418void InputDispatcher::removeMonitorChannelLocked(
4419 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004420 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004421 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004422 std::vector<Monitor>& monitors = it->second;
4423 const size_t numMonitors = monitors.size();
4424 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004425 if (monitors[i].inputChannel == inputChannel) {
4426 monitors.erase(monitors.begin() + i);
4427 break;
4428 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004429 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004430 if (monitors.empty()) {
4431 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004432 } else {
4433 ++it;
4434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435 }
4436}
4437
Michael Wright3dd60e22019-03-27 22:06:44 +00004438status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4439 { // acquire lock
4440 std::scoped_lock _l(mLock);
4441 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4442
4443 if (!foundDisplayId) {
4444 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4445 return BAD_VALUE;
4446 }
4447 int32_t displayId = foundDisplayId.value();
4448
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004449 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4450 mTouchStatesByDisplay.find(displayId);
4451 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004452 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4453 return BAD_VALUE;
4454 }
4455
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004456 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004457 std::optional<int32_t> foundDeviceId;
4458 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004459 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004460 foundDeviceId = state.deviceId;
4461 }
4462 }
4463 if (!foundDeviceId || !state.down) {
4464 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004465 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004466 return BAD_VALUE;
4467 }
4468 int32_t deviceId = foundDeviceId.value();
4469
4470 // Send cancel events to all the input channels we're stealing from.
4471 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004472 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004473 options.deviceId = deviceId;
4474 options.displayId = displayId;
4475 for (const TouchedWindow& window : state.windows) {
4476 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004477 if (channel != nullptr) {
4478 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4479 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004480 }
4481 // Then clear the current touch state so we stop dispatching to them as well.
4482 state.filterNonMonitors();
4483 }
4484 return OK;
4485}
4486
Michael Wright3dd60e22019-03-27 22:06:44 +00004487std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4488 const sp<IBinder>& token) {
4489 for (const auto& it : mGestureMonitorsByDisplay) {
4490 const std::vector<Monitor>& monitors = it.second;
4491 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004492 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004493 return it.first;
4494 }
4495 }
4496 }
4497 return std::nullopt;
4498}
4499
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004500sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004501 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004502 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004503 }
4504
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004505 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004506 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004507 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004508 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 }
4510 }
Robert Carr4e670e52018-08-15 13:26:12 -07004511
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004512 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513}
4514
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004515void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004516 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004517 removeByValue(mConnectionsByFd, connection);
4518}
4519
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004520void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4521 const sp<Connection>& connection, uint32_t seq,
4522 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004523 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4524 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 commandEntry->connection = connection;
4526 commandEntry->eventTime = currentTime;
4527 commandEntry->seq = seq;
4528 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004529 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530}
4531
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004532void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4533 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004535 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004537 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4538 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004540 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541}
4542
chaviw0c06c6e2019-01-09 13:27:07 -08004543void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004544 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004545 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4546 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004547 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4548 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004549 commandEntry->oldToken = oldToken;
4550 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004551 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004552}
4553
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004554void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4555 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4556 // is already healthy again. Don't raise ANR in this situation
4557 if (connection->waitQueue.empty()) {
4558 ALOGI("Not raising ANR because the connection %s has recovered",
4559 connection->inputChannel->getName().c_str());
4560 return;
4561 }
4562 /**
4563 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4564 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4565 * has changed. This could cause newer entries to time out before the already dispatched
4566 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4567 * processes the events linearly. So providing information about the oldest entry seems to be
4568 * most useful.
4569 */
4570 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4571 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4572 std::string reason =
4573 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4574 connection->inputChannel->getName().c_str(),
4575 ns2ms(currentWait),
4576 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004578 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4579 reason);
4580
4581 std::unique_ptr<CommandEntry> commandEntry =
4582 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4583 commandEntry->inputApplicationHandle = nullptr;
4584 commandEntry->inputChannel = connection->inputChannel;
4585 commandEntry->reason = std::move(reason);
4586 postCommandLocked(std::move(commandEntry));
4587}
4588
4589void InputDispatcher::onAnrLocked(const sp<InputApplicationHandle>& application) {
4590 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4591 application->getName().c_str());
4592
4593 updateLastAnrStateLocked(application, reason);
4594
4595 std::unique_ptr<CommandEntry> commandEntry =
4596 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4597 commandEntry->inputApplicationHandle = application;
4598 commandEntry->inputChannel = nullptr;
4599 commandEntry->reason = std::move(reason);
4600 postCommandLocked(std::move(commandEntry));
4601}
4602
4603void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4604 const std::string& reason) {
4605 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4606 updateLastAnrStateLocked(windowLabel, reason);
4607}
4608
4609void InputDispatcher::updateLastAnrStateLocked(const sp<InputApplicationHandle>& application,
4610 const std::string& reason) {
4611 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4612 updateLastAnrStateLocked(windowLabel, reason);
4613}
4614
4615void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4616 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004618 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619 struct tm tm;
4620 localtime_r(&t, &tm);
4621 char timestr[64];
4622 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004623 mLastAnrState.clear();
4624 mLastAnrState += INDENT "ANR:\n";
4625 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004626 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4627 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004628 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629}
4630
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004631void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 mLock.unlock();
4633
4634 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4635
4636 mLock.lock();
4637}
4638
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004639void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640 sp<Connection> connection = commandEntry->connection;
4641
4642 if (connection->status != Connection::STATUS_ZOMBIE) {
4643 mLock.unlock();
4644
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004645 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004646
4647 mLock.lock();
4648 }
4649}
4650
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004651void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004652 sp<IBinder> oldToken = commandEntry->oldToken;
4653 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004654 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004655 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004656 mLock.lock();
4657}
4658
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004659void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004660 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004661 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662 mLock.unlock();
4663
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004664 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004665 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666
4667 mLock.lock();
4668
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004669 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004670 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4671 } else {
4672 // stop waking up for events in this connection, it is already not responding
4673 sp<Connection> connection = getConnectionLocked(token);
4674 if (connection == nullptr) {
4675 return;
4676 }
4677 cancelEventsForAnrLocked(connection);
4678 }
4679}
4680
4681void InputDispatcher::extendAnrTimeoutsLocked(const sp<InputApplicationHandle>& application,
4682 const sp<IBinder>& connectionToken,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004683 std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004684 sp<Connection> connection = getConnectionLocked(connectionToken);
4685 if (connection == nullptr) {
4686 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4687 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004688 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004689 mAwaitedFocusedApplication = application;
4690 } else {
4691 // It's also possible that the connection already disappeared. No action necessary.
4692 }
4693 return;
4694 }
4695
4696 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004697 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004698
4699 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004700 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004701 for (DispatchEntry* entry : connection->waitQueue) {
4702 if (newTimeout >= entry->timeoutTime) {
4703 // Already removed old entries when connection was marked unresponsive
4704 entry->timeoutTime = newTimeout;
4705 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4706 }
4707 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708}
4709
4710void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4711 CommandEntry* commandEntry) {
4712 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004713 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714
4715 mLock.unlock();
4716
Michael Wright2b3c3302018-03-02 17:19:13 +00004717 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004718 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004719 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004720 : nullptr;
4721 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004722 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4723 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004724 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726
4727 mLock.lock();
4728
4729 if (delay < 0) {
4730 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4731 } else if (!delay) {
4732 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4733 } else {
4734 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4735 entry->interceptKeyWakeupTime = now() + delay;
4736 }
4737 entry->release();
4738}
4739
chaviwfd6d3512019-03-25 13:23:49 -07004740void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4741 mLock.unlock();
4742 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4743 mLock.lock();
4744}
4745
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004746/**
4747 * Connection is responsive if it has no events in the waitQueue that are older than the
4748 * current time.
4749 */
4750static bool isConnectionResponsive(const Connection& connection) {
4751 const nsecs_t currentTime = now();
4752 for (const DispatchEntry* entry : connection.waitQueue) {
4753 if (entry->timeoutTime < currentTime) {
4754 return false;
4755 }
4756 }
4757 return true;
4758}
4759
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004760void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004761 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004762 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004763 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004764 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765
4766 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004767 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004768 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004769 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004771 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004772 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004773 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004774 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4775 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004776 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004777 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004778
4779 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004780 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004781 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4782 restartEvent =
4783 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004784 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004785 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4786 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4787 handled);
4788 } else {
4789 restartEvent = false;
4790 }
4791
4792 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004793 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004794 // contents of the wait queue to have been drained, so we need to double-check
4795 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004796 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4797 if (dispatchEntryIt != connection->waitQueue.end()) {
4798 dispatchEntry = *dispatchEntryIt;
4799 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004800 mAnrTracker.erase(dispatchEntry->timeoutTime,
4801 connection->inputChannel->getConnectionToken());
4802 if (!connection->responsive) {
4803 connection->responsive = isConnectionResponsive(*connection);
4804 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004805 traceWaitQueueLength(connection);
4806 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004807 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004808 traceOutboundQueueLength(connection);
4809 } else {
4810 releaseDispatchEntry(dispatchEntry);
4811 }
4812 }
4813
4814 // Start the next dispatch cycle for this connection.
4815 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816}
4817
4818bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004819 DispatchEntry* dispatchEntry,
4820 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004821 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004822 if (!handled) {
4823 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004824 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004825 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004826 return false;
4827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004829 // Get the fallback key state.
4830 // Clear it out after dispatching the UP.
4831 int32_t originalKeyCode = keyEntry->keyCode;
4832 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4833 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4834 connection->inputState.removeFallbackKey(originalKeyCode);
4835 }
4836
4837 if (handled || !dispatchEntry->hasForegroundTarget()) {
4838 // If the application handles the original key for which we previously
4839 // generated a fallback or if the window is not a foreground window,
4840 // then cancel the associated fallback key, if any.
4841 if (fallbackKeyCode != -1) {
4842 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004844 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004845 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4846 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4847 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004849 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004850 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851
4852 mLock.unlock();
4853
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004854 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004855 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004856
4857 mLock.lock();
4858
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004859 // Cancel the fallback key.
4860 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004862 "application handled the original non-fallback key "
4863 "or is no longer a foreground target, "
4864 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 options.keyCode = fallbackKeyCode;
4866 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004868 connection->inputState.removeFallbackKey(originalKeyCode);
4869 }
4870 } else {
4871 // If the application did not handle a non-fallback key, first check
4872 // that we are in a good state to perform unhandled key event processing
4873 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004874 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004875 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004877 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004878 "since this is not an initial down. "
4879 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4880 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004882 return false;
4883 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004884
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004885 // Dispatch the unhandled key to the policy.
4886#if DEBUG_OUTBOUND_EVENT_DETAILS
4887 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004888 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4889 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004890#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004891 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004892
4893 mLock.unlock();
4894
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004895 bool fallback =
4896 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4897 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004898
4899 mLock.lock();
4900
4901 if (connection->status != Connection::STATUS_NORMAL) {
4902 connection->inputState.removeFallbackKey(originalKeyCode);
4903 return false;
4904 }
4905
4906 // Latch the fallback keycode for this key on an initial down.
4907 // The fallback keycode cannot change at any other point in the lifecycle.
4908 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004910 fallbackKeyCode = event.getKeyCode();
4911 } else {
4912 fallbackKeyCode = AKEYCODE_UNKNOWN;
4913 }
4914 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4915 }
4916
4917 ALOG_ASSERT(fallbackKeyCode != -1);
4918
4919 // Cancel the fallback key if the policy decides not to send it anymore.
4920 // We will continue to dispatch the key to the policy but we will no
4921 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004922 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4923 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004924#if DEBUG_OUTBOUND_EVENT_DETAILS
4925 if (fallback) {
4926 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004927 "as a fallback for %d, but on the DOWN it had requested "
4928 "to send %d instead. Fallback canceled.",
4929 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004930 } else {
4931 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004932 "but on the DOWN it had requested to send %d. "
4933 "Fallback canceled.",
4934 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004935 }
4936#endif
4937
4938 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4939 "canceling fallback, policy no longer desires it");
4940 options.keyCode = fallbackKeyCode;
4941 synthesizeCancelationEventsForConnectionLocked(connection, options);
4942
4943 fallback = false;
4944 fallbackKeyCode = AKEYCODE_UNKNOWN;
4945 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004946 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004947 }
4948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004949
4950#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004951 {
4952 std::string msg;
4953 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4954 connection->inputState.getFallbackKeys();
4955 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004956 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004957 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004958 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004959 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004960 }
4961#endif
4962
4963 if (fallback) {
4964 // Restart the dispatch cycle using the fallback key.
4965 keyEntry->eventTime = event.getEventTime();
4966 keyEntry->deviceId = event.getDeviceId();
4967 keyEntry->source = event.getSource();
4968 keyEntry->displayId = event.getDisplayId();
4969 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4970 keyEntry->keyCode = fallbackKeyCode;
4971 keyEntry->scanCode = event.getScanCode();
4972 keyEntry->metaState = event.getMetaState();
4973 keyEntry->repeatCount = event.getRepeatCount();
4974 keyEntry->downTime = event.getDownTime();
4975 keyEntry->syntheticRepeat = false;
4976
4977#if DEBUG_OUTBOUND_EVENT_DETAILS
4978 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004979 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4980 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004981#endif
4982 return true; // restart the event
4983 } else {
4984#if DEBUG_OUTBOUND_EVENT_DETAILS
4985 ALOGD("Unhandled key event: No fallback key.");
4986#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004987
4988 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004989 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990 }
4991 }
4992 return false;
4993}
4994
4995bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004996 DispatchEntry* dispatchEntry,
4997 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998 return false;
4999}
5000
5001void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5002 mLock.unlock();
5003
5004 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5005
5006 mLock.lock();
5007}
5008
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005009KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5010 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005011 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005012 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5013 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005014 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015}
5016
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005017void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5018 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005019 // TODO Write some statistics about how long we spend waiting.
5020}
5021
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005022/**
5023 * Report the touch event latency to the statsd server.
5024 * Input events are reported for statistics if:
5025 * - This is a touchscreen event
5026 * - InputFilter is not enabled
5027 * - Event is not injected or synthesized
5028 *
5029 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5030 * from getting aggregated with the "old" data.
5031 */
5032void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5033 REQUIRES(mLock) {
5034 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5035 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5036 if (!reportForStatistics) {
5037 return;
5038 }
5039
5040 if (mTouchStatistics.shouldReport()) {
5041 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5042 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5043 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5044 mTouchStatistics.reset();
5045 }
5046 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5047 mTouchStatistics.addValue(latencyMicros);
5048}
5049
Michael Wrightd02c5b62014-02-10 15:10:22 -08005050void InputDispatcher::traceInboundQueueLengthLocked() {
5051 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005052 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053 }
5054}
5055
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005056void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005057 if (ATRACE_ENABLED()) {
5058 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005059 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005060 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061 }
5062}
5063
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005064void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065 if (ATRACE_ENABLED()) {
5066 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005067 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005068 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069 }
5070}
5071
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005072void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005073 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005074
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005075 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005076 dumpDispatchStateLocked(dump);
5077
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005078 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005079 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005080 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081 }
5082}
5083
5084void InputDispatcher::monitor() {
5085 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005086 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005087 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005088 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089}
5090
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005091/**
5092 * Wake up the dispatcher and wait until it processes all events and commands.
5093 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5094 * this method can be safely called from any thread, as long as you've ensured that
5095 * the work you are interested in completing has already been queued.
5096 */
5097bool InputDispatcher::waitForIdle() {
5098 /**
5099 * Timeout should represent the longest possible time that a device might spend processing
5100 * events and commands.
5101 */
5102 constexpr std::chrono::duration TIMEOUT = 100ms;
5103 std::unique_lock lock(mLock);
5104 mLooper->wake();
5105 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5106 return result == std::cv_status::no_timeout;
5107}
5108
Garfield Tane84e6f92019-08-29 17:28:41 -07005109} // namespace android::inputdispatcher